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