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