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