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