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