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