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