]> wimlib.net Git - wimlib/blob - src/update_image.c
f14775a714664a5b19c040cbce6a95e61f59800b
[wimlib] / src / update_image.c
1 /*
2  * update_image.c - Update a WIM image.
3  */
4
5 /*
6  * Copyright (C) 2013, 2014 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #include "wimlib/capture.h"
29 #include "wimlib/dentry.h"
30 #include "wimlib/encoding.h"
31 #include "wimlib/endianness.h"
32 #include "wimlib/error.h"
33 #include "wimlib/lookup_table.h"
34 #include "wimlib/metadata.h"
35 #ifdef WITH_NTFS_3G
36 #  include "wimlib/ntfs_3g.h" /* for do_ntfs_umount() */
37 #endif
38 #include "wimlib/paths.h"
39 #include "wimlib/progress.h"
40 #include "wimlib/xml.h"
41
42 #include <errno.h>
43 #include <sys/stat.h>
44 #include <stdlib.h>
45
46 #ifdef HAVE_ALLOCA_H
47 #  include <alloca.h>
48 #endif
49
50 /* Saved specification of a "primitive" update operation that was performed.  */
51 struct update_primitive {
52         enum {
53                 /* Unlinked a dentry from its parent directory.  */
54                 UNLINK_DENTRY,
55
56                 /* Linked a dentry into its parent directory.  */
57                 LINK_DENTRY,
58
59                 /* Changed the file name of a dentry.  */
60                 CHANGE_FILE_NAME,
61
62                 /* Changed the short name of a dentry.  */
63                 CHANGE_SHORT_NAME,
64         } type;
65
66         union {
67                 /* For UNLINK_DENTRY and LINK_DENTRY operations  */
68                 struct {
69                         /* Dentry that was linked or unlinked.  */
70                         struct wim_dentry *subject;
71
72                         /* For link operations, the directory into which
73                          * @subject was linked, or NULL if @subject was set as
74                          * the root of the image.
75                          *
76                          * For unlink operations, the directory from which
77                          * @subject was unlinked, or NULL if @subject was unset
78                          * as the root of the image.  */
79                         struct wim_dentry *parent;
80                 } link;
81
82                 /* For CHANGE_FILE_NAME and CHANGE_SHORT_NAME operations  */
83                 struct {
84                         /* Dentry that had its name changed.  */
85                         struct wim_dentry *subject;
86
87                         /* The old name.  */
88                         utf16lechar *old_name;
89                 } name;
90         };
91 };
92
93 /* Chronological list of primitive operations that were executed for a single
94  * logical update command, such as 'add', 'delete', or 'rename'.  */
95 struct update_primitive_list {
96         struct update_primitive *entries;
97         struct update_primitive inline_entries[4];
98         size_t num_entries;
99         size_t num_alloc_entries;
100 };
101
102 /* Journal for managing the executing of zero or more logical update commands,
103  * such as 'add', 'delete', or 'rename'.  This allows either committing or
104  * rolling back the commands.  */
105 struct update_command_journal {
106         /* Number of update commands this journal contains.  */
107         size_t num_cmds;
108
109         /* Index of currently executing update command.  */
110         size_t cur_cmd;
111
112         /* Location of the WIM image's root pointer.  */
113         struct wim_dentry **root_p;
114
115         /* Pointer to the lookup table of the WIM (may needed for rollback)  */
116         struct wim_lookup_table *lookup_table;
117
118         /* List of dentries that are currently unlinked from the WIM image.
119          * These must be freed when no longer needed for commit or rollback.  */
120         struct list_head orphans;
121
122         /* Per-command logs.  */
123         struct update_primitive_list cmd_prims[];
124 };
125
126 static void
127 init_update_primitive_list(struct update_primitive_list *l)
128 {
129         l->entries = l->inline_entries;
130         l->num_entries = 0;
131         l->num_alloc_entries = ARRAY_LEN(l->inline_entries);
132 }
133
134 /* Allocates a new journal for managing the execution of up to @num_cmds update
135  * commands.  */
136 static struct update_command_journal *
137 new_update_command_journal(size_t num_cmds, struct wim_dentry **root_p,
138                            struct wim_lookup_table *lookup_table)
139 {
140         struct update_command_journal *j;
141
142         j = MALLOC(sizeof(*j) + num_cmds * sizeof(j->cmd_prims[0]));
143         if (j) {
144                 j->num_cmds = num_cmds;
145                 j->cur_cmd = 0;
146                 j->root_p = root_p;
147                 j->lookup_table = lookup_table;
148                 INIT_LIST_HEAD(&j->orphans);
149                 for (size_t i = 0; i < num_cmds; i++)
150                         init_update_primitive_list(&j->cmd_prims[i]);
151         }
152         return j;
153 }
154
155 /* Don't call this directly; use commit_update() or rollback_update() instead.
156  */
157 static void
158 free_update_command_journal(struct update_command_journal *j)
159 {
160         struct wim_dentry *orphan;
161
162         /* Free orphaned dentry trees  */
163         while (!list_empty(&j->orphans)) {
164                 orphan = list_first_entry(&j->orphans,
165                                           struct wim_dentry, tmp_list);
166                 list_del(&orphan->tmp_list);
167                 free_dentry_tree(orphan, j->lookup_table);
168         }
169
170         for (size_t i = 0; i < j->num_cmds; i++)
171                 if (j->cmd_prims[i].entries != j->cmd_prims[i].inline_entries)
172                         FREE(j->cmd_prims[i].entries);
173         FREE(j);
174 }
175
176 /* Add the entry @prim to the update command journal @j.  */
177 static int
178 record_update_primitive(struct update_command_journal *j,
179                         struct update_primitive prim)
180 {
181         struct update_primitive_list *l;
182
183         l = &j->cmd_prims[j->cur_cmd];
184
185         if (l->num_entries == l->num_alloc_entries) {
186                 struct update_primitive *new_entries;
187                 size_t new_num_alloc_entries;
188                 size_t new_size;
189
190                 new_num_alloc_entries = l->num_alloc_entries * 2;
191                 new_size = new_num_alloc_entries * sizeof(new_entries[0]);
192                 if (l->entries == l->inline_entries) {
193                         new_entries = MALLOC(new_size);
194                         if (!new_entries)
195                                 return WIMLIB_ERR_NOMEM;
196                         memcpy(new_entries, l->inline_entries,
197                                sizeof(l->inline_entries));
198                 } else {
199                         new_entries = REALLOC(l->entries, new_size);
200                         if (!new_entries)
201                                 return WIMLIB_ERR_NOMEM;
202                 }
203                 l->entries = new_entries;
204                 l->num_alloc_entries = new_num_alloc_entries;
205         }
206         l->entries[l->num_entries++] = prim;
207         return 0;
208 }
209
210 static void
211 do_unlink(struct wim_dentry *subject, struct wim_dentry *parent,
212           struct wim_dentry **root_p)
213 {
214         if (parent) {
215                 /* Unlink @subject from its @parent.  */
216                 wimlib_assert(subject->d_parent == parent);
217                 unlink_dentry(subject);
218         } else {
219                 /* Unset @subject as the root of the image.  */
220                 *root_p = NULL;
221         }
222         subject->d_parent = subject;
223 }
224
225 static void
226 do_link(struct wim_dentry *subject, struct wim_dentry *parent,
227         struct wim_dentry **root_p)
228 {
229         if (parent) {
230                 /* Link @subject to its @parent  */
231                 struct wim_dentry *existing;
232
233                 existing = dentry_add_child(parent, subject);
234                 wimlib_assert(!existing);
235         } else {
236                 /* Set @subject as root of the image  */
237                 *root_p = subject;
238         }
239 }
240
241 /* Undo a link operation.  */
242 static void
243 rollback_link(struct wim_dentry *subject, struct wim_dentry *parent,
244               struct wim_dentry **root_p, struct list_head *orphans)
245 {
246         /* Unlink is the opposite of link  */
247         do_unlink(subject, parent, root_p);
248
249         /* @subject is now unlinked.  Add it to orphans. */
250         list_add(&subject->tmp_list, orphans);
251         subject->is_orphan = 1;
252 }
253
254 /* Undo an unlink operation.  */
255 static void
256 rollback_unlink(struct wim_dentry *subject, struct wim_dentry *parent,
257                 struct wim_dentry **root_p)
258 {
259         /* Link is the opposite of unlink  */
260         do_link(subject, parent, root_p);
261
262         /* @subject is no longer unlinked.  Delete it from orphans. */
263         list_del(&subject->tmp_list);
264         subject->is_orphan = 0;
265 }
266
267 /* Rollback a name change operation.  */
268 static void
269 rollback_name_change(utf16lechar *old_name,
270                      utf16lechar **name_ptr, u16 *name_nbytes_ptr)
271 {
272         /* Free the new name, then replace it with the old name.  */
273         FREE(*name_ptr);
274         if (old_name) {
275                 *name_ptr = old_name;
276                 *name_nbytes_ptr = utf16le_strlen(old_name);
277         } else {
278                 *name_ptr = NULL;
279                 *name_nbytes_ptr = 0;
280         }
281 }
282
283 /* Rollback a primitive update operation.  */
284 static void
285 rollback_update_primitive(const struct update_primitive *prim,
286                           struct wim_dentry **root_p,
287                           struct list_head *orphans)
288 {
289         switch (prim->type) {
290         case LINK_DENTRY:
291                 rollback_link(prim->link.subject, prim->link.parent, root_p,
292                               orphans);
293                 break;
294         case UNLINK_DENTRY:
295                 rollback_unlink(prim->link.subject, prim->link.parent, root_p);
296                 break;
297         case CHANGE_FILE_NAME:
298                 rollback_name_change(prim->name.old_name,
299                                      &prim->name.subject->file_name,
300                                      &prim->name.subject->file_name_nbytes);
301                 break;
302         case CHANGE_SHORT_NAME:
303                 rollback_name_change(prim->name.old_name,
304                                      &prim->name.subject->short_name,
305                                      &prim->name.subject->short_name_nbytes);
306                 break;
307         }
308 }
309
310 /* Rollback a logical update command  */
311 static void
312 rollback_update_command(const struct update_primitive_list *l,
313                         struct wim_dentry **root_p,
314                         struct list_head *orphans)
315 {
316         size_t i = l->num_entries;
317
318         /* Rollback each primitive operation, in reverse order.  */
319         while (i--)
320                 rollback_update_primitive(&l->entries[i], root_p, orphans);
321 }
322
323 /****************************************************************************/
324
325 /* Link @subject into the directory @parent; or, if @parent is NULL, set
326  * @subject as the root of the WIM image.
327  *
328  * This is the journaled version, so it can be rolled back.  */
329 static int
330 journaled_link(struct update_command_journal *j,
331                struct wim_dentry *subject, struct wim_dentry *parent)
332 {
333         struct update_primitive prim;
334         int ret;
335
336         prim.type = LINK_DENTRY;
337         prim.link.subject = subject;
338         prim.link.parent = parent;
339
340         ret = record_update_primitive(j, prim);
341         if (ret)
342                 return ret;
343
344         do_link(subject, parent, j->root_p);
345
346         if (subject->is_orphan) {
347                 list_del(&subject->tmp_list);
348                 subject->is_orphan = 0;
349         }
350         return 0;
351 }
352
353 /* Unlink @subject from the WIM image.
354  *
355  * This is the journaled version, so it can be rolled back.  */
356 static int
357 journaled_unlink(struct update_command_journal *j, struct wim_dentry *subject)
358 {
359         struct wim_dentry *parent;
360         struct update_primitive prim;
361         int ret;
362
363         if (dentry_is_root(subject))
364                 parent = NULL;
365         else
366                 parent = subject->d_parent;
367
368         prim.type = UNLINK_DENTRY;
369         prim.link.subject = subject;
370         prim.link.parent = parent;
371
372         ret = record_update_primitive(j, prim);
373         if (ret)
374                 return ret;
375
376         do_unlink(subject, parent, j->root_p);
377
378         list_add(&subject->tmp_list, &j->orphans);
379         subject->is_orphan = 1;
380         return 0;
381 }
382
383 /* Change the name of @dentry to @new_name_tstr.
384  *
385  * This is the journaled version, so it can be rolled back.  */
386 static int
387 journaled_change_name(struct update_command_journal *j,
388                       struct wim_dentry *dentry, const tchar *new_name_tstr)
389 {
390         int ret;
391         utf16lechar *new_name;
392         size_t new_name_nbytes;
393         struct update_primitive prim;
394
395         /* Set the long name.  */
396         ret = tstr_to_utf16le(new_name_tstr,
397                               tstrlen(new_name_tstr) * sizeof(tchar),
398                               &new_name, &new_name_nbytes);
399         if (ret)
400                 return ret;
401
402         prim.type = CHANGE_FILE_NAME;
403         prim.name.subject = dentry;
404         prim.name.old_name = dentry->file_name;
405         ret = record_update_primitive(j, prim);
406         if (ret) {
407                 FREE(new_name);
408                 return ret;
409         }
410
411         dentry->file_name = new_name;
412         dentry->file_name_nbytes = new_name_nbytes;
413
414         /* Clear the short name.  */
415         prim.type = CHANGE_SHORT_NAME;
416         prim.name.subject = dentry;
417         prim.name.old_name = dentry->short_name;
418         ret = record_update_primitive(j, prim);
419         if (ret)
420                 return ret;
421
422         dentry->short_name = NULL;
423         dentry->short_name_nbytes = 0;
424         return 0;
425 }
426
427 static void
428 next_command(struct update_command_journal *j)
429 {
430         j->cur_cmd++;
431 }
432
433 static void
434 commit_update(struct update_command_journal *j)
435 {
436         for (size_t i = 0; i < j->num_cmds; i++)
437         {
438                 for (size_t k = 0; k < j->cmd_prims[i].num_entries; k++)
439                 {
440                         if (j->cmd_prims[i].entries[k].type == CHANGE_FILE_NAME ||
441                             j->cmd_prims[i].entries[k].type == CHANGE_SHORT_NAME)
442                         {
443                                 FREE(j->cmd_prims[i].entries[k].name.old_name);
444                         }
445                 }
446         }
447         free_update_command_journal(j);
448 }
449
450 static void
451 rollback_update(struct update_command_journal *j)
452 {
453         /* Rollback each logical update command, in reverse order.  */
454         size_t i = j->cur_cmd;
455         if (i < j->num_cmds)
456                 i++;
457         while (i--)
458                 rollback_update_command(&j->cmd_prims[i], j->root_p, &j->orphans);
459         free_update_command_journal(j);
460 }
461
462 static int
463 handle_conflict(struct wim_dentry *branch, struct wim_dentry *existing,
464                 struct update_command_journal *j,
465                 int add_flags,
466                 wimlib_progress_func_t progfunc, void *progctx)
467 {
468         bool branch_is_dir = dentry_is_directory(branch);
469         bool existing_is_dir = dentry_is_directory(existing);
470
471         if (branch_is_dir != existing_is_dir) {
472                 if (existing_is_dir)  {
473                         ERROR("\"%"TS"\" is a directory!\n"
474                               "        Specify the path at which "
475                               "to place the file inside this directory.",
476                               dentry_full_path(existing));
477                         return WIMLIB_ERR_IS_DIRECTORY;
478                 } else {
479                         ERROR("Can't place directory at \"%"TS"\" because "
480                               "a nondirectory file already exists there!",
481                               dentry_full_path(existing));
482                         return WIMLIB_ERR_NOTDIR;
483                 }
484         }
485
486         if (branch_is_dir) {
487                 /* Directory overlay  */
488                 while (dentry_has_children(branch)) {
489                         struct wim_dentry *new_child;
490                         struct wim_dentry *existing_child;
491                         int ret;
492
493                         new_child = dentry_any_child(branch);
494
495                         existing_child =
496                                 get_dentry_child_with_utf16le_name(existing,
497                                                                    new_child->file_name,
498                                                                    new_child->file_name_nbytes,
499                                                                    WIMLIB_CASE_PLATFORM_DEFAULT);
500                         unlink_dentry(new_child);
501                         if (existing_child) {
502                                 ret = handle_conflict(new_child, existing_child,
503                                                       j, add_flags,
504                                                       progfunc, progctx);
505                         } else {
506                                 ret = journaled_link(j, new_child, existing);
507                         }
508                         if (ret) {
509                                 dentry_add_child(branch, new_child);
510                                 return ret;
511                         }
512                 }
513                 free_dentry(branch);
514                 return 0;
515         } else if (add_flags & WIMLIB_ADD_FLAG_NO_REPLACE) {
516                 /* Can't replace nondirectory file  */
517                 ERROR("Refusing to overwrite nondirectory file \"%"TS"\"",
518                       dentry_full_path(existing));
519                 return WIMLIB_ERR_INVALID_OVERLAY;
520         } else {
521                 /* Replace nondirectory file  */
522                 struct wim_dentry *parent;
523                 int ret;
524
525                 parent = existing->d_parent;
526
527                 ret = calculate_dentry_full_path(existing);
528                 if (ret)
529                         return ret;
530
531                 if (add_flags & WIMLIB_ADD_FLAG_VERBOSE) {
532                         union wimlib_progress_info info;
533
534                         info.replace.path_in_wim = existing->_full_path;
535                         ret = call_progress(progfunc,
536                                             WIMLIB_PROGRESS_MSG_REPLACE_FILE_IN_WIM,
537                                             &info, progctx);
538                         if (ret)
539                                 return ret;
540                 }
541
542                 ret = journaled_unlink(j, existing);
543                 if (ret)
544                         return ret;
545
546                 return journaled_link(j, branch, parent);
547         }
548 }
549
550 static int
551 do_attach_branch(struct wim_dentry *branch, const utf16lechar *target,
552                  struct update_command_journal *j,
553                  int add_flags, wimlib_progress_func_t progfunc, void *progctx)
554 {
555         struct wim_dentry *parent;
556         struct wim_dentry *existing;
557         const utf16lechar empty_name[1] = {0};
558         const utf16lechar *cur_component_name;
559         size_t cur_component_nbytes;
560         const utf16lechar *next_component_name;
561         int ret;
562
563         /* Attempt to create root directory before proceeding to the "real"
564          * first component  */
565         parent = NULL;
566         existing = *j->root_p;
567         cur_component_name = empty_name;
568         cur_component_nbytes = 0;
569
570         /* Skip leading slashes  */
571         next_component_name = target;
572         while (*next_component_name == cpu_to_le16(WIM_PATH_SEPARATOR))
573                 next_component_name++;
574
575         while (*next_component_name) { /* While not the last component ... */
576                 const utf16lechar *end;
577
578                 if (existing) {
579                         /* Descend into existing directory  */
580                         if (!dentry_is_directory(existing)) {
581                                 ERROR("\"%"TS"\" in the WIM image "
582                                       "is not a directory!",
583                                       dentry_full_path(existing));
584                                 return WIMLIB_ERR_NOTDIR;
585                         }
586                 } else {
587                         /* A parent directory of the target didn't exist.  Make
588                          * the way by creating a filler directory.  */
589                         struct wim_dentry *filler;
590
591                         ret = new_filler_directory(&filler);
592                         if (ret)
593                                 return ret;
594                         ret = dentry_set_name_utf16le(filler,
595                                                       cur_component_name,
596                                                       cur_component_nbytes);
597                         if (ret) {
598                                 free_dentry(filler);
599                                 return ret;
600                         }
601                         ret = journaled_link(j, filler, parent);
602                         if (ret) {
603                                 free_dentry(filler);
604                                 return ret;
605                         }
606                         existing = filler;
607                 }
608
609                 /* Advance to next component  */
610
611                 cur_component_name = next_component_name;
612                 end = cur_component_name + 1;
613                 while (*end && *end != cpu_to_le16(WIM_PATH_SEPARATOR))
614                         end++;
615
616                 next_component_name = end;
617                 if (*end) {
618                         /* There will still be more components after this.  */
619                         do {
620                         } while (*++next_component_name == cpu_to_le16(WIM_PATH_SEPARATOR));
621                         wimlib_assert(*next_component_name);  /* No trailing slashes  */
622                 } else {
623                         /* This will be the last component  */
624                         next_component_name = end;
625                 }
626                 parent = existing;
627                 cur_component_nbytes = (end - cur_component_name) * sizeof(utf16lechar);
628                 existing = get_dentry_child_with_utf16le_name(
629                                         parent,
630                                         cur_component_name,
631                                         cur_component_nbytes,
632                                         WIMLIB_CASE_PLATFORM_DEFAULT);
633         }
634
635         /* Last component  */
636         if (existing) {
637                 return handle_conflict(branch, existing, j, add_flags,
638                                        progfunc, progctx);
639         } else {
640                 return journaled_link(j, branch, parent);
641         }
642 }
643
644 /*
645  * Place the directory entry tree @branch at the path @target_tstr in the WIM
646  * image.
647  *
648  * @target_tstr cannot contain trailing slashes, and all path separators must be
649  * WIM_PATH_SEPARATOR.
650  *
651  * On success, @branch is committed to the journal @j.
652  * Otherwise @branch is freed.
653  *
654  * The relevant @add_flags are WIMLIB_ADD_FLAG_NO_REPLACE and
655  * WIMLIB_ADD_FLAG_VERBOSE.
656  */
657 static int
658 attach_branch(struct wim_dentry *branch, const tchar *target_tstr,
659               struct update_command_journal *j, int add_flags,
660               wimlib_progress_func_t progfunc, void *progctx)
661 {
662         int ret;
663         const utf16lechar *target;
664
665         ret = 0;
666         if (unlikely(!branch))
667                 goto out;
668
669         ret = tstr_get_utf16le(target_tstr, &target);
670         if (ret)
671                 goto out_free_branch;
672
673         BUILD_BUG_ON(WIM_PATH_SEPARATOR != OS_PREFERRED_PATH_SEPARATOR);
674         ret = dentry_set_name(branch, path_basename(target_tstr));
675         if (ret)
676                 goto out_free_target;
677
678         ret = do_attach_branch(branch, target, j, add_flags, progfunc, progctx);
679         if (ret)
680                 goto out_free_target;
681         /* branch was successfully committed to the journal  */
682         branch = NULL;
683 out_free_target:
684         tstr_put_utf16le(target);
685 out_free_branch:
686         free_dentry_tree(branch, j->lookup_table);
687 out:
688         return ret;
689 }
690
691 static const char wincfg[] =
692 "[ExclusionList]\n"
693 "/$ntfs.log\n"
694 "/hiberfil.sys\n"
695 "/pagefile.sys\n"
696 "/swapfile.sys\n"
697 "/System Volume Information\n"
698 "/RECYCLER\n"
699 "/Windows/CSC\n";
700
701 static const tchar *wimboot_cfgfile =
702             WIMLIB_WIM_PATH_SEPARATOR_STRING T("Windows")
703             WIMLIB_WIM_PATH_SEPARATOR_STRING T("System32")
704             WIMLIB_WIM_PATH_SEPARATOR_STRING T("WimBootCompress.ini");
705
706 static int
707 get_capture_config(const tchar *config_file, struct capture_config *config,
708                    int add_flags, const tchar *fs_source_path)
709 {
710         int ret;
711         tchar *tmp_config_file = NULL;
712
713         memset(config, 0, sizeof(*config));
714
715         /* For WIMBoot capture, check for default capture configuration file
716          * unless one was explicitly specified.  */
717         if (!config_file && (add_flags & WIMLIB_ADD_FLAG_WIMBOOT)) {
718
719                 /* XXX: Handle loading file correctly when in NTFS volume.  */
720
721                 size_t len = tstrlen(fs_source_path) +
722                              tstrlen(wimboot_cfgfile);
723                 tmp_config_file = MALLOC((len + 1) * sizeof(tchar));
724                 struct stat st;
725
726                 tsprintf(tmp_config_file, T("%"TS"%"TS),
727                          fs_source_path, wimboot_cfgfile);
728                 if (!tstat(tmp_config_file, &st)) {
729                         config_file = tmp_config_file;
730                         add_flags &= ~WIMLIB_ADD_FLAG_WINCONFIG;
731                 } else {
732                         WARNING("\"%"TS"\" does not exist.\n"
733                                 "          Using default capture configuration!",
734                                 tmp_config_file);
735                 }
736         }
737
738         if (add_flags & WIMLIB_ADD_FLAG_WINCONFIG) {
739                 /* Use Windows default.  */
740                 if (config_file)
741                         return WIMLIB_ERR_INVALID_PARAM;
742                 ret = read_capture_config(T("wincfg"), wincfg,
743                                           sizeof(wincfg) - 1, config);
744         } else if (config_file) {
745                 /* Use the specified configuration file.  */
746                 ret = read_capture_config(config_file, NULL, 0, config);
747         } else {
748                 /* ... Or don't use any configuration file at all.  No files
749                  * will be excluded from capture, all files will be compressed,
750                  * etc.  */
751                 ret = 0;
752         }
753         FREE(tmp_config_file);
754         return ret;
755 }
756
757 static int
758 execute_add_command(struct update_command_journal *j,
759                     WIMStruct *wim,
760                     const struct wimlib_update_command *add_cmd,
761                     struct wim_inode_table *inode_table,
762                     struct wim_sd_set *sd_set,
763                     struct list_head *unhashed_streams)
764 {
765         int ret;
766         int add_flags;
767         tchar *fs_source_path;
768         tchar *wim_target_path;
769         const tchar *config_file;
770         struct add_image_params params;
771         struct capture_config config;
772         capture_tree_t capture_tree = platform_default_capture_tree;
773 #ifdef WITH_NTFS_3G
774         struct _ntfs_volume *ntfs_vol = NULL;
775 #endif
776         void *extra_arg = NULL;
777         struct wim_dentry *branch;
778
779         add_flags = add_cmd->add.add_flags;
780         fs_source_path = add_cmd->add.fs_source_path;
781         wim_target_path = add_cmd->add.wim_target_path;
782         config_file = add_cmd->add.config_file;
783
784         DEBUG("fs_source_path=\"%"TS"\", wim_target_path=\"%"TS"\", add_flags=%#x",
785               fs_source_path, wim_target_path, add_flags);
786
787         memset(&params, 0, sizeof(params));
788
789 #ifdef WITH_NTFS_3G
790         if (add_flags & WIMLIB_ADD_FLAG_NTFS) {
791                 capture_tree = build_dentry_tree_ntfs;
792                 extra_arg = &ntfs_vol;
793                 if (wim_get_current_image_metadata(wim)->ntfs_vol != NULL) {
794                         ERROR("NTFS volume already set");
795                         ret = WIMLIB_ERR_INVALID_PARAM;
796                         goto out;
797                 }
798         }
799 #endif
800
801         ret = get_capture_config(config_file, &config,
802                                  add_flags, fs_source_path);
803         if (ret)
804                 goto out;
805
806         params.lookup_table = wim->lookup_table;
807         params.unhashed_streams = unhashed_streams;
808         params.inode_table = inode_table;
809         params.sd_set = sd_set;
810         params.config = &config;
811         params.add_flags = add_flags;
812         params.extra_arg = extra_arg;
813
814         params.progfunc = wim->progfunc;
815         params.progctx = wim->progctx;
816         params.progress.scan.source = fs_source_path;
817         params.progress.scan.wim_target_path = wim_target_path;
818         ret = call_progress(params.progfunc, WIMLIB_PROGRESS_MSG_SCAN_BEGIN,
819                             &params.progress, params.progctx);
820         if (ret)
821                 goto out_destroy_config;
822
823         if (WIMLIB_IS_WIM_ROOT_PATH(wim_target_path))
824                 params.add_flags |= WIMLIB_ADD_FLAG_ROOT;
825         ret = (*capture_tree)(&branch, fs_source_path, &params);
826         if (ret)
827                 goto out_destroy_config;
828
829         ret = call_progress(params.progfunc, WIMLIB_PROGRESS_MSG_SCAN_END,
830                             &params.progress, params.progctx);
831         if (ret) {
832                 free_dentry_tree(branch, wim->lookup_table);
833                 goto out_cleanup_after_capture;
834         }
835
836         if (WIMLIB_IS_WIM_ROOT_PATH(wim_target_path) &&
837             branch && !dentry_is_directory(branch))
838         {
839                 ERROR("\"%"TS"\" is not a directory!", fs_source_path);
840                 ret = WIMLIB_ERR_NOTDIR;
841                 free_dentry_tree(branch, wim->lookup_table);
842                 goto out_cleanup_after_capture;
843         }
844
845         ret = attach_branch(branch, wim_target_path, j,
846                             add_flags, params.progfunc, params.progctx);
847         if (ret)
848                 goto out_cleanup_after_capture;
849
850         if (config_file && (add_flags & WIMLIB_ADD_FLAG_WIMBOOT) &&
851             WIMLIB_IS_WIM_ROOT_PATH(wim_target_path))
852         {
853                 params.add_flags = 0;
854                 params.progfunc = NULL;
855                 params.config = NULL;
856
857                 /* If a capture configuration file was explicitly specified when
858                  * capturing an image in WIMBoot mode, save it as
859                  * /Windows/System32/WimBootCompress.ini in the WIM image. */
860                 ret = platform_default_capture_tree(&branch, config_file, &params);
861                 if (ret)
862                         goto out_cleanup_after_capture;
863
864                 ret = attach_branch(branch, wimboot_cfgfile, j, 0, NULL, NULL);
865                 if (ret)
866                         goto out_cleanup_after_capture;
867         }
868
869 #ifdef WITH_NTFS_3G
870         wim_get_current_image_metadata(wim)->ntfs_vol = ntfs_vol;
871 #endif
872         if (add_flags & WIMLIB_ADD_FLAG_RPFIX)
873                 wim->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
874         ret = 0;
875         goto out_destroy_config;
876 out_cleanup_after_capture:
877 #ifdef WITH_NTFS_3G
878         if (ntfs_vol)
879                 do_ntfs_umount(ntfs_vol);
880 #endif
881 out_destroy_config:
882         destroy_capture_config(&config);
883 out:
884         return ret;
885 }
886
887 static int
888 execute_delete_command(struct update_command_journal *j,
889                        WIMStruct *wim,
890                        const struct wimlib_update_command *delete_cmd)
891 {
892         int flags;
893         const tchar *wim_path;
894         struct wim_dentry *tree;
895
896         flags = delete_cmd->delete_.delete_flags;
897         wim_path = delete_cmd->delete_.wim_path;
898
899         DEBUG("Deleting WIM path \"%"TS"\" (flags=%#x)", wim_path, flags);
900
901         tree = get_dentry(wim, wim_path, WIMLIB_CASE_PLATFORM_DEFAULT);
902         if (!tree) {
903                 /* Path to delete does not exist in the WIM. */
904                 if (flags & WIMLIB_DELETE_FLAG_FORCE) {
905                         return 0;
906                 } else {
907                         ERROR("Path \"%"TS"\" does not exist in WIM image %d",
908                               wim_path, wim->current_image);
909                         return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
910                 }
911         }
912
913         if (dentry_is_directory(tree) && !(flags & WIMLIB_DELETE_FLAG_RECURSIVE)) {
914                 ERROR("Path \"%"TS"\" in WIM image %d is a directory "
915                       "but a recursive delete was not requested",
916                       wim_path, wim->current_image);
917                 return WIMLIB_ERR_IS_DIRECTORY;
918         }
919
920         return journaled_unlink(j, tree);
921 }
922
923 static int
924 free_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
925 {
926         FREE(dentry->_full_path);
927         dentry->_full_path = NULL;
928         return 0;
929 }
930
931 /* Is @d1 a (possibly nonproper) ancestor of @d2?  */
932 static bool
933 is_ancestor(const struct wim_dentry *d1, const struct wim_dentry *d2)
934 {
935         for (;;) {
936                 if (d2 == d1)
937                         return true;
938                 if (dentry_is_root(d2))
939                         return false;
940                 d2 = d2->d_parent;
941         }
942 }
943
944 /* Rename a file or directory in the WIM.
945  *
946  * This returns a -errno value.
947  *
948  * The journal @j is optional.
949  */
950 int
951 rename_wim_path(WIMStruct *wim, const tchar *from, const tchar *to,
952                 CASE_SENSITIVITY_TYPE case_type,
953                 struct update_command_journal *j)
954 {
955         struct wim_dentry *src;
956         struct wim_dentry *dst;
957         struct wim_dentry *parent_of_dst;
958         int ret;
959
960         /* This rename() implementation currently only supports actual files
961          * (not alternate data streams) */
962
963         src = get_dentry(wim, from, case_type);
964         if (!src)
965                 return -errno;
966
967         dst = get_dentry(wim, to, case_type);
968
969         if (dst) {
970                 /* Destination file exists */
971
972                 if (src == dst) /* Same file */
973                         return 0;
974
975                 if (!dentry_is_directory(src)) {
976                         /* Cannot rename non-directory to directory. */
977                         if (dentry_is_directory(dst))
978                                 return -EISDIR;
979                 } else {
980                         /* Cannot rename directory to a non-directory or a non-empty
981                          * directory */
982                         if (!dentry_is_directory(dst))
983                                 return -ENOTDIR;
984                         if (dentry_has_children(dst))
985                                 return -ENOTEMPTY;
986                 }
987                 parent_of_dst = dst->d_parent;
988         } else {
989                 /* Destination does not exist */
990                 parent_of_dst = get_parent_dentry(wim, to, case_type);
991                 if (!parent_of_dst)
992                         return -errno;
993
994                 if (!dentry_is_directory(parent_of_dst))
995                         return -ENOTDIR;
996         }
997
998         /* @src can't be an ancestor of @dst.  Otherwise we're unlinking @src
999          * from the tree and creating a loop...  */
1000         if (is_ancestor(src, parent_of_dst))
1001                 return -EBUSY;
1002
1003         if (j) {
1004                 if (dst)
1005                         if (journaled_unlink(j, dst))
1006                                 return -ENOMEM;
1007                 if (journaled_unlink(j, src))
1008                         return -ENOMEM;
1009                 if (journaled_change_name(j, src, path_basename(to)))
1010                         return -ENOMEM;
1011                 if (journaled_link(j, src, parent_of_dst))
1012                         return -ENOMEM;
1013         } else {
1014                 ret = dentry_set_name(src, path_basename(to));
1015                 if (ret)
1016                         return -ENOMEM;
1017                 if (dst) {
1018                         unlink_dentry(dst);
1019                         free_dentry_tree(dst, wim->lookup_table);
1020                 }
1021                 unlink_dentry(src);
1022                 dentry_add_child(parent_of_dst, src);
1023         }
1024         if (src->_full_path)
1025                 for_dentry_in_tree(src, free_dentry_full_path, NULL);
1026         return 0;
1027 }
1028
1029
1030 static int
1031 execute_rename_command(struct update_command_journal *j,
1032                        WIMStruct *wim,
1033                        const struct wimlib_update_command *rename_cmd)
1034 {
1035         int ret;
1036
1037         ret = rename_wim_path(wim, rename_cmd->rename.wim_source_path,
1038                               rename_cmd->rename.wim_target_path,
1039                               WIMLIB_CASE_PLATFORM_DEFAULT, j);
1040         if (ret) {
1041                 ret = -ret;
1042                 errno = ret;
1043                 ERROR_WITH_ERRNO("Can't rename \"%"TS"\" to \"%"TS"\"",
1044                                  rename_cmd->rename.wim_source_path,
1045                                  rename_cmd->rename.wim_target_path);
1046                 switch (ret) {
1047                 case ENOMEM:
1048                         ret = WIMLIB_ERR_NOMEM;
1049                         break;
1050                 case ENOTDIR:
1051                         ret = WIMLIB_ERR_NOTDIR;
1052                         break;
1053                 case ENOTEMPTY:
1054                 case EBUSY:
1055                         /* XXX: EBUSY is returned when the rename would create a
1056                          * loop.  It maybe should have its own error code.  */
1057                         ret = WIMLIB_ERR_NOTEMPTY;
1058                         break;
1059                 case EISDIR:
1060                         ret = WIMLIB_ERR_IS_DIRECTORY;
1061                         break;
1062                 case ENOENT:
1063                 default:
1064                         ret = WIMLIB_ERR_PATH_DOES_NOT_EXIST;
1065                         break;
1066                 }
1067         }
1068         return ret;
1069 }
1070
1071 static inline const tchar *
1072 update_op_to_str(int op)
1073 {
1074         switch (op) {
1075         case WIMLIB_UPDATE_OP_ADD:
1076                 return T("add");
1077         case WIMLIB_UPDATE_OP_DELETE:
1078                 return T("delete");
1079         case WIMLIB_UPDATE_OP_RENAME:
1080                 return T("rename");
1081         default:
1082                 wimlib_assert(0);
1083                 return NULL;
1084         }
1085 }
1086
1087 static bool
1088 have_command_type(const struct wimlib_update_command *cmds, size_t num_cmds,
1089                   enum wimlib_update_op op)
1090 {
1091         for (size_t i = 0; i < num_cmds; i++)
1092                 if (cmds[i].op == op)
1093                         return true;
1094         return false;
1095 }
1096
1097 static int
1098 execute_update_commands(WIMStruct *wim,
1099                         const struct wimlib_update_command *cmds,
1100                         size_t num_cmds,
1101                         int update_flags)
1102 {
1103         struct wim_inode_table *inode_table;
1104         struct wim_sd_set *sd_set;
1105         struct list_head unhashed_streams;
1106         struct update_command_journal *j;
1107         union wimlib_progress_info info;
1108         int ret;
1109
1110         if (have_command_type(cmds, num_cmds, WIMLIB_UPDATE_OP_ADD)) {
1111                 /* If we have at least one "add" command, create the inode and
1112                  * security descriptor tables to index new inodes and new
1113                  * security descriptors, respectively.  */
1114                 inode_table = alloca(sizeof(struct wim_inode_table));
1115                 sd_set = alloca(sizeof(struct wim_sd_set));
1116
1117                 ret = init_inode_table(inode_table, 9001);
1118                 if (ret)
1119                         goto out;
1120
1121                 ret = init_sd_set(sd_set, wim_get_current_security_data(wim));
1122                 if (ret)
1123                         goto out_destroy_inode_table;
1124
1125                 INIT_LIST_HEAD(&unhashed_streams);
1126         } else {
1127                 inode_table = NULL;
1128                 sd_set = NULL;
1129         }
1130
1131         /* Start an in-memory journal to allow rollback if something goes wrong
1132          */
1133         j = new_update_command_journal(num_cmds,
1134                                        &wim_get_current_image_metadata(wim)->root_dentry,
1135                                        wim->lookup_table);
1136         if (!j) {
1137                 ret = WIMLIB_ERR_NOMEM;
1138                 goto out_destroy_sd_set;
1139         }
1140
1141         info.update.completed_commands = 0;
1142         info.update.total_commands = num_cmds;
1143         ret = 0;
1144         for (size_t i = 0; i < num_cmds; i++) {
1145                 DEBUG("Executing update command %zu of %zu (op=%"TS")",
1146                       i + 1, num_cmds, update_op_to_str(cmds[i].op));
1147                 info.update.command = &cmds[i];
1148                 if (update_flags & WIMLIB_UPDATE_FLAG_SEND_PROGRESS) {
1149                         ret = call_progress(wim->progfunc,
1150                                             WIMLIB_PROGRESS_MSG_UPDATE_BEGIN_COMMAND,
1151                                             &info, wim->progctx);
1152                         if (ret)
1153                                 goto rollback;
1154                 }
1155
1156                 switch (cmds[i].op) {
1157                 case WIMLIB_UPDATE_OP_ADD:
1158                         ret = execute_add_command(j, wim, &cmds[i], inode_table,
1159                                                   sd_set, &unhashed_streams);
1160                         break;
1161                 case WIMLIB_UPDATE_OP_DELETE:
1162                         ret = execute_delete_command(j, wim, &cmds[i]);
1163                         break;
1164                 case WIMLIB_UPDATE_OP_RENAME:
1165                         ret = execute_rename_command(j, wim, &cmds[i]);
1166                         break;
1167                 }
1168                 if (unlikely(ret))
1169                         goto rollback;
1170                 info.update.completed_commands++;
1171                 if (update_flags & WIMLIB_UPDATE_FLAG_SEND_PROGRESS) {
1172                         ret = call_progress(wim->progfunc,
1173                                             WIMLIB_PROGRESS_MSG_UPDATE_END_COMMAND,
1174                                             &info, wim->progctx);
1175                         if (ret)
1176                                 goto rollback;
1177                 }
1178                 next_command(j);
1179         }
1180
1181         commit_update(j);
1182         if (inode_table) {
1183                 struct wim_image_metadata *imd;
1184
1185                 imd = wim_get_current_image_metadata(wim);
1186
1187                 list_splice_tail(&unhashed_streams, &imd->unhashed_streams);
1188                 inode_table_prepare_inode_list(inode_table, &imd->inode_list);
1189         }
1190         goto out_destroy_sd_set;
1191
1192 rollback:
1193         if (sd_set)
1194                 rollback_new_security_descriptors(sd_set);
1195         rollback_update(j);
1196 out_destroy_sd_set:
1197         if (sd_set)
1198                 destroy_sd_set(sd_set);
1199 out_destroy_inode_table:
1200         if (inode_table)
1201                 destroy_inode_table(inode_table);
1202 out:
1203         return ret;
1204 }
1205
1206
1207 static int
1208 check_add_command(struct wimlib_update_command *cmd,
1209                   const struct wim_header *hdr)
1210 {
1211         int add_flags = cmd->add.add_flags;
1212
1213         if (add_flags & ~(WIMLIB_ADD_FLAG_NTFS |
1214                           WIMLIB_ADD_FLAG_DEREFERENCE |
1215                           WIMLIB_ADD_FLAG_VERBOSE |
1216                           /* BOOT doesn't make sense for wimlib_update_image().  */
1217                           /*WIMLIB_ADD_FLAG_BOOT |*/
1218                           WIMLIB_ADD_FLAG_UNIX_DATA |
1219                           WIMLIB_ADD_FLAG_NO_ACLS |
1220                           WIMLIB_ADD_FLAG_STRICT_ACLS |
1221                           WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE |
1222                           WIMLIB_ADD_FLAG_RPFIX |
1223                           WIMLIB_ADD_FLAG_NORPFIX |
1224                           WIMLIB_ADD_FLAG_NO_UNSUPPORTED_EXCLUDE |
1225                           WIMLIB_ADD_FLAG_WINCONFIG |
1226                           WIMLIB_ADD_FLAG_WIMBOOT |
1227                           WIMLIB_ADD_FLAG_NO_REPLACE |
1228                           WIMLIB_ADD_FLAG_TEST_FILE_EXCLUSION))
1229                 return WIMLIB_ERR_INVALID_PARAM;
1230
1231         bool is_entire_image = WIMLIB_IS_WIM_ROOT_PATH(cmd->add.wim_target_path);
1232
1233 #ifndef WITH_NTFS_3G
1234         if (add_flags & WIMLIB_ADD_FLAG_NTFS) {
1235                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
1236                       "        we cannot capture a WIM image directly "
1237                       "from an NTFS volume");
1238                 return WIMLIB_ERR_UNSUPPORTED;
1239         }
1240 #endif
1241
1242 #ifdef __WIN32__
1243         /* Check for flags not supported on Windows */
1244         if (add_flags & WIMLIB_ADD_FLAG_UNIX_DATA) {
1245                 ERROR("Capturing UNIX-specific data is not supported on Windows");
1246                 return WIMLIB_ERR_UNSUPPORTED;
1247         }
1248         if (add_flags & WIMLIB_ADD_FLAG_DEREFERENCE) {
1249                 ERROR("Dereferencing symbolic links is not supported on Windows");
1250                 return WIMLIB_ERR_UNSUPPORTED;
1251         }
1252 #endif
1253
1254         /* VERBOSE implies EXCLUDE_VERBOSE */
1255         if (add_flags & WIMLIB_ADD_FLAG_VERBOSE)
1256                 add_flags |= WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE;
1257
1258         /* Check for contradictory reparse point fixup flags */
1259         if ((add_flags & (WIMLIB_ADD_FLAG_RPFIX |
1260                           WIMLIB_ADD_FLAG_NORPFIX)) ==
1261                 (WIMLIB_ADD_FLAG_RPFIX |
1262                  WIMLIB_ADD_FLAG_NORPFIX))
1263         {
1264                 ERROR("Cannot specify RPFIX and NORPFIX flags "
1265                       "at the same time!");
1266                 return WIMLIB_ERR_INVALID_PARAM;
1267         }
1268
1269         /* Set default behavior on reparse point fixups if requested */
1270         if ((add_flags & (WIMLIB_ADD_FLAG_RPFIX |
1271                           WIMLIB_ADD_FLAG_NORPFIX)) == 0)
1272         {
1273                 /* Do reparse-point fixups by default if we are capturing an
1274                  * entire image and either the header flag is set from previous
1275                  * images, or if this is the first image being added. */
1276                 if (is_entire_image &&
1277                     ((hdr->flags & WIM_HDR_FLAG_RP_FIX) || hdr->image_count == 1))
1278                         add_flags |= WIMLIB_ADD_FLAG_RPFIX;
1279         }
1280
1281         if (!is_entire_image) {
1282                 if (add_flags & WIMLIB_ADD_FLAG_NTFS) {
1283                         ERROR("Cannot add directly from an NTFS volume "
1284                               "when not capturing a full image!");
1285                         return WIMLIB_ERR_INVALID_PARAM;
1286                 }
1287
1288                 if (add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1289                         ERROR("Cannot do reparse point fixups when "
1290                               "not capturing a full image!");
1291                         return WIMLIB_ERR_INVALID_PARAM;
1292                 }
1293         }
1294         /* We may have modified the add flags. */
1295         cmd->add.add_flags = add_flags;
1296         return 0;
1297 }
1298
1299 static int
1300 check_delete_command(const struct wimlib_update_command *cmd)
1301 {
1302         if (cmd->delete_.delete_flags & ~(WIMLIB_DELETE_FLAG_FORCE |
1303                                           WIMLIB_DELETE_FLAG_RECURSIVE))
1304                 return WIMLIB_ERR_INVALID_PARAM;
1305         return 0;
1306 }
1307
1308 static int
1309 check_rename_command(const struct wimlib_update_command *cmd)
1310 {
1311         if (cmd->rename.rename_flags != 0)
1312                 return WIMLIB_ERR_INVALID_PARAM;
1313         return 0;
1314 }
1315
1316 static int
1317 check_update_command(struct wimlib_update_command *cmd,
1318                      const struct wim_header *hdr)
1319 {
1320         switch (cmd->op) {
1321         case WIMLIB_UPDATE_OP_ADD:
1322                 return check_add_command(cmd, hdr);
1323         case WIMLIB_UPDATE_OP_DELETE:
1324                 return check_delete_command(cmd);
1325         case WIMLIB_UPDATE_OP_RENAME:
1326                 return check_rename_command(cmd);
1327         }
1328         return 0;
1329 }
1330
1331 static int
1332 check_update_commands(struct wimlib_update_command *cmds, size_t num_cmds,
1333                       const struct wim_header *hdr)
1334 {
1335         int ret = 0;
1336         for (size_t i = 0; i < num_cmds; i++) {
1337                 ret = check_update_command(&cmds[i], hdr);
1338                 if (ret)
1339                         break;
1340         }
1341         return ret;
1342 }
1343
1344
1345 static void
1346 free_update_commands(struct wimlib_update_command *cmds, size_t num_cmds)
1347 {
1348         if (cmds) {
1349                 for (size_t i = 0; i < num_cmds; i++) {
1350                         switch (cmds[i].op) {
1351                         case WIMLIB_UPDATE_OP_ADD:
1352                                 FREE(cmds[i].add.wim_target_path);
1353                                 break;
1354                         case WIMLIB_UPDATE_OP_DELETE:
1355                                 FREE(cmds[i].delete_.wim_path);
1356                                 break;
1357                         case WIMLIB_UPDATE_OP_RENAME:
1358                                 FREE(cmds[i].rename.wim_source_path);
1359                                 FREE(cmds[i].rename.wim_target_path);
1360                                 break;
1361                         }
1362                 }
1363                 FREE(cmds);
1364         }
1365 }
1366
1367 static int
1368 copy_update_commands(const struct wimlib_update_command *cmds,
1369                      size_t num_cmds,
1370                      struct wimlib_update_command **cmds_copy_ret)
1371 {
1372         int ret;
1373         struct wimlib_update_command *cmds_copy;
1374
1375         cmds_copy = CALLOC(num_cmds, sizeof(cmds[0]));
1376         if (!cmds_copy)
1377                 goto oom;
1378
1379         for (size_t i = 0; i < num_cmds; i++) {
1380                 cmds_copy[i].op = cmds[i].op;
1381                 switch (cmds[i].op) {
1382                 case WIMLIB_UPDATE_OP_ADD:
1383                         cmds_copy[i].add.fs_source_path = cmds[i].add.fs_source_path;
1384                         cmds_copy[i].add.wim_target_path =
1385                                 canonicalize_wim_path(cmds[i].add.wim_target_path);
1386                         if (!cmds_copy[i].add.wim_target_path)
1387                                 goto oom;
1388                         cmds_copy[i].add.config_file = cmds[i].add.config_file;
1389                         cmds_copy[i].add.add_flags = cmds[i].add.add_flags;
1390                         break;
1391                 case WIMLIB_UPDATE_OP_DELETE:
1392                         cmds_copy[i].delete_.wim_path =
1393                                 canonicalize_wim_path(cmds[i].delete_.wim_path);
1394                         if (!cmds_copy[i].delete_.wim_path)
1395                                 goto oom;
1396                         cmds_copy[i].delete_.delete_flags = cmds[i].delete_.delete_flags;
1397                         break;
1398                 case WIMLIB_UPDATE_OP_RENAME:
1399                         cmds_copy[i].rename.wim_source_path =
1400                                 canonicalize_wim_path(cmds[i].rename.wim_source_path);
1401                         cmds_copy[i].rename.wim_target_path =
1402                                 canonicalize_wim_path(cmds[i].rename.wim_target_path);
1403                         if (!cmds_copy[i].rename.wim_source_path ||
1404                             !cmds_copy[i].rename.wim_target_path)
1405                                 goto oom;
1406                         break;
1407                 default:
1408                         ERROR("Unknown update operation %u", cmds[i].op);
1409                         ret = WIMLIB_ERR_INVALID_PARAM;
1410                         goto err;
1411                 }
1412         }
1413         *cmds_copy_ret = cmds_copy;
1414         ret = 0;
1415 out:
1416         return ret;
1417 oom:
1418         ret = WIMLIB_ERR_NOMEM;
1419 err:
1420         free_update_commands(cmds_copy, num_cmds);
1421         goto out;
1422 }
1423
1424 /* API function documented in wimlib.h  */
1425 WIMLIBAPI int
1426 wimlib_update_image(WIMStruct *wim,
1427                     int image,
1428                     const struct wimlib_update_command *cmds,
1429                     size_t num_cmds,
1430                     int update_flags)
1431 {
1432         int ret;
1433         struct wimlib_update_command *cmds_copy;
1434
1435         if (update_flags & ~WIMLIB_UPDATE_FLAG_SEND_PROGRESS)
1436                 return WIMLIB_ERR_INVALID_PARAM;
1437
1438         DEBUG("Updating image %d with %zu commands", image, num_cmds);
1439
1440         if (have_command_type(cmds, num_cmds, WIMLIB_UPDATE_OP_DELETE))
1441                 ret = can_delete_from_wim(wim);
1442         else
1443                 ret = can_modify_wim(wim);
1444
1445         if (ret)
1446                 goto out;
1447
1448         /* Load the metadata for the image to modify (if not loaded already) */
1449         ret = select_wim_image(wim, image);
1450         if (ret)
1451                 goto out;
1452
1453         DEBUG("Preparing %zu update commands", num_cmds);
1454
1455         /* Make a copy of the update commands, in the process doing certain
1456          * canonicalizations on paths (e.g. translating backslashes to forward
1457          * slashes).  This is done to avoid modifying the caller's copy of the
1458          * commands. */
1459         ret = copy_update_commands(cmds, num_cmds, &cmds_copy);
1460         if (ret)
1461                 goto out;
1462
1463         /* Perform additional checks on the update commands before we execute
1464          * them. */
1465         ret = check_update_commands(cmds_copy, num_cmds, &wim->hdr);
1466         if (ret)
1467                 goto out_free_cmds_copy;
1468
1469         /* Actually execute the update commands. */
1470         DEBUG("Executing %zu update commands", num_cmds);
1471         ret = execute_update_commands(wim, cmds_copy, num_cmds, update_flags);
1472         if (ret)
1473                 goto out_free_cmds_copy;
1474
1475         wim->image_metadata[image - 1]->modified = 1;
1476
1477         /* Statistics about the WIM image, such as the numbers of files and
1478          * directories, may have changed.  Call xml_update_image_info() to
1479          * recalculate these statistics. */
1480         xml_update_image_info(wim, image);
1481 out_free_cmds_copy:
1482         free_update_commands(cmds_copy, num_cmds);
1483 out:
1484         return ret;
1485 }
1486
1487 WIMLIBAPI int
1488 wimlib_delete_path(WIMStruct *wim, int image,
1489                    const tchar *path, int delete_flags)
1490 {
1491         struct wimlib_update_command cmd;
1492
1493         cmd.op = WIMLIB_UPDATE_OP_DELETE;
1494         cmd.delete_.wim_path = (tchar *)path;
1495         cmd.delete_.delete_flags = delete_flags;
1496
1497         return wimlib_update_image(wim, image, &cmd, 1, 0);
1498 }
1499
1500 WIMLIBAPI int
1501 wimlib_rename_path(WIMStruct *wim, int image,
1502                    const tchar *source_path, const tchar *dest_path)
1503 {
1504         struct wimlib_update_command cmd;
1505
1506         cmd.op = WIMLIB_UPDATE_OP_RENAME;
1507         cmd.rename.wim_source_path = (tchar *)source_path;
1508         cmd.rename.wim_target_path = (tchar *)dest_path;
1509         cmd.rename.rename_flags = 0;
1510
1511         return wimlib_update_image(wim, image, &cmd, 1, 0);
1512 }
1513
1514 WIMLIBAPI int
1515 wimlib_add_tree(WIMStruct *wim, int image,
1516                 const tchar *fs_source_path, const tchar *wim_target_path,
1517                 int add_flags)
1518 {
1519         struct wimlib_update_command cmd;
1520
1521         cmd.op = WIMLIB_UPDATE_OP_ADD;
1522         cmd.add.fs_source_path = (tchar *)fs_source_path;
1523         cmd.add.wim_target_path = (tchar *)wim_target_path;
1524         cmd.add.add_flags = add_flags;
1525         cmd.add.config_file = NULL;
1526
1527         return wimlib_update_image(wim, image, &cmd, 1, 0);
1528 }