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