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