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