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