82da53f4b3968fba37e2c252dbf41f7fe67f256d
[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/capture.h"
60 #include "wimlib/dentry.h"
61 #include "wimlib/encoding.h"
62 #include "wimlib/endianness.h"
63 #include "wimlib/error.h"
64 #include "wimlib/metadata.h"
65 #include "wimlib/paths.h"
66 #include "wimlib/progress.h"
67 #include "wimlib/xml.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->_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         BUILD_BUG_ON(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 capture_params params;
790         struct capture_config config;
791         capture_tree_t capture_tree = platform_default_capture_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         DEBUG("fs_source_path=\"%"TS"\", wim_target_path=\"%"TS"\", add_flags=%#x",
800               fs_source_path, wim_target_path, add_flags);
801
802         memset(&params, 0, sizeof(params));
803
804 #ifdef WITH_NTFS_3G
805         if (add_flags & WIMLIB_ADD_FLAG_NTFS)
806                 capture_tree = ntfs_3g_build_dentry_tree;
807 #endif
808
809         ret = get_capture_config(config_file, &config,
810                                  add_flags, fs_source_path);
811         if (ret)
812                 goto out;
813
814         params.blob_table = wim->blob_table;
815         params.unhashed_blobs = unhashed_blobs;
816         params.inode_table = inode_table;
817         params.sd_set = sd_set;
818         params.config = &config;
819         params.add_flags = add_flags;
820
821         params.progfunc = wim->progfunc;
822         params.progctx = wim->progctx;
823         params.progress.scan.source = fs_source_path;
824         params.progress.scan.wim_target_path = wim_target_path;
825         ret = call_progress(params.progfunc, WIMLIB_PROGRESS_MSG_SCAN_BEGIN,
826                             &params.progress, params.progctx);
827         if (ret)
828                 goto out_destroy_config;
829
830         if (WIMLIB_IS_WIM_ROOT_PATH(wim_target_path))
831                 params.add_flags |= WIMLIB_ADD_FLAG_ROOT;
832         ret = (*capture_tree)(&branch, fs_source_path, &params);
833         if (ret)
834                 goto out_destroy_config;
835
836         ret = call_progress(params.progfunc, WIMLIB_PROGRESS_MSG_SCAN_END,
837                             &params.progress, params.progctx);
838         if (ret) {
839                 free_dentry_tree(branch, wim->blob_table);
840                 goto out_destroy_config;
841         }
842
843         if (WIMLIB_IS_WIM_ROOT_PATH(wim_target_path) &&
844             branch && !dentry_is_directory(branch))
845         {
846                 ERROR("\"%"TS"\" is not a directory!", fs_source_path);
847                 ret = WIMLIB_ERR_NOTDIR;
848                 free_dentry_tree(branch, wim->blob_table);
849                 goto out_destroy_config;
850         }
851
852         ret = attach_branch(branch, wim_target_path, j,
853                             add_flags, params.progfunc, params.progctx);
854         if (ret)
855                 goto out_destroy_config;
856
857         if (config_file && (add_flags & WIMLIB_ADD_FLAG_WIMBOOT) &&
858             WIMLIB_IS_WIM_ROOT_PATH(wim_target_path))
859         {
860                 params.add_flags = 0;
861                 params.progfunc = NULL;
862                 params.config = NULL;
863
864                 /* If a capture configuration file was explicitly specified when
865                  * capturing an image in WIMBoot mode, save it as
866                  * /Windows/System32/WimBootCompress.ini in the WIM image. */
867                 ret = platform_default_capture_tree(&branch, config_file, &params);
868                 if (ret)
869                         goto out_destroy_config;
870
871                 ret = attach_branch(branch, wimboot_cfgfile, j, 0, NULL, NULL);
872                 if (ret)
873                         goto out_destroy_config;
874         }
875
876         ret = 0;
877 out_destroy_config:
878         destroy_capture_config(&config);
879 out:
880         return ret;
881 }
882
883 static int
884 execute_delete_command(struct update_command_journal *j,
885                        WIMStruct *wim,
886                        const struct wimlib_update_command *delete_cmd)
887 {
888         int flags;
889         const tchar *wim_path;
890         struct wim_dentry *tree;
891
892         flags = delete_cmd->delete_.delete_flags;
893         wim_path = delete_cmd->delete_.wim_path;
894
895         DEBUG("Deleting WIM path \"%"TS"\" (flags=%#x)", wim_path, flags);
896
897         tree = get_dentry(wim, wim_path, WIMLIB_CASE_PLATFORM_DEFAULT);
898         if (!tree) {
899                 /* Path to delete does not exist in the WIM. */
900                 if (flags & WIMLIB_DELETE_FLAG_FORCE) {
901                         return 0;
902                 } else {
903                         ERROR("Path \"%"TS"\" does not exist in WIM image %d",
904                               wim_path, wim->current_image);
905                         return WIMLIB_ERR_PATH_DOES_NOT_EXIST;
906                 }
907         }
908
909         if (dentry_is_directory(tree) && !(flags & WIMLIB_DELETE_FLAG_RECURSIVE)) {
910                 ERROR("Path \"%"TS"\" in WIM image %d is a directory "
911                       "but a recursive delete was not requested",
912                       wim_path, wim->current_image);
913                 return WIMLIB_ERR_IS_DIRECTORY;
914         }
915
916         return journaled_unlink(j, tree);
917 }
918
919 static int
920 free_dentry_full_path(struct wim_dentry *dentry, void *_ignore)
921 {
922         FREE(dentry->_full_path);
923         dentry->_full_path = NULL;
924         return 0;
925 }
926
927 /* Is @d1 a (possibly nonproper) ancestor of @d2?  */
928 static bool
929 is_ancestor(const struct wim_dentry *d1, const struct wim_dentry *d2)
930 {
931         for (;;) {
932                 if (d2 == d1)
933                         return true;
934                 if (dentry_is_root(d2))
935                         return false;
936                 d2 = d2->d_parent;
937         }
938 }
939
940 /* Rename a file or directory in the WIM.
941  *
942  * This returns a -errno value.
943  *
944  * The journal @j is optional.
945  */
946 int
947 rename_wim_path(WIMStruct *wim, const tchar *from, const tchar *to,
948                 CASE_SENSITIVITY_TYPE case_type,
949                 struct update_command_journal *j)
950 {
951         struct wim_dentry *src;
952         struct wim_dentry *dst;
953         struct wim_dentry *parent_of_dst;
954         int ret;
955
956         /* This rename() implementation currently only supports actual files
957          * (not alternate data streams) */
958
959         src = get_dentry(wim, from, case_type);
960         if (!src)
961                 return -errno;
962
963         dst = get_dentry(wim, to, case_type);
964
965         if (dst) {
966                 /* Destination file exists */
967
968                 if (src == dst) /* Same file */
969                         return 0;
970
971                 if (!dentry_is_directory(src)) {
972                         /* Cannot rename non-directory to directory. */
973                         if (dentry_is_directory(dst))
974                                 return -EISDIR;
975                 } else {
976                         /* Cannot rename directory to a non-directory or a non-empty
977                          * directory */
978                         if (!dentry_is_directory(dst))
979                                 return -ENOTDIR;
980                         if (dentry_has_children(dst))
981                                 return -ENOTEMPTY;
982                 }
983                 parent_of_dst = dst->d_parent;
984         } else {
985                 /* Destination does not exist */
986                 parent_of_dst = get_parent_dentry(wim, to, case_type);
987                 if (!parent_of_dst)
988                         return -errno;
989
990                 if (!dentry_is_directory(parent_of_dst))
991                         return -ENOTDIR;
992         }
993
994         /* @src can't be an ancestor of @dst.  Otherwise we're unlinking @src
995          * from the tree and creating a loop...  */
996         if (is_ancestor(src, parent_of_dst))
997                 return -EBUSY;
998
999         if (j) {
1000                 if (dst)
1001                         if (journaled_unlink(j, dst))
1002                                 return -ENOMEM;
1003                 if (journaled_unlink(j, src))
1004                         return -ENOMEM;
1005                 if (journaled_change_name(j, src, path_basename(to)))
1006                         return -ENOMEM;
1007                 if (journaled_link(j, src, parent_of_dst))
1008                         return -ENOMEM;
1009         } else {
1010                 ret = dentry_set_name(src, path_basename(to));
1011                 if (ret)
1012                         return -ENOMEM;
1013                 if (dst) {
1014                         unlink_dentry(dst);
1015                         free_dentry_tree(dst, wim->blob_table);
1016                 }
1017                 unlink_dentry(src);
1018                 dentry_add_child(parent_of_dst, src);
1019         }
1020         if (src->_full_path)
1021                 for_dentry_in_tree(src, free_dentry_full_path, NULL);
1022         return 0;
1023 }
1024
1025
1026 static int
1027 execute_rename_command(struct update_command_journal *j,
1028                        WIMStruct *wim,
1029                        const struct wimlib_update_command *rename_cmd)
1030 {
1031         int ret;
1032
1033         ret = rename_wim_path(wim, rename_cmd->rename.wim_source_path,
1034                               rename_cmd->rename.wim_target_path,
1035                               WIMLIB_CASE_PLATFORM_DEFAULT, j);
1036         if (ret) {
1037                 ret = -ret;
1038                 errno = ret;
1039                 ERROR_WITH_ERRNO("Can't rename \"%"TS"\" to \"%"TS"\"",
1040                                  rename_cmd->rename.wim_source_path,
1041                                  rename_cmd->rename.wim_target_path);
1042                 switch (ret) {
1043                 case ENOMEM:
1044                         ret = WIMLIB_ERR_NOMEM;
1045                         break;
1046                 case ENOTDIR:
1047                         ret = WIMLIB_ERR_NOTDIR;
1048                         break;
1049                 case ENOTEMPTY:
1050                 case EBUSY:
1051                         /* XXX: EBUSY is returned when the rename would create a
1052                          * loop.  It maybe should have its own error code.  */
1053                         ret = WIMLIB_ERR_NOTEMPTY;
1054                         break;
1055                 case EISDIR:
1056                         ret = WIMLIB_ERR_IS_DIRECTORY;
1057                         break;
1058                 case ENOENT:
1059                 default:
1060                         ret = WIMLIB_ERR_PATH_DOES_NOT_EXIST;
1061                         break;
1062                 }
1063         }
1064         return ret;
1065 }
1066
1067 static inline const tchar *
1068 update_op_to_str(int op)
1069 {
1070         switch (op) {
1071         case WIMLIB_UPDATE_OP_ADD:
1072                 return T("add");
1073         case WIMLIB_UPDATE_OP_DELETE:
1074                 return T("delete");
1075         case WIMLIB_UPDATE_OP_RENAME:
1076                 return T("rename");
1077         default:
1078                 wimlib_assert(0);
1079                 return NULL;
1080         }
1081 }
1082
1083 static bool
1084 have_command_type(const struct wimlib_update_command *cmds, size_t num_cmds,
1085                   enum wimlib_update_op op)
1086 {
1087         for (size_t i = 0; i < num_cmds; i++)
1088                 if (cmds[i].op == op)
1089                         return true;
1090         return false;
1091 }
1092
1093 static int
1094 execute_update_commands(WIMStruct *wim,
1095                         const struct wimlib_update_command *cmds,
1096                         size_t num_cmds,
1097                         int update_flags)
1098 {
1099         struct wim_inode_table *inode_table;
1100         struct wim_sd_set *sd_set;
1101         struct list_head unhashed_blobs;
1102         struct update_command_journal *j;
1103         union wimlib_progress_info info;
1104         int ret;
1105
1106         if (have_command_type(cmds, num_cmds, WIMLIB_UPDATE_OP_ADD)) {
1107                 /* If we have at least one "add" command, create the inode and
1108                  * security descriptor tables to index new inodes and new
1109                  * security descriptors, respectively.  */
1110                 inode_table = alloca(sizeof(struct wim_inode_table));
1111                 sd_set = alloca(sizeof(struct wim_sd_set));
1112
1113                 ret = init_inode_table(inode_table, 9001);
1114                 if (ret)
1115                         goto out;
1116
1117                 ret = init_sd_set(sd_set, wim_get_current_security_data(wim));
1118                 if (ret)
1119                         goto out_destroy_inode_table;
1120
1121                 INIT_LIST_HEAD(&unhashed_blobs);
1122         } else {
1123                 inode_table = NULL;
1124                 sd_set = NULL;
1125         }
1126
1127         /* Start an in-memory journal to allow rollback if something goes wrong
1128          */
1129         j = new_update_command_journal(num_cmds,
1130                                        &wim_get_current_image_metadata(wim)->root_dentry,
1131                                        wim->blob_table);
1132         if (!j) {
1133                 ret = WIMLIB_ERR_NOMEM;
1134                 goto out_destroy_sd_set;
1135         }
1136
1137         info.update.completed_commands = 0;
1138         info.update.total_commands = num_cmds;
1139         ret = 0;
1140         for (size_t i = 0; i < num_cmds; i++) {
1141                 DEBUG("Executing update command %zu of %zu (op=%"TS")",
1142                       i + 1, num_cmds, update_op_to_str(cmds[i].op));
1143                 info.update.command = &cmds[i];
1144                 if (update_flags & WIMLIB_UPDATE_FLAG_SEND_PROGRESS) {
1145                         ret = call_progress(wim->progfunc,
1146                                             WIMLIB_PROGRESS_MSG_UPDATE_BEGIN_COMMAND,
1147                                             &info, wim->progctx);
1148                         if (ret)
1149                                 goto rollback;
1150                 }
1151
1152                 switch (cmds[i].op) {
1153                 case WIMLIB_UPDATE_OP_ADD:
1154                         ret = execute_add_command(j, wim, &cmds[i], inode_table,
1155                                                   sd_set, &unhashed_blobs);
1156                         break;
1157                 case WIMLIB_UPDATE_OP_DELETE:
1158                         ret = execute_delete_command(j, wim, &cmds[i]);
1159                         break;
1160                 case WIMLIB_UPDATE_OP_RENAME:
1161                         ret = execute_rename_command(j, wim, &cmds[i]);
1162                         break;
1163                 }
1164                 if (unlikely(ret))
1165                         goto rollback;
1166                 info.update.completed_commands++;
1167                 if (update_flags & WIMLIB_UPDATE_FLAG_SEND_PROGRESS) {
1168                         ret = call_progress(wim->progfunc,
1169                                             WIMLIB_PROGRESS_MSG_UPDATE_END_COMMAND,
1170                                             &info, wim->progctx);
1171                         if (ret)
1172                                 goto rollback;
1173                 }
1174                 next_command(j);
1175         }
1176
1177         commit_update(j);
1178         if (inode_table) {
1179                 struct wim_image_metadata *imd;
1180
1181                 imd = wim_get_current_image_metadata(wim);
1182
1183                 list_splice_tail(&unhashed_blobs, &imd->unhashed_blobs);
1184                 inode_table_prepare_inode_list(inode_table, &imd->inode_list);
1185         }
1186         goto out_destroy_sd_set;
1187
1188 rollback:
1189         if (sd_set)
1190                 rollback_new_security_descriptors(sd_set);
1191         rollback_update(j);
1192 out_destroy_sd_set:
1193         if (sd_set)
1194                 destroy_sd_set(sd_set);
1195 out_destroy_inode_table:
1196         if (inode_table)
1197                 destroy_inode_table(inode_table);
1198 out:
1199         return ret;
1200 }
1201
1202
1203 static int
1204 check_add_command(struct wimlib_update_command *cmd,
1205                   const struct wim_header *hdr)
1206 {
1207         int add_flags = cmd->add.add_flags;
1208
1209         if (add_flags & ~(WIMLIB_ADD_FLAG_NTFS |
1210                           WIMLIB_ADD_FLAG_DEREFERENCE |
1211                           WIMLIB_ADD_FLAG_VERBOSE |
1212                           /* BOOT doesn't make sense for wimlib_update_image().  */
1213                           /*WIMLIB_ADD_FLAG_BOOT |*/
1214                           WIMLIB_ADD_FLAG_UNIX_DATA |
1215                           WIMLIB_ADD_FLAG_NO_ACLS |
1216                           WIMLIB_ADD_FLAG_STRICT_ACLS |
1217                           WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE |
1218                           WIMLIB_ADD_FLAG_RPFIX |
1219                           WIMLIB_ADD_FLAG_NORPFIX |
1220                           WIMLIB_ADD_FLAG_NO_UNSUPPORTED_EXCLUDE |
1221                           WIMLIB_ADD_FLAG_WINCONFIG |
1222                           WIMLIB_ADD_FLAG_WIMBOOT |
1223                           WIMLIB_ADD_FLAG_NO_REPLACE |
1224                           WIMLIB_ADD_FLAG_TEST_FILE_EXCLUSION))
1225                 return WIMLIB_ERR_INVALID_PARAM;
1226
1227         bool is_entire_image = WIMLIB_IS_WIM_ROOT_PATH(cmd->add.wim_target_path);
1228
1229 #ifndef WITH_NTFS_3G
1230         if (add_flags & WIMLIB_ADD_FLAG_NTFS) {
1231                 ERROR("NTFS-3g capture mode is unsupported because wimlib "
1232                       "was compiled --without-ntfs-3g");
1233                 return WIMLIB_ERR_UNSUPPORTED;
1234         }
1235 #endif
1236
1237 #ifdef __WIN32__
1238         /* Check for flags not supported on Windows */
1239         if (add_flags & WIMLIB_ADD_FLAG_UNIX_DATA) {
1240                 ERROR("Capturing UNIX-specific data is not supported on Windows");
1241                 return WIMLIB_ERR_UNSUPPORTED;
1242         }
1243         if (add_flags & WIMLIB_ADD_FLAG_DEREFERENCE) {
1244                 ERROR("Dereferencing symbolic links is not supported on Windows");
1245                 return WIMLIB_ERR_UNSUPPORTED;
1246         }
1247 #endif
1248
1249         /* VERBOSE implies EXCLUDE_VERBOSE */
1250         if (add_flags & WIMLIB_ADD_FLAG_VERBOSE)
1251                 add_flags |= WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE;
1252
1253         /* Check for contradictory reparse point fixup flags */
1254         if ((add_flags & (WIMLIB_ADD_FLAG_RPFIX |
1255                           WIMLIB_ADD_FLAG_NORPFIX)) ==
1256                 (WIMLIB_ADD_FLAG_RPFIX |
1257                  WIMLIB_ADD_FLAG_NORPFIX))
1258         {
1259                 ERROR("Cannot specify RPFIX and NORPFIX flags "
1260                       "at the same time!");
1261                 return WIMLIB_ERR_INVALID_PARAM;
1262         }
1263
1264         /* Set default behavior on reparse point fixups if requested */
1265         if ((add_flags & (WIMLIB_ADD_FLAG_RPFIX |
1266                           WIMLIB_ADD_FLAG_NORPFIX)) == 0)
1267         {
1268                 /* Do reparse-point fixups by default if we are capturing an
1269                  * entire image and either the header flag is set from previous
1270                  * images, or if this is the first image being added. */
1271                 if (is_entire_image &&
1272                     ((hdr->flags & WIM_HDR_FLAG_RP_FIX) || hdr->image_count == 1))
1273                         add_flags |= WIMLIB_ADD_FLAG_RPFIX;
1274         }
1275
1276         if (!is_entire_image) {
1277                 if (add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1278                         ERROR("Cannot do reparse point fixups when "
1279                               "not capturing a full image!");
1280                         return WIMLIB_ERR_INVALID_PARAM;
1281                 }
1282         }
1283         /* We may have modified the add flags. */
1284         cmd->add.add_flags = add_flags;
1285         return 0;
1286 }
1287
1288 static int
1289 check_delete_command(const struct wimlib_update_command *cmd)
1290 {
1291         if (cmd->delete_.delete_flags & ~(WIMLIB_DELETE_FLAG_FORCE |
1292                                           WIMLIB_DELETE_FLAG_RECURSIVE))
1293                 return WIMLIB_ERR_INVALID_PARAM;
1294         return 0;
1295 }
1296
1297 static int
1298 check_rename_command(const struct wimlib_update_command *cmd)
1299 {
1300         if (cmd->rename.rename_flags != 0)
1301                 return WIMLIB_ERR_INVALID_PARAM;
1302         return 0;
1303 }
1304
1305 static int
1306 check_update_command(struct wimlib_update_command *cmd,
1307                      const struct wim_header *hdr)
1308 {
1309         switch (cmd->op) {
1310         case WIMLIB_UPDATE_OP_ADD:
1311                 return check_add_command(cmd, hdr);
1312         case WIMLIB_UPDATE_OP_DELETE:
1313                 return check_delete_command(cmd);
1314         case WIMLIB_UPDATE_OP_RENAME:
1315                 return check_rename_command(cmd);
1316         }
1317         return 0;
1318 }
1319
1320 static int
1321 check_update_commands(struct wimlib_update_command *cmds, size_t num_cmds,
1322                       const struct wim_header *hdr)
1323 {
1324         int ret = 0;
1325         for (size_t i = 0; i < num_cmds; i++) {
1326                 ret = check_update_command(&cmds[i], hdr);
1327                 if (ret)
1328                         break;
1329         }
1330         return ret;
1331 }
1332
1333
1334 static void
1335 free_update_commands(struct wimlib_update_command *cmds, size_t num_cmds)
1336 {
1337         if (cmds) {
1338                 for (size_t i = 0; i < num_cmds; i++) {
1339                         switch (cmds[i].op) {
1340                         case WIMLIB_UPDATE_OP_ADD:
1341                                 FREE(cmds[i].add.wim_target_path);
1342                                 break;
1343                         case WIMLIB_UPDATE_OP_DELETE:
1344                                 FREE(cmds[i].delete_.wim_path);
1345                                 break;
1346                         case WIMLIB_UPDATE_OP_RENAME:
1347                                 FREE(cmds[i].rename.wim_source_path);
1348                                 FREE(cmds[i].rename.wim_target_path);
1349                                 break;
1350                         }
1351                 }
1352                 FREE(cmds);
1353         }
1354 }
1355
1356 static int
1357 copy_update_commands(const struct wimlib_update_command *cmds,
1358                      size_t num_cmds,
1359                      struct wimlib_update_command **cmds_copy_ret)
1360 {
1361         int ret;
1362         struct wimlib_update_command *cmds_copy;
1363
1364         cmds_copy = CALLOC(num_cmds, sizeof(cmds[0]));
1365         if (!cmds_copy)
1366                 goto oom;
1367
1368         for (size_t i = 0; i < num_cmds; i++) {
1369                 cmds_copy[i].op = cmds[i].op;
1370                 switch (cmds[i].op) {
1371                 case WIMLIB_UPDATE_OP_ADD:
1372                         cmds_copy[i].add.fs_source_path = cmds[i].add.fs_source_path;
1373                         cmds_copy[i].add.wim_target_path =
1374                                 canonicalize_wim_path(cmds[i].add.wim_target_path);
1375                         if (!cmds_copy[i].add.wim_target_path)
1376                                 goto oom;
1377                         cmds_copy[i].add.config_file = cmds[i].add.config_file;
1378                         cmds_copy[i].add.add_flags = cmds[i].add.add_flags;
1379                         break;
1380                 case WIMLIB_UPDATE_OP_DELETE:
1381                         cmds_copy[i].delete_.wim_path =
1382                                 canonicalize_wim_path(cmds[i].delete_.wim_path);
1383                         if (!cmds_copy[i].delete_.wim_path)
1384                                 goto oom;
1385                         cmds_copy[i].delete_.delete_flags = cmds[i].delete_.delete_flags;
1386                         break;
1387                 case WIMLIB_UPDATE_OP_RENAME:
1388                         cmds_copy[i].rename.wim_source_path =
1389                                 canonicalize_wim_path(cmds[i].rename.wim_source_path);
1390                         cmds_copy[i].rename.wim_target_path =
1391                                 canonicalize_wim_path(cmds[i].rename.wim_target_path);
1392                         if (!cmds_copy[i].rename.wim_source_path ||
1393                             !cmds_copy[i].rename.wim_target_path)
1394                                 goto oom;
1395                         break;
1396                 default:
1397                         ERROR("Unknown update operation %u", cmds[i].op);
1398                         ret = WIMLIB_ERR_INVALID_PARAM;
1399                         goto err;
1400                 }
1401         }
1402         *cmds_copy_ret = cmds_copy;
1403         ret = 0;
1404 out:
1405         return ret;
1406 oom:
1407         ret = WIMLIB_ERR_NOMEM;
1408 err:
1409         free_update_commands(cmds_copy, num_cmds);
1410         goto out;
1411 }
1412
1413 /* API function documented in wimlib.h  */
1414 WIMLIBAPI int
1415 wimlib_update_image(WIMStruct *wim,
1416                     int image,
1417                     const struct wimlib_update_command *cmds,
1418                     size_t num_cmds,
1419                     int update_flags)
1420 {
1421         int ret;
1422         struct wimlib_update_command *cmds_copy;
1423
1424         if (update_flags & ~WIMLIB_UPDATE_FLAG_SEND_PROGRESS)
1425                 return WIMLIB_ERR_INVALID_PARAM;
1426
1427         DEBUG("Updating image %d with %zu commands", image, num_cmds);
1428
1429         /* Load the metadata for the image to modify (if not loaded already) */
1430         ret = select_wim_image(wim, image);
1431         if (ret)
1432                 goto out;
1433
1434         DEBUG("Preparing %zu update commands", num_cmds);
1435
1436         /* Make a copy of the update commands, in the process doing certain
1437          * canonicalizations on paths (e.g. translating backslashes to forward
1438          * slashes).  This is done to avoid modifying the caller's copy of the
1439          * commands. */
1440         ret = copy_update_commands(cmds, num_cmds, &cmds_copy);
1441         if (ret)
1442                 goto out;
1443
1444         /* Perform additional checks on the update commands before we execute
1445          * them. */
1446         ret = check_update_commands(cmds_copy, num_cmds, &wim->hdr);
1447         if (ret)
1448                 goto out_free_cmds_copy;
1449
1450         /* Actually execute the update commands. */
1451         DEBUG("Executing %zu update commands", num_cmds);
1452         ret = execute_update_commands(wim, cmds_copy, num_cmds, update_flags);
1453         if (ret)
1454                 goto out_free_cmds_copy;
1455
1456         wim->image_metadata[image - 1]->modified = 1;
1457
1458         /* Statistics about the WIM image, such as the numbers of files and
1459          * directories, may have changed.  Call xml_update_image_info() to
1460          * recalculate these statistics. */
1461         xml_update_image_info(wim, image);
1462
1463         for (size_t i = 0; i < num_cmds; i++)
1464                 if (cmds_copy[i].op == WIMLIB_UPDATE_OP_ADD &&
1465                     cmds_copy[i].add.add_flags & WIMLIB_ADD_FLAG_RPFIX)
1466                         wim->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
1467 out_free_cmds_copy:
1468         free_update_commands(cmds_copy, num_cmds);
1469 out:
1470         return ret;
1471 }
1472
1473 WIMLIBAPI int
1474 wimlib_delete_path(WIMStruct *wim, int image,
1475                    const tchar *path, int delete_flags)
1476 {
1477         struct wimlib_update_command cmd;
1478
1479         cmd.op = WIMLIB_UPDATE_OP_DELETE;
1480         cmd.delete_.wim_path = (tchar *)path;
1481         cmd.delete_.delete_flags = delete_flags;
1482
1483         return wimlib_update_image(wim, image, &cmd, 1, 0);
1484 }
1485
1486 WIMLIBAPI int
1487 wimlib_rename_path(WIMStruct *wim, int image,
1488                    const tchar *source_path, const tchar *dest_path)
1489 {
1490         struct wimlib_update_command cmd;
1491
1492         cmd.op = WIMLIB_UPDATE_OP_RENAME;
1493         cmd.rename.wim_source_path = (tchar *)source_path;
1494         cmd.rename.wim_target_path = (tchar *)dest_path;
1495         cmd.rename.rename_flags = 0;
1496
1497         return wimlib_update_image(wim, image, &cmd, 1, 0);
1498 }
1499
1500 WIMLIBAPI int
1501 wimlib_add_tree(WIMStruct *wim, int image,
1502                 const tchar *fs_source_path, const tchar *wim_target_path,
1503                 int add_flags)
1504 {
1505         struct wimlib_update_command cmd;
1506
1507         cmd.op = WIMLIB_UPDATE_OP_ADD;
1508         cmd.add.fs_source_path = (tchar *)fs_source_path;
1509         cmd.add.wim_target_path = (tchar *)wim_target_path;
1510         cmd.add.add_flags = add_flags;
1511         cmd.add.config_file = NULL;
1512
1513         return wimlib_update_image(wim, image, &cmd, 1, 0);
1514 }