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