]> wimlib.net Git - wimlib/blob - src/add_image.c
Win32 apply: More special checks for root directory
[wimlib] / src / add_image.c
1 /*
2  * add_image.c
3  */
4
5 /*
6  * Copyright (C) 2012, 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #include "config.h"
25
26 #ifdef __WIN32__
27 #  include "win32.h"
28 #else
29 #  include <dirent.h>
30 #  include <sys/stat.h>
31 #  include <fnmatch.h>
32 #  include "timestamp.h"
33 #endif
34
35 #include "wimlib_internal.h"
36 #include "dentry.h"
37 #include "lookup_table.h"
38 #include "xml.h"
39 #include "security.h"
40
41 #include <ctype.h>
42 #include <errno.h>
43 #include <stdlib.h>
44 #include <limits.h>
45 #include <string.h>
46
47 #include <unistd.h>
48
49 #ifdef HAVE_ALLOCA_H
50 #  include <alloca.h>
51 #endif
52
53 /*
54  * Adds the dentry tree and security data for a new image to the image metadata
55  * array of the WIMStruct.
56  */
57 static int
58 add_new_dentry_tree(WIMStruct *w, struct wim_dentry *root_dentry,
59                     struct wim_security_data *sd)
60 {
61         struct wim_image_metadata *new_imd;
62         struct wim_lookup_table_entry *metadata_lte;
63         int ret;
64
65         metadata_lte = new_lookup_table_entry();
66         if (!metadata_lte)
67                 return WIMLIB_ERR_NOMEM;
68
69         metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
70         metadata_lte->unhashed = 1;
71
72         new_imd = new_image_metadata();
73         if (!new_imd) {
74                 free_lookup_table_entry(metadata_lte);
75                 return WIMLIB_ERR_NOMEM;
76         }
77
78         new_imd->root_dentry    = root_dentry;
79         new_imd->metadata_lte   = metadata_lte;
80         new_imd->security_data  = sd;
81         new_imd->modified       = 1;
82
83         ret = append_image_metadata(w, new_imd);
84         if (ret)
85                 put_image_metadata(new_imd, NULL);
86         return ret;
87
88 }
89
90 #ifndef __WIN32__
91
92 static int
93 unix_capture_regular_file(const char *path,
94                           u64 size,
95                           struct wim_inode *inode,
96                           struct wim_lookup_table *lookup_table)
97 {
98         inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
99
100         /* Empty files do not have to have a lookup table entry. */
101         if (size != 0) {
102                 struct wim_lookup_table_entry *lte;
103                 char *file_on_disk;
104
105                 file_on_disk = STRDUP(path);
106                 if (!file_on_disk)
107                         return WIMLIB_ERR_NOMEM;
108                 lte = new_lookup_table_entry();
109                 if (!lte) {
110                         FREE(file_on_disk);
111                         return WIMLIB_ERR_NOMEM;
112                 }
113                 lte->file_on_disk = file_on_disk;
114                 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
115                 lte->resource_entry.original_size = size;
116                 lookup_table_insert_unhashed(lookup_table, lte, inode, 0);
117                 inode->i_lte = lte;
118         }
119         return 0;
120 }
121
122 static int
123 unix_build_dentry_tree_recursive(struct wim_dentry **root_ret,
124                                  char *path,
125                                  size_t path_len,
126                                  struct add_image_params *params);
127
128 static int
129 unix_capture_directory(struct wim_dentry *dir_dentry,
130                        char *path,
131                        size_t path_len,
132                        struct add_image_params *params)
133 {
134
135         DIR *dir;
136         struct dirent *entry;
137         struct wim_dentry *child;
138         int ret;
139
140         dir_dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
141         dir = opendir(path);
142         if (!dir) {
143                 ERROR_WITH_ERRNO("Failed to open the directory `%s'",
144                                  path);
145                 return WIMLIB_ERR_OPEN;
146         }
147
148         /* Recurse on directory contents */
149         ret = 0;
150         for (;;) {
151                 errno = 0;
152                 entry = readdir(dir);
153                 if (!entry) {
154                         if (errno) {
155                                 ret = WIMLIB_ERR_READ;
156                                 ERROR_WITH_ERRNO("Error reading the "
157                                                  "directory `%s'", path);
158                         }
159                         break;
160                 }
161
162                 if (entry->d_name[0] == '.' && (entry->d_name[1] == '\0'
163                       || (entry->d_name[1] == '.' && entry->d_name[2] == '\0')))
164                                 continue;
165
166                 size_t name_len = strlen(entry->d_name);
167
168                 path[path_len] = '/';
169                 memcpy(&path[path_len + 1], entry->d_name, name_len + 1);
170                 ret = unix_build_dentry_tree_recursive(&child,
171                                                        path,
172                                                        path_len + 1 + name_len,
173                                                        params);
174                 if (ret)
175                         break;
176                 if (child)
177                         dentry_add_child(dir_dentry, child);
178         }
179         closedir(dir);
180         return ret;
181 }
182
183 static int
184 unix_capture_symlink(struct wim_dentry **root_p,
185                      const char *path,
186                      struct wim_inode *inode,
187                      struct add_image_params *params)
188 {
189         char deref_name_buf[4096];
190         ssize_t deref_name_len;
191         int ret;
192
193         inode->i_attributes = FILE_ATTRIBUTE_REPARSE_POINT;
194         inode->i_reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
195
196         /* The idea here is to call readlink() to get the UNIX target of
197          * the symbolic link, then turn the target into a reparse point
198          * data buffer that contains a relative or absolute symbolic
199          * link (NOT a junction point or *full* path symbolic link with
200          * drive letter).
201          */
202         deref_name_len = readlink(path, deref_name_buf,
203                                   sizeof(deref_name_buf) - 1);
204         if (deref_name_len >= 0) {
205                 char *dest = deref_name_buf;
206
207                 dest[deref_name_len] = '\0';
208                 DEBUG("Read symlink `%s'", dest);
209
210                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX) &&
211                      dest[0] == '/')
212                 {
213                         dest = fixup_symlink(dest,
214                                              params->capture_root_ino,
215                                              params->capture_root_dev);
216                         if (!dest) {
217                                 WARNING("Ignoring out of tree absolute symlink "
218                                         "\"%s\" -> \"%s\"\n"
219                                         "          (Use --norpfix to capture "
220                                         "absolute symlinks as-is)",
221                                         path, deref_name_buf);
222                                 free_dentry(*root_p);
223                                 *root_p = NULL;
224                                 return 0;
225                         }
226                         inode->i_not_rpfixed = 0;
227                 }
228                 ret = inode_set_symlink(inode, dest,
229                                         params->lookup_table, NULL);
230                 if (ret == 0) {
231                         /* Unfortunately, Windows seems to have the concept of
232                          * "file" symbolic links as being different from
233                          * "directory" symbolic links...  so
234                          * FILE_ATTRIBUTE_DIRECTORY needs to be set on the
235                          * symbolic link if the *target* of the symbolic link is
236                          * a directory.  */
237                         struct stat stbuf;
238                         if (stat(path, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
239                                 inode->i_attributes |= FILE_ATTRIBUTE_DIRECTORY;
240                 }
241         } else {
242                 ERROR_WITH_ERRNO("Failed to read target of "
243                                  "symbolic link `%s'", path);
244                 ret = WIMLIB_ERR_READLINK;
245         }
246         return ret;
247 }
248
249 static int
250 unix_build_dentry_tree_recursive(struct wim_dentry **root_ret,
251                                  char *path,
252                                  size_t path_len,
253                                  struct add_image_params *params)
254 {
255         struct wim_dentry *root = NULL;
256         int ret = 0;
257         struct wim_inode *inode;
258
259         if (exclude_path(path, path_len, params->config, true)) {
260                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
261                     && params->progress_func)
262                 {
263                         union wimlib_progress_info info;
264                         info.scan.cur_path = path;
265                         info.scan.excluded = true;
266                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
267                 }
268                 goto out;
269         }
270
271         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
272             && params->progress_func)
273         {
274                 union wimlib_progress_info info;
275                 info.scan.cur_path = path;
276                 info.scan.excluded = false;
277                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
278         }
279
280         struct stat stbuf;
281         int (*stat_fn)(const char *restrict, struct stat *restrict);
282         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) ||
283             (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT))
284                 stat_fn = stat;
285         else
286                 stat_fn = lstat;
287
288         ret = (*stat_fn)(path, &stbuf);
289         if (ret != 0) {
290                 ERROR_WITH_ERRNO("Failed to stat `%s'", path);
291                 goto out;
292         }
293         if (!S_ISREG(stbuf.st_mode) && !S_ISDIR(stbuf.st_mode)
294             && !S_ISLNK(stbuf.st_mode)) {
295                 ERROR("`%s' is not a regular file, directory, or symbolic link.",
296                       path);
297                 ret = WIMLIB_ERR_SPECIAL_FILE;
298                 goto out;
299         }
300
301         ret = inode_table_new_dentry(params->inode_table,
302                                      path_basename_with_len(path, path_len),
303                                      stbuf.st_ino, stbuf.st_dev, false, &root);
304         if (ret)
305                 goto out;
306
307         inode = root->d_inode;
308
309         if (inode->i_nlink > 1) /* Already captured this inode? */
310                 goto out;
311
312 #ifdef HAVE_STAT_NANOSECOND_PRECISION
313         inode->i_creation_time = timespec_to_wim_timestamp(stbuf.st_mtim);
314         inode->i_last_write_time = timespec_to_wim_timestamp(stbuf.st_mtim);
315         inode->i_last_access_time = timespec_to_wim_timestamp(stbuf.st_atim);
316 #else
317         inode->i_creation_time = unix_timestamp_to_wim(stbuf.st_mtime);
318         inode->i_last_write_time = unix_timestamp_to_wim(stbuf.st_mtime);
319         inode->i_last_access_time = unix_timestamp_to_wim(stbuf.st_atime);
320 #endif
321         inode->i_resolved = 1;
322         if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
323                 ret = inode_set_unix_data(inode, stbuf.st_uid,
324                                           stbuf.st_gid,
325                                           stbuf.st_mode,
326                                           params->lookup_table,
327                                           UNIX_DATA_ALL | UNIX_DATA_CREATE);
328                 if (ret)
329                         goto out;
330         }
331         params->add_image_flags &=
332                 ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
333         if (S_ISREG(stbuf.st_mode))
334                 ret = unix_capture_regular_file(path, stbuf.st_size,
335                                                 inode, params->lookup_table);
336         else if (S_ISDIR(stbuf.st_mode))
337                 ret = unix_capture_directory(root, path, path_len, params);
338         else
339                 ret = unix_capture_symlink(&root, path, inode, params);
340 out:
341         if (ret == 0)
342                 *root_ret = root;
343         else
344                 free_dentry_tree(root, params->lookup_table);
345         return ret;
346 }
347
348 /*
349  * unix_build_dentry_tree():
350  *      Builds a tree of WIM dentries from an on-disk directory tree (UNIX
351  *      version; no NTFS-specific data is captured).
352  *
353  * @root_ret:   Place to return a pointer to the root of the dentry tree.  Only
354  *              modified if successful.  Set to NULL if the file or directory was
355  *              excluded from capture.
356  *
357  * @root_disk_path:  The path to the root of the directory tree on disk.
358  *
359  * @params:     See doc for `struct add_image_params'.
360  *
361  * @return:     0 on success, nonzero on failure.  It is a failure if any of
362  *              the files cannot be `stat'ed, or if any of the needed
363  *              directories cannot be opened or read.  Failure to add the files
364  *              to the WIM may still occur later when trying to actually read
365  *              the on-disk files during a call to wimlib_write() or
366  *              wimlib_overwrite().
367  */
368 static int
369 unix_build_dentry_tree(struct wim_dentry **root_ret,
370                        const char *root_disk_path,
371                        struct add_image_params *params)
372 {
373         char *path_buf;
374         int ret;
375         size_t path_len;
376         size_t path_bufsz;
377
378         {
379                 struct stat root_stbuf;
380                 if (stat(root_disk_path, &root_stbuf)) {
381                         ERROR_WITH_ERRNO("Failed to stat \"%s\"", root_disk_path);
382                         return WIMLIB_ERR_STAT;
383                 }
384
385                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
386                     !S_ISDIR(root_stbuf.st_mode))
387                 {
388                         ERROR("Root of capture \"%s\" is not a directory",
389                               root_disk_path);
390                         return WIMLIB_ERR_NOTDIR;
391                 }
392                 params->capture_root_ino = root_stbuf.st_ino;
393                 params->capture_root_dev = root_stbuf.st_dev;
394         }
395
396         path_bufsz = min(32790, PATH_MAX + 1);
397         path_len = strlen(root_disk_path);
398
399         if (path_len >= path_bufsz)
400                 return WIMLIB_ERR_INVALID_PARAM;
401
402         path_buf = MALLOC(path_bufsz);
403         if (!path_buf)
404                 return WIMLIB_ERR_NOMEM;
405         memcpy(path_buf, root_disk_path, path_len + 1);
406
407         ret = unix_build_dentry_tree_recursive(root_ret, path_buf,
408                                                path_len, params);
409         FREE(path_buf);
410         return ret;
411 }
412 #endif /* !__WIN32__ */
413
414 static bool
415 match_pattern(const tchar *path,
416               const tchar *path_basename,
417               const struct wimlib_pattern_list *list)
418 {
419         for (size_t i = 0; i < list->num_pats; i++) {
420
421                 const tchar *pat = list->pats[i];
422                 const tchar *string;
423
424                 if (*pat == T('/')) {
425                         /* Absolute path from root of capture */
426                         string = path;
427                 } else {
428                         if (tstrchr(pat, T('/')))
429                                 /* Relative path from root of capture */
430                                 string = path + 1;
431                         else
432                                 /* A file name pattern */
433                                 string = path_basename;
434                 }
435
436                 /* Warning: on Windows native builds, fnmatch() calls the
437                  * replacement function in win32.c. */
438                 if (fnmatch(pat, string, FNM_PATHNAME | FNM_NOESCAPE
439                                 #ifdef FNM_CASEFOLD
440                                         | FNM_CASEFOLD
441                                 #endif
442                             ) == 0)
443                 {
444                         DEBUG("\"%"TS"\" matches the pattern \"%"TS"\"",
445                               string, pat);
446                         return true;
447                 } else {
448                         DEBUG2("\"%"TS"\" does not match the pattern \"%"TS"\"",
449                                string, pat);
450                 }
451         }
452         return false;
453 }
454
455 /* Return true if the image capture configuration file indicates we should
456  * exclude the filename @path from capture.
457  *
458  * If @exclude_prefix is %true, the part of the path up and including the name
459  * of the directory being captured is not included in the path for matching
460  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
461  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
462  * directory.
463  */
464 bool
465 exclude_path(const tchar *path, size_t path_len,
466              const struct wimlib_capture_config *config, bool exclude_prefix)
467 {
468         const tchar *basename = path_basename_with_len(path, path_len);
469         if (exclude_prefix) {
470                 wimlib_assert(path_len >= config->_prefix_num_tchars);
471                 if (!tmemcmp(config->_prefix, path, config->_prefix_num_tchars) &&
472                     path[config->_prefix_num_tchars] == T('/'))
473                 {
474                         path += config->_prefix_num_tchars;
475                 }
476         }
477         return match_pattern(path, basename, &config->exclusion_pats) &&
478                 !match_pattern(path, basename, &config->exclusion_exception_pats);
479
480 }
481
482 /* Strip leading and trailing forward slashes from a string.  Modifies it in
483  * place and returns the stripped string. */
484 static const tchar *
485 canonicalize_target_path(tchar *target_path)
486 {
487         tchar *p;
488         if (target_path == NULL)
489                 return T("");
490         for (;;) {
491                 if (*target_path == T('\0'))
492                         return target_path;
493                 else if (*target_path == T('/'))
494                         target_path++;
495                 else
496                         break;
497         }
498
499         p = tstrchr(target_path, T('\0')) - 1;
500         while (*p == T('/'))
501                 *p-- = T('\0');
502         return target_path;
503 }
504
505 /* Strip leading and trailing slashes from the target paths, and translate all
506  * backslashes in the source and target paths into forward slashes. */
507 static void
508 canonicalize_sources_and_targets(struct wimlib_capture_source *sources,
509                                  size_t num_sources)
510 {
511         while (num_sources--) {
512                 DEBUG("Canonicalizing { source: \"%"TS"\", target=\"%"TS"\"}",
513                       sources->fs_source_path,
514                       sources->wim_target_path);
515
516                 /* The Windows API can handle forward slashes.  Just get rid of
517                  * backslashes to avoid confusing other parts of the library
518                  * code. */
519                 zap_backslashes(sources->fs_source_path);
520                 if (sources->wim_target_path)
521                         zap_backslashes(sources->wim_target_path);
522
523                 sources->wim_target_path =
524                         (tchar*)canonicalize_target_path(sources->wim_target_path);
525                 DEBUG("Canonical target: \"%"TS"\"", sources->wim_target_path);
526                 sources++;
527         }
528 }
529
530 static int
531 capture_source_cmp(const void *p1, const void *p2)
532 {
533         const struct wimlib_capture_source *s1 = p1, *s2 = p2;
534         return tstrcmp(s1->wim_target_path, s2->wim_target_path);
535 }
536
537 /* Sorts the capture sources lexicographically by target path.  This occurs
538  * after leading and trailing forward slashes are stripped.
539  *
540  * One purpose of this is to make sure that target paths that are inside other
541  * target paths are added after the containing target paths. */
542 static void
543 sort_sources(struct wimlib_capture_source *sources, size_t num_sources)
544 {
545         qsort(sources, num_sources, sizeof(sources[0]), capture_source_cmp);
546 }
547
548 static int
549 check_sorted_sources(struct wimlib_capture_source *sources, size_t num_sources,
550                      int add_image_flags)
551 {
552         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
553                 if (num_sources != 1) {
554                         ERROR("Must specify exactly 1 capture source "
555                               "(the NTFS volume) in NTFS mode!");
556                         return WIMLIB_ERR_INVALID_PARAM;
557                 }
558                 if (sources[0].wim_target_path[0] != T('\0')) {
559                         ERROR("In NTFS capture mode the target path inside "
560                               "the image must be the root directory!");
561                         return WIMLIB_ERR_INVALID_PARAM;
562                 }
563         } else if (num_sources != 0) {
564                 /* This code is disabled because the current code
565                  * unconditionally attempts to do overlays.  So, duplicate
566                  * target paths are OK. */
567         #if 0
568                 if (num_sources > 1 && sources[0].wim_target_path[0] == '\0') {
569                         ERROR("Cannot specify root target when using multiple "
570                               "capture sources!");
571                         return WIMLIB_ERR_INVALID_PARAM;
572                 }
573                 for (size_t i = 0; i < num_sources - 1; i++) {
574                         size_t len = strlen(sources[i].wim_target_path);
575                         size_t j = i + 1;
576                         const char *target1 = sources[i].wim_target_path;
577                         do {
578                                 const char *target2 = sources[j].wim_target_path;
579                                 DEBUG("target1=%s, target2=%s",
580                                       target1,target2);
581                                 if (strncmp(target1, target2, len) ||
582                                     target2[len] > '/')
583                                         break;
584                                 if (target2[len] == '/') {
585                                         ERROR("Invalid target `%s': is a prefix of `%s'",
586                                               target1, target2);
587                                         return WIMLIB_ERR_INVALID_PARAM;
588                                 }
589                                 if (target2[len] == '\0') {
590                                         ERROR("Invalid target `%s': is a duplicate of `%s'",
591                                               target1, target2);
592                                         return WIMLIB_ERR_INVALID_PARAM;
593                                 }
594                         } while (++j != num_sources);
595                 }
596         #endif
597         }
598         return 0;
599
600 }
601
602 /* Creates a new directory to place in the WIM image.  This is to create parent
603  * directories that are not part of any target as needed.  */
604 static int
605 new_filler_directory(const tchar *name, struct wim_dentry **dentry_ret)
606 {
607         int ret;
608         struct wim_dentry *dentry;
609
610         DEBUG("Creating filler directory \"%"TS"\"", name);
611         ret = new_dentry_with_inode(name, &dentry);
612         if (ret == 0) {
613                 /* Leave the inode number as 0; this is allowed for non
614                  * hard-linked files. */
615                 dentry->d_inode->i_resolved = 1;
616                 dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
617                 *dentry_ret = dentry;
618         }
619         return ret;
620 }
621
622 /* Overlays @branch onto @target, both of which must be directories. */
623 static int
624 do_overlay(struct wim_dentry *target, struct wim_dentry *branch)
625 {
626         struct rb_root *rb_root;
627
628         DEBUG("Doing overlay \"%"WS"\" => \"%"WS"\"",
629               branch->file_name, target->file_name);
630
631         if (!dentry_is_directory(branch) || !dentry_is_directory(target)) {
632                 ERROR("Cannot overlay \"%"WS"\" onto existing dentry: "
633                       "is not directory-on-directory!", branch->file_name);
634                 return WIMLIB_ERR_INVALID_OVERLAY;
635         }
636
637         rb_root = &branch->d_inode->i_children;
638         while (rb_root->rb_node) { /* While @branch has children... */
639                 struct wim_dentry *child = rbnode_dentry(rb_root->rb_node);
640                 struct wim_dentry *existing;
641
642                 /* Move @child to the directory @target */
643                 unlink_dentry(child);
644                 existing = dentry_add_child(target, child);
645
646                 /* File or directory with same name already exists */
647                 if (existing) {
648                         int ret;
649                         ret = do_overlay(existing, child);
650                         if (ret) {
651                                 /* Overlay failed.  Revert the change to avoid
652                                  * leaking the directory tree rooted at @child.
653                                  * */
654                                 dentry_add_child(branch, child);
655                                 return ret;
656                         }
657                 }
658         }
659         free_dentry(branch);
660         return 0;
661 }
662
663 /* Attach or overlay a branch onto the WIM image.
664  *
665  * @root_p:
666  *      Pointer to the root of the WIM image, or pointer to NULL if it has not
667  *      been created yet.
668  * @branch
669  *      Branch to add.
670  * @target_path:
671  *      Path in the WIM image to add the branch, with leading and trailing
672  *      slashes stripped.
673  */
674 static int
675 attach_branch(struct wim_dentry **root_p, struct wim_dentry *branch,
676               tchar *target_path)
677 {
678         tchar *slash;
679         struct wim_dentry *dentry, *parent, *target;
680         int ret;
681
682         DEBUG("Attaching branch \"%"WS"\" => \"%"TS"\"",
683               branch->file_name, target_path);
684
685         if (*target_path == T('\0')) {
686                 /* Target: root directory */
687                 if (*root_p) {
688                         /* Overlay on existing root */
689                         return do_overlay(*root_p, branch);
690                 } else  {
691                         /* Set as root */
692                         *root_p = branch;
693                         return 0;
694                 }
695         }
696
697         /* Adding a non-root branch.  Create root if it hasn't been created
698          * already. */
699         if (!*root_p) {
700                 ret  = new_filler_directory(T(""), root_p);
701                 if (ret)
702                         return ret;
703         }
704
705         /* Walk the path to the branch, creating filler directories as needed.
706          * */
707         parent = *root_p;
708         while ((slash = tstrchr(target_path, T('/')))) {
709                 *slash = T('\0');
710                 dentry = get_dentry_child_with_name(parent, target_path);
711                 if (!dentry) {
712                         ret = new_filler_directory(target_path, &dentry);
713                         if (ret)
714                                 return ret;
715                         dentry_add_child(parent, dentry);
716                 }
717                 parent = dentry;
718                 target_path = slash;
719                 /* Skip over slashes.  Note: this cannot overrun the length of
720                  * the string because the last character cannot be a slash, as
721                  * trailing slashes were tripped.  */
722                 do {
723                         ++target_path;
724                 } while (*target_path == T('/'));
725         }
726
727         /* If the target path already existed, overlay the branch onto it.
728          * Otherwise, set the branch as the target path. */
729         target = get_dentry_child_with_utf16le_name(parent, branch->file_name,
730                                                     branch->file_name_nbytes);
731         if (target) {
732                 return do_overlay(target, branch);
733         } else {
734                 dentry_add_child(parent, branch);
735                 return 0;
736         }
737 }
738
739 static int
740 canonicalize_pat(tchar **pat_p)
741 {
742         tchar *pat = *pat_p;
743
744         /* Turn all backslashes in the pattern into forward slashes. */
745         zap_backslashes(pat);
746
747         if (*pat != T('/') && *pat != T('\0') && *(pat + 1) == T(':')) {
748                 /* Pattern begins with drive letter */
749                 if (*(pat + 2) != T('/')) {
750                         /* Something like c:file, which is actually a path
751                          * relative to the current working directory on the c:
752                          * drive.  We require paths with drive letters to be
753                          * absolute. */
754                         ERROR("Invalid path \"%"TS"\"; paths including drive letters "
755                               "must be absolute!", pat);
756                         ERROR("Maybe try \"%"TC":/%"TS"\"?",
757                               *pat, pat + 2);
758                         return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
759                 }
760
761                 WARNING("Pattern \"%"TS"\" starts with a drive letter, which is "
762                         "being removed.", pat);
763                 /* Strip the drive letter */
764                 pat += 2;
765                 *pat_p = pat;
766         }
767         return 0;
768 }
769
770 static int
771 canonicalize_pat_list(struct wimlib_pattern_list *pat_list)
772 {
773         int ret = 0;
774         for (size_t i = 0; i < pat_list->num_pats; i++) {
775                 ret = canonicalize_pat(&pat_list->pats[i]);
776                 if (ret)
777                         break;
778         }
779         return ret;
780 }
781
782 static int
783 canonicalize_capture_config(struct wimlib_capture_config *config)
784 {
785         int ret = canonicalize_pat_list(&config->exclusion_pats);
786         if (ret)
787                 return ret;
788         return canonicalize_pat_list(&config->exclusion_exception_pats);
789 }
790
791 WIMLIBAPI int
792 wimlib_add_image_multisource(WIMStruct *w,
793                              struct wimlib_capture_source *sources,
794                              size_t num_sources,
795                              const tchar *name,
796                              struct wimlib_capture_config *config,
797                              int add_image_flags,
798                              wimlib_progress_func_t progress_func)
799 {
800         int (*capture_tree)(struct wim_dentry **,
801                             const tchar *,
802                             struct add_image_params *);
803         void *extra_arg;
804         struct wim_dentry *root_dentry;
805         struct wim_dentry *branch;
806         struct wim_security_data *sd;
807         struct wim_image_metadata *imd;
808         struct wim_inode_table inode_table;
809         struct list_head unhashed_streams;
810         struct add_image_params params;
811         int ret;
812         struct sd_set sd_set;
813 #ifdef WITH_NTFS_3G
814         struct _ntfs_volume *ntfs_vol = NULL;
815 #endif
816
817         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
818 #ifdef WITH_NTFS_3G
819                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
820                         ERROR("Cannot dereference files when capturing directly from NTFS");
821                         return WIMLIB_ERR_INVALID_PARAM;
822                 }
823                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
824                         ERROR("Capturing UNIX owner and mode not supported "
825                               "when capturing directly from NTFS");
826                         return WIMLIB_ERR_INVALID_PARAM;
827                 }
828                 capture_tree = build_dentry_tree_ntfs;
829                 extra_arg = &ntfs_vol;
830 #else
831                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
832                       "        cannot capture a WIM image directly from a NTFS volume!");
833                 return WIMLIB_ERR_UNSUPPORTED;
834 #endif
835         } else {
836         #ifdef __WIN32__
837                 capture_tree = win32_build_dentry_tree;
838         #else
839                 capture_tree = unix_build_dentry_tree;
840         #endif
841                 extra_arg = NULL;
842         }
843
844 #ifdef __WIN32__
845         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
846                 ERROR("Capturing UNIX-specific data is not supported on Windows");
847                 return WIMLIB_ERR_INVALID_PARAM;
848         }
849         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
850                 ERROR("Dereferencing symbolic links is not supported on Windows");
851                 return WIMLIB_ERR_INVALID_PARAM;
852         }
853 #endif
854
855         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
856                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
857
858         if ((add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_RPFIX |
859                                 WIMLIB_ADD_IMAGE_FLAG_RPFIX)) ==
860                 (WIMLIB_ADD_IMAGE_FLAG_RPFIX | WIMLIB_ADD_IMAGE_FLAG_NORPFIX))
861         {
862                 ERROR("Cannot specify RPFIX and NORPFIX flags at the same time!");
863                 return WIMLIB_ERR_INVALID_PARAM;
864         }
865
866         if ((add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_RPFIX |
867                                 WIMLIB_ADD_IMAGE_FLAG_NORPFIX)) == 0)
868         {
869                 /* Do reparse-point fixups by default if the header flag is set
870                  * from previous images, or if this is the first image being
871                  * added. */
872                 if ((w->hdr.flags & WIM_HDR_FLAG_RP_FIX) || w->hdr.image_count == 0)
873                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
874         }
875
876         if (!name || !*name) {
877                 ERROR("Must specify a non-empty string for the image name");
878                 return WIMLIB_ERR_INVALID_PARAM;
879         }
880
881         if (w->hdr.total_parts != 1) {
882                 ERROR("Cannot add an image to a split WIM");
883                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
884         }
885
886         if (wimlib_image_name_in_use(w, name)) {
887                 ERROR("There is already an image named \"%"TS"\" in the WIM!",
888                       name);
889                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
890         }
891
892         if (!config) {
893                 DEBUG("Capture config not provided; using empty config");
894                 config = alloca(sizeof(*config));
895                 memset(config, 0, sizeof(*config));
896         }
897
898         ret = canonicalize_capture_config(config);
899         if (ret)
900                 goto out;
901
902         ret = init_inode_table(&inode_table, 9001);
903         if (ret)
904                 goto out;
905
906         DEBUG("Allocating security data");
907         sd = CALLOC(1, sizeof(struct wim_security_data));
908         if (!sd) {
909                 ret = WIMLIB_ERR_NOMEM;
910                 goto out_destroy_inode_table;
911         }
912         sd->total_length = 8;
913
914         sd_set.sd = sd;
915         sd_set.rb_root.rb_node = NULL;
916
917
918         DEBUG("Using %zu capture sources", num_sources);
919         canonicalize_sources_and_targets(sources, num_sources);
920         sort_sources(sources, num_sources);
921         ret = check_sorted_sources(sources, num_sources, add_image_flags);
922         if (ret) {
923                 ret = WIMLIB_ERR_INVALID_PARAM;
924                 goto out_free_security_data;
925         }
926
927         INIT_LIST_HEAD(&unhashed_streams);
928         w->lookup_table->unhashed_streams = &unhashed_streams;
929         root_dentry = NULL;
930
931         params.lookup_table = w->lookup_table;
932         params.inode_table = &inode_table;
933         params.sd_set = &sd_set;
934         params.config = config;
935         params.add_image_flags = add_image_flags;
936         params.progress_func = progress_func;
937         params.extra_arg = extra_arg;
938         for (size_t i = 0; i < num_sources; i++) {
939                 int flags;
940                 union wimlib_progress_info progress;
941
942                 DEBUG("Building dentry tree for source %zu of %zu "
943                       "(\"%"TS"\" => \"%"TS"\")", i + 1, num_sources,
944                       sources[i].fs_source_path,
945                       sources[i].wim_target_path);
946                 if (progress_func) {
947                         memset(&progress, 0, sizeof(progress));
948                         progress.scan.source = sources[i].fs_source_path;
949                         progress.scan.wim_target_path = sources[i].wim_target_path;
950                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
951                 }
952                 config->_prefix = sources[i].fs_source_path;
953                 config->_prefix_num_tchars = tstrlen(sources[i].fs_source_path);
954                 flags = add_image_flags | WIMLIB_ADD_IMAGE_FLAG_SOURCE;
955                 if (!*sources[i].wim_target_path)
956                         flags |= WIMLIB_ADD_IMAGE_FLAG_ROOT;
957                 ret = (*capture_tree)(&branch, sources[i].fs_source_path,
958                                       &params);
959                 if (ret) {
960                         ERROR("Failed to build dentry tree for `%"TS"'",
961                               sources[i].fs_source_path);
962                         goto out_free_dentry_tree;
963                 }
964                 if (branch) {
965                         /* Use the target name, not the source name, for
966                          * the root of each branch from a capture
967                          * source.  (This will also set the root dentry
968                          * of the entire image to be unnamed.) */
969                         ret = set_dentry_name(branch,
970                                               path_basename(sources[i].wim_target_path));
971                         if (ret)
972                                 goto out_free_branch;
973
974                         ret = attach_branch(&root_dentry, branch,
975                                             sources[i].wim_target_path);
976                         if (ret)
977                                 goto out_free_branch;
978                 }
979                 if (progress_func)
980                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
981         }
982
983         if (root_dentry == NULL) {
984                 ret = new_filler_directory(T(""), &root_dentry);
985                 if (ret)
986                         goto out_free_dentry_tree;
987         }
988
989         ret = add_new_dentry_tree(w, root_dentry, sd);
990
991         if (ret) {
992 #ifdef WITH_NTFS_3G
993                 if (ntfs_vol)
994                         do_ntfs_umount(ntfs_vol);
995 #endif
996                 goto out_free_dentry_tree;
997         }
998
999         imd = w->image_metadata[w->hdr.image_count - 1];
1000         list_transfer(&unhashed_streams, &imd->unhashed_streams);
1001
1002 #ifdef WITH_NTFS_3G
1003         imd->ntfs_vol = ntfs_vol;
1004 #endif
1005
1006         DEBUG("Assigning hard link group IDs");
1007         inode_table_prepare_inode_list(&inode_table, &imd->inode_list);
1008
1009         ret = xml_add_image(w, name);
1010         if (ret)
1011                 goto out_put_imd;
1012
1013         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
1014                 wimlib_set_boot_idx(w, w->hdr.image_count);
1015
1016         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX)
1017                 w->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
1018
1019         ret = 0;
1020         goto out_destroy_inode_table;
1021 out_put_imd:
1022         put_image_metadata(w->image_metadata[--w->hdr.image_count],
1023                            w->lookup_table);
1024         goto out_destroy_inode_table;
1025 out_free_branch:
1026         free_dentry_tree(branch, w->lookup_table);
1027 out_free_dentry_tree:
1028         free_dentry_tree(root_dentry, w->lookup_table);
1029 out_free_security_data:
1030         free_security_data(sd);
1031 out_destroy_inode_table:
1032         destroy_inode_table(&inode_table);
1033         destroy_sd_set(&sd_set);
1034 out:
1035         return ret;
1036 }
1037
1038 WIMLIBAPI int
1039 wimlib_add_image(WIMStruct *w,
1040                  const tchar *source,
1041                  const tchar *name,
1042                  struct wimlib_capture_config *config,
1043                  int add_image_flags,
1044                  wimlib_progress_func_t progress_func)
1045 {
1046         if (!source || !*source)
1047                 return WIMLIB_ERR_INVALID_PARAM;
1048
1049         tchar *fs_source_path = TSTRDUP(source);
1050         int ret;
1051         struct wimlib_capture_source capture_src = {
1052                 .fs_source_path = fs_source_path,
1053                 .wim_target_path = NULL,
1054                 .reserved = 0,
1055         };
1056         ret = wimlib_add_image_multisource(w, &capture_src, 1, name,
1057                                            config, add_image_flags,
1058                                            progress_func);
1059         FREE(fs_source_path);
1060         return ret;
1061 }