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