]> wimlib.net Git - wimlib/blob - src/add_image.c
mount_image.c: Use fuse_context.umask only when available
[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 = capture_fixup_absolute_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 = wim_inode_set_symlink(inode, dest, params->lookup_table);
229                 if (ret == 0) {
230                         /* Unfortunately, Windows seems to have the concept of
231                          * "file" symbolic links as being different from
232                          * "directory" symbolic links...  so
233                          * FILE_ATTRIBUTE_DIRECTORY needs to be set on the
234                          * symbolic link if the *target* of the symbolic link is
235                          * a directory.  */
236                         struct stat stbuf;
237                         if (stat(path, &stbuf) == 0 && S_ISDIR(stbuf.st_mode))
238                                 inode->i_attributes |= FILE_ATTRIBUTE_DIRECTORY;
239                 }
240         } else {
241                 ERROR_WITH_ERRNO("Failed to read target of "
242                                  "symbolic link `%s'", path);
243                 ret = WIMLIB_ERR_READLINK;
244         }
245         return ret;
246 }
247
248 static int
249 unix_build_dentry_tree_recursive(struct wim_dentry **root_ret,
250                                  char *path,
251                                  size_t path_len,
252                                  struct add_image_params *params)
253 {
254         struct wim_dentry *root = NULL;
255         int ret = 0;
256         struct wim_inode *inode;
257
258         if (exclude_path(path, path_len, params->config, true)) {
259                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE)
260                     && params->progress_func)
261                 {
262                         union wimlib_progress_info info;
263                         info.scan.cur_path = path;
264                         info.scan.excluded = true;
265                         params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
266                 }
267                 goto out;
268         }
269
270         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
271             && params->progress_func)
272         {
273                 union wimlib_progress_info info;
274                 info.scan.cur_path = path;
275                 info.scan.excluded = false;
276                 params->progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
277         }
278
279         struct stat stbuf;
280         int (*stat_fn)(const char *restrict, struct stat *restrict);
281         if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) ||
282             (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT))
283                 stat_fn = stat;
284         else
285                 stat_fn = lstat;
286
287         ret = (*stat_fn)(path, &stbuf);
288         if (ret != 0) {
289                 ERROR_WITH_ERRNO("Failed to stat `%s'", path);
290                 goto out;
291         }
292         if (!S_ISREG(stbuf.st_mode) && !S_ISDIR(stbuf.st_mode)
293             && !S_ISLNK(stbuf.st_mode)) {
294                 ERROR("`%s' is not a regular file, directory, or symbolic link.",
295                       path);
296                 ret = WIMLIB_ERR_SPECIAL_FILE;
297                 goto out;
298         }
299
300         ret = inode_table_new_dentry(params->inode_table,
301                                      path_basename_with_len(path, path_len),
302                                      stbuf.st_ino, stbuf.st_dev, false, &root);
303         if (ret)
304                 goto out;
305
306         inode = root->d_inode;
307
308         if (inode->i_nlink > 1) /* Already captured this inode? */
309                 goto out;
310
311 #ifdef HAVE_STAT_NANOSECOND_PRECISION
312         inode->i_creation_time = timespec_to_wim_timestamp(stbuf.st_mtim);
313         inode->i_last_write_time = timespec_to_wim_timestamp(stbuf.st_mtim);
314         inode->i_last_access_time = timespec_to_wim_timestamp(stbuf.st_atim);
315 #else
316         inode->i_creation_time = unix_timestamp_to_wim(stbuf.st_mtime);
317         inode->i_last_write_time = unix_timestamp_to_wim(stbuf.st_mtime);
318         inode->i_last_access_time = unix_timestamp_to_wim(stbuf.st_atime);
319 #endif
320         inode->i_resolved = 1;
321         if (params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
322                 ret = inode_set_unix_data(inode, stbuf.st_uid,
323                                           stbuf.st_gid,
324                                           stbuf.st_mode,
325                                           params->lookup_table,
326                                           UNIX_DATA_ALL | UNIX_DATA_CREATE);
327                 if (ret)
328                         goto out;
329         }
330         params->add_image_flags &=
331                 ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
332         if (S_ISREG(stbuf.st_mode))
333                 ret = unix_capture_regular_file(path, stbuf.st_size,
334                                                 inode, params->lookup_table);
335         else if (S_ISDIR(stbuf.st_mode))
336                 ret = unix_capture_directory(root, path, path_len, params);
337         else
338                 ret = unix_capture_symlink(&root, path, inode, params);
339 out:
340         if (ret == 0)
341                 *root_ret = root;
342         else
343                 free_dentry_tree(root, params->lookup_table);
344         return ret;
345 }
346
347 /*
348  * unix_build_dentry_tree():
349  *      Builds a tree of WIM dentries from an on-disk directory tree (UNIX
350  *      version; no NTFS-specific data is captured).
351  *
352  * @root_ret:   Place to return a pointer to the root of the dentry tree.  Only
353  *              modified if successful.  Set to NULL if the file or directory was
354  *              excluded from capture.
355  *
356  * @root_disk_path:  The path to the root of the directory tree on disk.
357  *
358  * @params:     See doc for `struct add_image_params'.
359  *
360  * @return:     0 on success, nonzero on failure.  It is a failure if any of
361  *              the files cannot be `stat'ed, or if any of the needed
362  *              directories cannot be opened or read.  Failure to add the files
363  *              to the WIM may still occur later when trying to actually read
364  *              the on-disk files during a call to wimlib_write() or
365  *              wimlib_overwrite().
366  */
367 static int
368 unix_build_dentry_tree(struct wim_dentry **root_ret,
369                        const char *root_disk_path,
370                        struct add_image_params *params)
371 {
372         char *path_buf;
373         int ret;
374         size_t path_len;
375         size_t path_bufsz;
376
377         {
378                 struct stat root_stbuf;
379                 if (stat(root_disk_path, &root_stbuf)) {
380                         ERROR_WITH_ERRNO("Failed to stat \"%s\"", root_disk_path);
381                         return WIMLIB_ERR_STAT;
382                 }
383
384                 if ((params->add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
385                     !S_ISDIR(root_stbuf.st_mode))
386                 {
387                         ERROR("Root of capture \"%s\" is not a directory",
388                               root_disk_path);
389                         return WIMLIB_ERR_NOTDIR;
390                 }
391                 params->capture_root_ino = root_stbuf.st_ino;
392                 params->capture_root_dev = root_stbuf.st_dev;
393         }
394
395         path_bufsz = min(32790, PATH_MAX + 1);
396         path_len = strlen(root_disk_path);
397
398         if (path_len >= path_bufsz)
399                 return WIMLIB_ERR_INVALID_PARAM;
400
401         path_buf = MALLOC(path_bufsz);
402         if (!path_buf)
403                 return WIMLIB_ERR_NOMEM;
404         memcpy(path_buf, root_disk_path, path_len + 1);
405
406         ret = unix_build_dentry_tree_recursive(root_ret, path_buf,
407                                                path_len, params);
408         FREE(path_buf);
409         return ret;
410 }
411 #endif /* !__WIN32__ */
412
413 static bool
414 match_pattern(const tchar *path,
415               const tchar *path_basename,
416               const struct wimlib_pattern_list *list)
417 {
418         for (size_t i = 0; i < list->num_pats; i++) {
419
420                 const tchar *pat = list->pats[i];
421                 const tchar *string;
422
423                 if (*pat == T('/')) {
424                         /* Absolute path from root of capture */
425                         string = path;
426                 } else {
427                         if (tstrchr(pat, T('/')))
428                                 /* Relative path from root of capture */
429                                 string = path + 1;
430                         else
431                                 /* A file name pattern */
432                                 string = path_basename;
433                 }
434
435                 /* Warning: on Windows native builds, fnmatch() calls the
436                  * replacement function in win32.c. */
437                 if (fnmatch(pat, string, FNM_PATHNAME | FNM_NOESCAPE
438                                 #ifdef FNM_CASEFOLD
439                                         | FNM_CASEFOLD
440                                 #endif
441                             ) == 0)
442                 {
443                         DEBUG("\"%"TS"\" matches the pattern \"%"TS"\"",
444                               string, pat);
445                         return true;
446                 } else {
447                         DEBUG2("\"%"TS"\" does not match the pattern \"%"TS"\"",
448                                string, pat);
449                 }
450         }
451         return false;
452 }
453
454 /* Return true if the image capture configuration file indicates we should
455  * exclude the filename @path from capture.
456  *
457  * If @exclude_prefix is %true, the part of the path up and including the name
458  * of the directory being captured is not included in the path for matching
459  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
460  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
461  * directory.
462  */
463 bool
464 exclude_path(const tchar *path, size_t path_len,
465              const struct wimlib_capture_config *config, bool exclude_prefix)
466 {
467         const tchar *basename = path_basename_with_len(path, path_len);
468         if (exclude_prefix) {
469                 wimlib_assert(path_len >= config->_prefix_num_tchars);
470                 if (!tmemcmp(config->_prefix, path, config->_prefix_num_tchars) &&
471                     path[config->_prefix_num_tchars] == T('/'))
472                 {
473                         path += config->_prefix_num_tchars;
474                 }
475         }
476         return match_pattern(path, basename, &config->exclusion_pats) &&
477                 !match_pattern(path, basename, &config->exclusion_exception_pats);
478
479 }
480
481 /* Strip leading and trailing forward slashes from a string.  Modifies it in
482  * place and returns the stripped string. */
483 static const tchar *
484 canonicalize_target_path(tchar *target_path)
485 {
486         tchar *p;
487         if (target_path == NULL)
488                 return T("");
489         for (;;) {
490                 if (*target_path == T('\0'))
491                         return target_path;
492                 else if (*target_path == T('/'))
493                         target_path++;
494                 else
495                         break;
496         }
497
498         p = tstrchr(target_path, T('\0')) - 1;
499         while (*p == T('/'))
500                 *p-- = T('\0');
501         return target_path;
502 }
503
504 /* Strip leading and trailing slashes from the target paths, and translate all
505  * backslashes in the source and target paths into forward slashes. */
506 static void
507 canonicalize_sources_and_targets(struct wimlib_capture_source *sources,
508                                  size_t num_sources)
509 {
510         while (num_sources--) {
511                 DEBUG("Canonicalizing { source: \"%"TS"\", target=\"%"TS"\"}",
512                       sources->fs_source_path,
513                       sources->wim_target_path);
514
515                 /* The Windows API can handle forward slashes.  Just get rid of
516                  * backslashes to avoid confusing other parts of the library
517                  * code. */
518                 zap_backslashes(sources->fs_source_path);
519                 if (sources->wim_target_path)
520                         zap_backslashes(sources->wim_target_path);
521
522                 sources->wim_target_path =
523                         (tchar*)canonicalize_target_path(sources->wim_target_path);
524                 DEBUG("Canonical target: \"%"TS"\"", sources->wim_target_path);
525                 sources++;
526         }
527 }
528
529 static int
530 capture_source_cmp(const void *p1, const void *p2)
531 {
532         const struct wimlib_capture_source *s1 = p1, *s2 = p2;
533         return tstrcmp(s1->wim_target_path, s2->wim_target_path);
534 }
535
536 /* Sorts the capture sources lexicographically by target path.  This occurs
537  * after leading and trailing forward slashes are stripped.
538  *
539  * One purpose of this is to make sure that target paths that are inside other
540  * target paths are added after the containing target paths. */
541 static void
542 sort_sources(struct wimlib_capture_source *sources, size_t num_sources)
543 {
544         qsort(sources, num_sources, sizeof(sources[0]), capture_source_cmp);
545 }
546
547 static int
548 check_sorted_sources(struct wimlib_capture_source *sources, size_t num_sources,
549                      int add_image_flags)
550 {
551         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
552                 if (num_sources != 1) {
553                         ERROR("Must specify exactly 1 capture source "
554                               "(the NTFS volume) in NTFS mode!");
555                         return WIMLIB_ERR_INVALID_PARAM;
556                 }
557                 if (sources[0].wim_target_path[0] != T('\0')) {
558                         ERROR("In NTFS capture mode the target path inside "
559                               "the image must be the root directory!");
560                         return WIMLIB_ERR_INVALID_PARAM;
561                 }
562         } else if (num_sources != 0) {
563                 /* This code is disabled because the current code
564                  * unconditionally attempts to do overlays.  So, duplicate
565                  * target paths are OK. */
566         #if 0
567                 if (num_sources > 1 && sources[0].wim_target_path[0] == '\0') {
568                         ERROR("Cannot specify root target when using multiple "
569                               "capture sources!");
570                         return WIMLIB_ERR_INVALID_PARAM;
571                 }
572                 for (size_t i = 0; i < num_sources - 1; i++) {
573                         size_t len = strlen(sources[i].wim_target_path);
574                         size_t j = i + 1;
575                         const char *target1 = sources[i].wim_target_path;
576                         do {
577                                 const char *target2 = sources[j].wim_target_path;
578                                 DEBUG("target1=%s, target2=%s",
579                                       target1,target2);
580                                 if (strncmp(target1, target2, len) ||
581                                     target2[len] > '/')
582                                         break;
583                                 if (target2[len] == '/') {
584                                         ERROR("Invalid target `%s': is a prefix of `%s'",
585                                               target1, target2);
586                                         return WIMLIB_ERR_INVALID_PARAM;
587                                 }
588                                 if (target2[len] == '\0') {
589                                         ERROR("Invalid target `%s': is a duplicate of `%s'",
590                                               target1, target2);
591                                         return WIMLIB_ERR_INVALID_PARAM;
592                                 }
593                         } while (++j != num_sources);
594                 }
595         #endif
596         }
597         return 0;
598
599 }
600
601 /* Creates a new directory to place in the WIM image.  This is to create parent
602  * directories that are not part of any target as needed.  */
603 static int
604 new_filler_directory(const tchar *name, struct wim_dentry **dentry_ret)
605 {
606         int ret;
607         struct wim_dentry *dentry;
608
609         DEBUG("Creating filler directory \"%"TS"\"", name);
610         ret = new_dentry_with_inode(name, &dentry);
611         if (ret == 0) {
612                 /* Leave the inode number as 0; this is allowed for non
613                  * hard-linked files. */
614                 dentry->d_inode->i_resolved = 1;
615                 dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
616                 *dentry_ret = dentry;
617         }
618         return ret;
619 }
620
621 /* Overlays @branch onto @target, both of which must be directories. */
622 static int
623 do_overlay(struct wim_dentry *target, struct wim_dentry *branch)
624 {
625         struct rb_root *rb_root;
626
627         DEBUG("Doing overlay \"%"WS"\" => \"%"WS"\"",
628               branch->file_name, target->file_name);
629
630         if (!dentry_is_directory(branch) || !dentry_is_directory(target)) {
631                 ERROR("Cannot overlay \"%"WS"\" onto existing dentry: "
632                       "is not directory-on-directory!", branch->file_name);
633                 return WIMLIB_ERR_INVALID_OVERLAY;
634         }
635
636         rb_root = &branch->d_inode->i_children;
637         while (rb_root->rb_node) { /* While @branch has children... */
638                 struct wim_dentry *child = rbnode_dentry(rb_root->rb_node);
639                 struct wim_dentry *existing;
640
641                 /* Move @child to the directory @target */
642                 unlink_dentry(child);
643                 existing = dentry_add_child(target, child);
644
645                 /* File or directory with same name already exists */
646                 if (existing) {
647                         int ret;
648                         ret = do_overlay(existing, child);
649                         if (ret) {
650                                 /* Overlay failed.  Revert the change to avoid
651                                  * leaking the directory tree rooted at @child.
652                                  * */
653                                 dentry_add_child(branch, child);
654                                 return ret;
655                         }
656                 }
657         }
658         free_dentry(branch);
659         return 0;
660 }
661
662 /* Attach or overlay a branch onto the WIM image.
663  *
664  * @root_p:
665  *      Pointer to the root of the WIM image, or pointer to NULL if it has not
666  *      been created yet.
667  * @branch
668  *      Branch to add.
669  * @target_path:
670  *      Path in the WIM image to add the branch, with leading and trailing
671  *      slashes stripped.
672  */
673 static int
674 attach_branch(struct wim_dentry **root_p, struct wim_dentry *branch,
675               tchar *target_path)
676 {
677         tchar *slash;
678         struct wim_dentry *dentry, *parent, *target;
679         int ret;
680
681         DEBUG("Attaching branch \"%"WS"\" => \"%"TS"\"",
682               branch->file_name, target_path);
683
684         if (*target_path == T('\0')) {
685                 /* Target: root directory */
686                 if (*root_p) {
687                         /* Overlay on existing root */
688                         return do_overlay(*root_p, branch);
689                 } else  {
690                         /* Set as root */
691                         *root_p = branch;
692                         return 0;
693                 }
694         }
695
696         /* Adding a non-root branch.  Create root if it hasn't been created
697          * already. */
698         if (!*root_p) {
699                 ret  = new_filler_directory(T(""), root_p);
700                 if (ret)
701                         return ret;
702         }
703
704         /* Walk the path to the branch, creating filler directories as needed.
705          * */
706         parent = *root_p;
707         while ((slash = tstrchr(target_path, T('/')))) {
708                 *slash = T('\0');
709                 dentry = get_dentry_child_with_name(parent, target_path);
710                 if (!dentry) {
711                         ret = new_filler_directory(target_path, &dentry);
712                         if (ret)
713                                 return ret;
714                         dentry_add_child(parent, dentry);
715                 }
716                 parent = dentry;
717                 target_path = slash;
718                 /* Skip over slashes.  Note: this cannot overrun the length of
719                  * the string because the last character cannot be a slash, as
720                  * trailing slashes were tripped.  */
721                 do {
722                         ++target_path;
723                 } while (*target_path == T('/'));
724         }
725
726         /* If the target path already existed, overlay the branch onto it.
727          * Otherwise, set the branch as the target path. */
728         target = get_dentry_child_with_utf16le_name(parent, branch->file_name,
729                                                     branch->file_name_nbytes);
730         if (target) {
731                 return do_overlay(target, branch);
732         } else {
733                 dentry_add_child(parent, branch);
734                 return 0;
735         }
736 }
737
738 static int
739 canonicalize_pat(tchar **pat_p)
740 {
741         tchar *pat = *pat_p;
742
743         /* Turn all backslashes in the pattern into forward slashes. */
744         zap_backslashes(pat);
745
746         if (*pat != T('/') && *pat != T('\0') && *(pat + 1) == T(':')) {
747                 /* Pattern begins with drive letter */
748                 if (*(pat + 2) != T('/')) {
749                         /* Something like c:file, which is actually a path
750                          * relative to the current working directory on the c:
751                          * drive.  We require paths with drive letters to be
752                          * absolute. */
753                         ERROR("Invalid path \"%"TS"\"; paths including drive letters "
754                               "must be absolute!", pat);
755                         ERROR("Maybe try \"%"TC":/%"TS"\"?",
756                               *pat, pat + 2);
757                         return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
758                 }
759
760                 WARNING("Pattern \"%"TS"\" starts with a drive letter, which is "
761                         "being removed.", pat);
762                 /* Strip the drive letter */
763                 pat += 2;
764                 *pat_p = pat;
765         }
766         return 0;
767 }
768
769 static int
770 canonicalize_pat_list(struct wimlib_pattern_list *pat_list)
771 {
772         int ret = 0;
773         for (size_t i = 0; i < pat_list->num_pats; i++) {
774                 ret = canonicalize_pat(&pat_list->pats[i]);
775                 if (ret)
776                         break;
777         }
778         return ret;
779 }
780
781 static int
782 canonicalize_capture_config(struct wimlib_capture_config *config)
783 {
784         int ret = canonicalize_pat_list(&config->exclusion_pats);
785         if (ret)
786                 return ret;
787         return canonicalize_pat_list(&config->exclusion_exception_pats);
788 }
789
790 WIMLIBAPI int
791 wimlib_add_image_multisource(WIMStruct *w,
792                              struct wimlib_capture_source *sources,
793                              size_t num_sources,
794                              const tchar *name,
795                              struct wimlib_capture_config *config,
796                              int add_image_flags,
797                              wimlib_progress_func_t progress_func)
798 {
799         int (*capture_tree)(struct wim_dentry **,
800                             const tchar *,
801                             struct add_image_params *);
802         void *extra_arg;
803         struct wim_dentry *root_dentry;
804         struct wim_dentry *branch;
805         struct wim_security_data *sd;
806         struct wim_image_metadata *imd;
807         struct wim_inode_table inode_table;
808         struct list_head unhashed_streams;
809         struct add_image_params params;
810         int ret;
811         struct sd_set sd_set;
812 #ifdef WITH_NTFS_3G
813         struct _ntfs_volume *ntfs_vol = NULL;
814 #endif
815
816         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
817 #ifdef WITH_NTFS_3G
818                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
819                         ERROR("Cannot dereference files when capturing directly from NTFS");
820                         return WIMLIB_ERR_INVALID_PARAM;
821                 }
822                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
823                         ERROR("Capturing UNIX owner and mode not supported "
824                               "when capturing directly from NTFS");
825                         return WIMLIB_ERR_INVALID_PARAM;
826                 }
827                 capture_tree = build_dentry_tree_ntfs;
828                 extra_arg = &ntfs_vol;
829 #else
830                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
831                       "        cannot capture a WIM image directly from a NTFS volume!");
832                 return WIMLIB_ERR_UNSUPPORTED;
833 #endif
834         } else {
835         #ifdef __WIN32__
836                 capture_tree = win32_build_dentry_tree;
837         #else
838                 capture_tree = unix_build_dentry_tree;
839         #endif
840                 extra_arg = NULL;
841         }
842
843 #ifdef __WIN32__
844         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
845                 ERROR("Capturing UNIX-specific data is not supported on Windows");
846                 return WIMLIB_ERR_INVALID_PARAM;
847         }
848         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
849                 ERROR("Dereferencing symbolic links is not supported on Windows");
850                 return WIMLIB_ERR_INVALID_PARAM;
851         }
852 #endif
853
854         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
855                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
856
857         if ((add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_RPFIX |
858                                 WIMLIB_ADD_IMAGE_FLAG_RPFIX)) ==
859                 (WIMLIB_ADD_IMAGE_FLAG_RPFIX | WIMLIB_ADD_IMAGE_FLAG_NORPFIX))
860         {
861                 ERROR("Cannot specify RPFIX and NORPFIX flags at the same time!");
862                 return WIMLIB_ERR_INVALID_PARAM;
863         }
864
865         if ((add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_RPFIX |
866                                 WIMLIB_ADD_IMAGE_FLAG_NORPFIX)) == 0)
867         {
868                 /* Do reparse-point fixups by default if the header flag is set
869                  * from previous images, or if this is the first image being
870                  * added. */
871                 if ((w->hdr.flags & WIM_HDR_FLAG_RP_FIX) || w->hdr.image_count == 0)
872                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
873         }
874
875         if (!name || !*name) {
876                 ERROR("Must specify a non-empty string for the image name");
877                 return WIMLIB_ERR_INVALID_PARAM;
878         }
879
880         if (w->hdr.total_parts != 1) {
881                 ERROR("Cannot add an image to a split WIM");
882                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
883         }
884
885         if (wimlib_image_name_in_use(w, name)) {
886                 ERROR("There is already an image named \"%"TS"\" in the WIM!",
887                       name);
888                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
889         }
890
891         if (!config) {
892                 DEBUG("Capture config not provided; using empty config");
893                 config = alloca(sizeof(*config));
894                 memset(config, 0, sizeof(*config));
895         }
896
897         ret = canonicalize_capture_config(config);
898         if (ret)
899                 goto out;
900
901         ret = init_inode_table(&inode_table, 9001);
902         if (ret)
903                 goto out;
904
905         DEBUG("Allocating security data");
906         sd = CALLOC(1, sizeof(struct wim_security_data));
907         if (!sd) {
908                 ret = WIMLIB_ERR_NOMEM;
909                 goto out_destroy_inode_table;
910         }
911         sd->total_length = 8;
912
913         sd_set.sd = sd;
914         sd_set.rb_root.rb_node = NULL;
915
916
917         DEBUG("Using %zu capture sources", num_sources);
918         canonicalize_sources_and_targets(sources, num_sources);
919         sort_sources(sources, num_sources);
920         ret = check_sorted_sources(sources, num_sources, add_image_flags);
921         if (ret) {
922                 ret = WIMLIB_ERR_INVALID_PARAM;
923                 goto out_free_security_data;
924         }
925
926         INIT_LIST_HEAD(&unhashed_streams);
927         w->lookup_table->unhashed_streams = &unhashed_streams;
928         root_dentry = NULL;
929
930         params.lookup_table = w->lookup_table;
931         params.inode_table = &inode_table;
932         params.sd_set = &sd_set;
933         params.config = config;
934         params.add_image_flags = add_image_flags;
935         params.progress_func = progress_func;
936         params.extra_arg = extra_arg;
937         for (size_t i = 0; i < num_sources; i++) {
938                 int flags;
939                 union wimlib_progress_info progress;
940
941                 DEBUG("Building dentry tree for source %zu of %zu "
942                       "(\"%"TS"\" => \"%"TS"\")", i + 1, num_sources,
943                       sources[i].fs_source_path,
944                       sources[i].wim_target_path);
945                 if (progress_func) {
946                         memset(&progress, 0, sizeof(progress));
947                         progress.scan.source = sources[i].fs_source_path;
948                         progress.scan.wim_target_path = sources[i].wim_target_path;
949                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
950                 }
951                 config->_prefix = sources[i].fs_source_path;
952                 config->_prefix_num_tchars = tstrlen(sources[i].fs_source_path);
953                 flags = add_image_flags | WIMLIB_ADD_IMAGE_FLAG_SOURCE;
954                 if (!*sources[i].wim_target_path)
955                         flags |= WIMLIB_ADD_IMAGE_FLAG_ROOT;
956                 ret = (*capture_tree)(&branch, sources[i].fs_source_path,
957                                       &params);
958                 if (ret) {
959                         ERROR("Failed to build dentry tree for `%"TS"'",
960                               sources[i].fs_source_path);
961                         goto out_free_dentry_tree;
962                 }
963                 if (branch) {
964                         /* Use the target name, not the source name, for
965                          * the root of each branch from a capture
966                          * source.  (This will also set the root dentry
967                          * of the entire image to be unnamed.) */
968                         ret = set_dentry_name(branch,
969                                               path_basename(sources[i].wim_target_path));
970                         if (ret)
971                                 goto out_free_branch;
972
973                         ret = attach_branch(&root_dentry, branch,
974                                             sources[i].wim_target_path);
975                         if (ret)
976                                 goto out_free_branch;
977                 }
978                 if (progress_func)
979                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
980         }
981
982         if (root_dentry == NULL) {
983                 ret = new_filler_directory(T(""), &root_dentry);
984                 if (ret)
985                         goto out_free_dentry_tree;
986         }
987
988         ret = add_new_dentry_tree(w, root_dentry, sd);
989
990         if (ret) {
991 #ifdef WITH_NTFS_3G
992                 if (ntfs_vol)
993                         do_ntfs_umount(ntfs_vol);
994 #endif
995                 goto out_free_dentry_tree;
996         }
997
998         imd = w->image_metadata[w->hdr.image_count - 1];
999         list_transfer(&unhashed_streams, &imd->unhashed_streams);
1000
1001 #ifdef WITH_NTFS_3G
1002         imd->ntfs_vol = ntfs_vol;
1003 #endif
1004
1005         DEBUG("Assigning hard link group IDs");
1006         inode_table_prepare_inode_list(&inode_table, &imd->inode_list);
1007
1008         ret = xml_add_image(w, name);
1009         if (ret)
1010                 goto out_put_imd;
1011
1012         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
1013                 wimlib_set_boot_idx(w, w->hdr.image_count);
1014
1015         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_RPFIX)
1016                 w->hdr.flags |= WIM_HDR_FLAG_RP_FIX;
1017
1018         ret = 0;
1019         goto out_destroy_inode_table;
1020 out_put_imd:
1021         put_image_metadata(w->image_metadata[--w->hdr.image_count],
1022                            w->lookup_table);
1023         goto out_destroy_inode_table;
1024 out_free_branch:
1025         free_dentry_tree(branch, w->lookup_table);
1026 out_free_dentry_tree:
1027         free_dentry_tree(root_dentry, w->lookup_table);
1028 out_free_security_data:
1029         free_security_data(sd);
1030 out_destroy_inode_table:
1031         destroy_inode_table(&inode_table);
1032         destroy_sd_set(&sd_set);
1033 out:
1034         return ret;
1035 }
1036
1037 WIMLIBAPI int
1038 wimlib_add_image(WIMStruct *w,
1039                  const tchar *source,
1040                  const tchar *name,
1041                  struct wimlib_capture_config *config,
1042                  int add_image_flags,
1043                  wimlib_progress_func_t progress_func)
1044 {
1045         if (!source || !*source)
1046                 return WIMLIB_ERR_INVALID_PARAM;
1047
1048         tchar *fs_source_path = TSTRDUP(source);
1049         int ret;
1050         struct wimlib_capture_source capture_src = {
1051                 .fs_source_path = fs_source_path,
1052                 .wim_target_path = NULL,
1053                 .reserved = 0,
1054         };
1055         ret = wimlib_add_image_multisource(w, &capture_src, 1, name,
1056                                            config, add_image_flags,
1057                                            progress_func);
1058         FREE(fs_source_path);
1059         return ret;
1060 }