]> wimlib.net Git - wimlib/blob - src/add_image.c
Specify hard_remove option to fuse_main() when possible
[wimlib] / src / add_image.c
1 /*
2  * add_image.c
3  */
4
5 /*
6  * Copyright (C) 2012 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 "wimlib_internal.h"
25 #include "dentry.h"
26 #include "timestamp.h"
27 #include "lookup_table.h"
28 #include "xml.h"
29 #include <string.h>
30 #include <fnmatch.h>
31 #include <ctype.h>
32 #include <sys/stat.h>
33 #include <dirent.h>
34 #include <errno.h>
35 #include <unistd.h>
36
37 /** Private flag: Used to mark that we currently adding the root directory of
38  * the WIM image. */
39 #define WIMLIB_ADD_IMAGE_FLAG_ROOT 0x80000000
40
41 /*
42  * Adds an image (given by its dentry tree) to the image metadata array of a WIM
43  * file, adds an entry to the lookup table for the image metadata, updates the
44  * image count in the header, and selects the new image.
45  *
46  * Does not update the XML data.
47  *
48  * On failure, WIMLIB_ERR_NOMEM is returned and no changes are made.  Otherwise,
49  * 0 is returned and the image metadata array of @w is modified.
50  *
51  * @w:            The WIMStruct for the WIM file.
52  * @root_dentry:  The root of the directory tree for the image.
53  * @sd:           The security data for the image.
54  */
55 int add_new_dentry_tree(WIMStruct *w, struct dentry *root_dentry,
56                         struct wim_security_data *sd)
57 {
58         struct lookup_table_entry *metadata_lte;
59         struct image_metadata *imd;
60         struct image_metadata *new_imd;
61         int ret;
62
63         wimlib_assert(root_dentry != NULL);
64
65         DEBUG("Reallocating image metadata array for image_count = %u",
66               w->hdr.image_count + 1);
67         imd = CALLOC((w->hdr.image_count + 1), sizeof(struct image_metadata));
68
69         if (!imd) {
70                 ERROR("Failed to allocate memory for new image metadata array");
71                 goto err;
72         }
73
74         memcpy(imd, w->image_metadata,
75                w->hdr.image_count * sizeof(struct image_metadata));
76
77         metadata_lte = new_lookup_table_entry();
78         if (!metadata_lte)
79                 goto err_free_imd;
80
81         metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
82         random_hash(metadata_lte->hash);
83         lookup_table_insert(w->lookup_table, metadata_lte);
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
104 /*
105  * Recursively builds a dentry tree from a directory tree on disk, outside the
106  * WIM file.
107  *
108  * @root_ret:   Place to return a pointer to the root of the dentry tree.  Only
109  *              modified if successful.  NULL if the file or directory was
110  *              excluded from capture.
111  *
112  * @root_disk_path:  The path to the root of the directory tree on disk.
113  *
114  * @lookup_table: The lookup table for the WIM file.  For each file added to the
115  *              dentry tree being built, an entry is added to the lookup table,
116  *              unless an identical stream is already in the lookup table.
117  *              These lookup table entries that are added point to the path of
118  *              the file on disk.
119  *
120  * @sd:         Ignored.  (Security data only captured in NTFS mode.)
121  *
122  * @capture_config:
123  *              Configuration for files to be excluded from capture.
124  *
125  * @add_flags:  Bitwise or of WIMLIB_ADD_IMAGE_FLAG_*
126  *
127  * @extra_arg:  Ignored. (Only used in NTFS mode.)
128  *
129  * @return:     0 on success, nonzero on failure.  It is a failure if any of
130  *              the files cannot be `stat'ed, or if any of the needed
131  *              directories cannot be opened or read.  Failure to add the files
132  *              to the WIM may still occur later when trying to actually read
133  *              the on-disk files during a call to wimlib_write() or
134  *              wimlib_overwrite().
135  */
136 static int build_dentry_tree(struct dentry **root_ret,
137                              const char *root_disk_path,
138                              struct lookup_table *lookup_table,
139                              struct wim_security_data *sd,
140                              const struct capture_config *config,
141                              int add_image_flags,
142                              wimlib_progress_func_t progress_func,
143                              void *extra_arg)
144 {
145         struct stat root_stbuf;
146         int ret = 0;
147         int (*stat_fn)(const char *restrict, struct stat *restrict);
148         struct dentry *root;
149         const char *filename;
150         struct inode *inode;
151
152         if (exclude_path(root_disk_path, config, true)) {
153                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
154                         ERROR("Cannot exclude the root directory from capture");
155                         return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
156                 }
157                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
158                     && progress_func)
159                 {
160                         union wimlib_progress_info info;
161                         info.scan.cur_path = root_disk_path;
162                         info.scan.excluded = true;
163                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
164                 }
165                 *root_ret = NULL;
166                 return 0;
167         }
168
169         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
170             && progress_func)
171         {
172                 union wimlib_progress_info info;
173                 info.scan.cur_path = root_disk_path;
174                 info.scan.excluded = false;
175                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
176         }
177
178         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
179                 stat_fn = stat;
180         else
181                 stat_fn = lstat;
182
183         ret = (*stat_fn)(root_disk_path, &root_stbuf);
184         if (ret != 0) {
185                 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
186                 return WIMLIB_ERR_STAT;
187         }
188
189         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
190               !S_ISDIR(root_stbuf.st_mode))
191         {
192                 /* Do a dereference-stat in case the root is a symbolic link.
193                  * This case is allowed, provided that the symbolic link points
194                  * to a directory. */
195                 ret = stat(root_disk_path, &root_stbuf);
196                 if (ret != 0) {
197                         ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
198                         return WIMLIB_ERR_STAT;
199                 }
200                 if (!S_ISDIR(root_stbuf.st_mode)) {
201                         ERROR("`%s' is not a directory", root_disk_path);
202                         return WIMLIB_ERR_NOTDIR;
203                 }
204         }
205         if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
206             && !S_ISLNK(root_stbuf.st_mode)) {
207                 ERROR("`%s' is not a regular file, directory, or symbolic link.",
208                       root_disk_path);
209                 return WIMLIB_ERR_SPECIAL_FILE;
210         }
211
212         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT)
213                 filename = "";
214         else
215                 filename = path_basename(root_disk_path);
216
217         root = new_dentry_with_timeless_inode(filename);
218         if (!root)
219                 return WIMLIB_ERR_NOMEM;
220
221         inode = root->d_inode;
222
223 #ifdef HAVE_STAT_NANOSECOND_PRECISION
224         inode->creation_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
225         inode->last_write_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
226         inode->last_access_time = timespec_to_wim_timestamp(&root_stbuf.st_atim);
227 #else
228         inode->creation_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
229         inode->last_write_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
230         inode->last_access_time = unix_timestamp_to_wim(root_stbuf.st_atime);
231 #endif
232         if (sizeof(ino_t) >= 8)
233                 inode->ino = (u64)root_stbuf.st_ino;
234         else
235                 inode->ino = (u64)root_stbuf.st_ino |
236                                    ((u64)root_stbuf.st_dev << ((sizeof(ino_t) * 8) & 63));
237
238         add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
239         inode->resolved = 1;
240
241         if (S_ISREG(root_stbuf.st_mode)) { /* Archiving a regular file */
242
243                 struct lookup_table_entry *lte;
244                 u8 hash[SHA1_HASH_SIZE];
245
246                 inode->attributes = FILE_ATTRIBUTE_NORMAL;
247
248                 /* Empty files do not have to have a lookup table entry. */
249                 if (root_stbuf.st_size == 0)
250                         goto out;
251
252                 /* For each regular file, we must check to see if the file is in
253                  * the lookup table already; if it is, we increment its refcnt;
254                  * otherwise, we create a new lookup table entry and insert it.
255                  * */
256
257                 ret = sha1sum(root_disk_path, hash);
258                 if (ret != 0)
259                         goto out;
260
261                 lte = __lookup_resource(lookup_table, hash);
262                 if (lte) {
263                         lte->refcnt++;
264                         DEBUG("Add lte reference %u for `%s'", lte->refcnt,
265                               root_disk_path);
266                 } else {
267                         char *file_on_disk = STRDUP(root_disk_path);
268                         if (!file_on_disk) {
269                                 ERROR("Failed to allocate memory for file path");
270                                 ret = WIMLIB_ERR_NOMEM;
271                                 goto out;
272                         }
273                         lte = new_lookup_table_entry();
274                         if (!lte) {
275                                 FREE(file_on_disk);
276                                 ret = WIMLIB_ERR_NOMEM;
277                                 goto out;
278                         }
279                         lte->file_on_disk = file_on_disk;
280                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
281                         lte->resource_entry.original_size = root_stbuf.st_size;
282                         lte->resource_entry.size = root_stbuf.st_size;
283                         copy_hash(lte->hash, hash);
284                         lookup_table_insert(lookup_table, lte);
285                 }
286                 root->d_inode->lte = lte;
287         } else if (S_ISDIR(root_stbuf.st_mode)) { /* Archiving a directory */
288
289                 inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
290
291                 DIR *dir;
292                 struct dirent entry, *result;
293                 struct dentry *child;
294
295                 dir = opendir(root_disk_path);
296                 if (!dir) {
297                         ERROR_WITH_ERRNO("Failed to open the directory `%s'",
298                                          root_disk_path);
299                         ret = WIMLIB_ERR_OPEN;
300                         goto out;
301                 }
302
303                 /* Buffer for names of files in directory. */
304                 size_t len = strlen(root_disk_path);
305                 char name[len + 1 + FILENAME_MAX + 1];
306                 memcpy(name, root_disk_path, len);
307                 name[len] = '/';
308
309                 /* Create a dentry for each entry in the directory on disk, and recurse
310                  * to any subdirectories. */
311                 while (1) {
312                         errno = 0;
313                         ret = readdir_r(dir, &entry, &result);
314                         if (ret != 0) {
315                                 ret = WIMLIB_ERR_READ;
316                                 ERROR_WITH_ERRNO("Error reading the "
317                                                  "directory `%s'",
318                                                  root_disk_path);
319                                 break;
320                         }
321                         if (result == NULL)
322                                 break;
323                         if (result->d_name[0] == '.' && (result->d_name[1] == '\0'
324                               || (result->d_name[1] == '.' && result->d_name[2] == '\0')))
325                                         continue;
326                         strcpy(name + len + 1, result->d_name);
327                         ret = build_dentry_tree(&child, name, lookup_table,
328                                                 NULL, config, add_image_flags,
329                                                 progress_func, NULL);
330                         if (ret != 0)
331                                 break;
332                         if (child)
333                                 dentry_add_child(root, child);
334                 }
335                 closedir(dir);
336         } else { /* Archiving a symbolic link */
337                 inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
338                 inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
339
340                 /* The idea here is to call readlink() to get the UNIX target of
341                  * the symbolic link, then turn the target into a reparse point
342                  * data buffer that contains a relative or absolute symbolic
343                  * link (NOT a junction point or *full* path symbolic link with
344                  * drive letter).
345                  */
346
347                 char deref_name_buf[4096];
348                 ssize_t deref_name_len;
349
350                 deref_name_len = readlink(root_disk_path, deref_name_buf,
351                                           sizeof(deref_name_buf) - 1);
352                 if (deref_name_len >= 0) {
353                         deref_name_buf[deref_name_len] = '\0';
354                         DEBUG("Read symlink `%s'", deref_name_buf);
355                         ret = inode_set_symlink(root->d_inode, deref_name_buf,
356                                                 lookup_table, NULL);
357                         if (ret == 0) {
358                                 /*
359                                  * Unfortunately, Windows seems to have the
360                                  * concept of "file" symbolic links as being
361                                  * different from "directory" symbolic links...
362                                  * so FILE_ATTRIBUTE_DIRECTORY needs to be set
363                                  * on the symbolic link if the *target* of the
364                                  * symbolic link is a directory.
365                                  */
366                                 struct stat stbuf;
367                                 if (stat(root_disk_path, &stbuf) == 0 &&
368                                     S_ISDIR(stbuf.st_mode))
369                                 {
370                                         inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
371                                 }
372                         }
373                 } else {
374                         ERROR_WITH_ERRNO("Failed to read target of "
375                                          "symbolic link `%s'", root_disk_path);
376                         ret = WIMLIB_ERR_READLINK;
377                 }
378         }
379 out:
380         if (ret == 0)
381                 *root_ret = root;
382         else
383                 free_dentry_tree(root, lookup_table);
384         return ret;
385 }
386
387
388 enum pattern_type {
389         NONE = 0,
390         EXCLUSION_LIST,
391         EXCLUSION_EXCEPTION,
392         COMPRESSION_EXCLUSION_LIST,
393         ALIGNMENT_LIST,
394 };
395
396 /* Default capture configuration file when none is specified. */
397 static const char *default_config =
398 "[ExclusionList]\n"
399 "\\$ntfs.log\n"
400 "\\hiberfil.sys\n"
401 "\\pagefile.sys\n"
402 "\\System Volume Information\n"
403 "\\RECYCLER\n"
404 "\\Windows\\CSC\n"
405 "\n"
406 "[CompressionExclusionList]\n"
407 "*.mp3\n"
408 "*.zip\n"
409 "*.cab\n"
410 "\\WINDOWS\\inf\\*.pnf\n";
411
412 static void destroy_pattern_list(struct pattern_list *list)
413 {
414         FREE(list->pats);
415 }
416
417 static void destroy_capture_config(struct capture_config *config)
418 {
419         destroy_pattern_list(&config->exclusion_list);
420         destroy_pattern_list(&config->exclusion_exception);
421         destroy_pattern_list(&config->compression_exclusion_list);
422         destroy_pattern_list(&config->alignment_list);
423         FREE(config->config_str);
424         FREE(config->prefix);
425         memset(config, 0, sizeof(*config));
426 }
427
428 static int pattern_list_add_pattern(struct pattern_list *list,
429                                     const char *pattern)
430 {
431         const char **pats;
432         if (list->num_pats >= list->num_allocated_pats) {
433                 pats = REALLOC(list->pats,
434                                sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
435                 if (!pats)
436                         return WIMLIB_ERR_NOMEM;
437                 list->num_allocated_pats += 8;
438                 list->pats = pats;
439         }
440         list->pats[list->num_pats++] = pattern;
441         return 0;
442 }
443
444 /* Parses the contents of the image capture configuration file and fills in a
445  * `struct capture_config'. */
446 static int init_capture_config(const char *_config_str, size_t config_len,
447                                const char *_prefix, struct capture_config *config)
448 {
449         char *config_str;
450         char *prefix;
451         char *p;
452         char *eol;
453         char *next_p;
454         size_t bytes_remaining;
455         enum pattern_type type = NONE;
456         int ret;
457         unsigned long line_no = 0;
458
459         DEBUG("config_len = %zu", config_len);
460         bytes_remaining = config_len;
461         memset(config, 0, sizeof(*config));
462         config_str = MALLOC(config_len);
463         if (!config_str) {
464                 ERROR("Could not duplicate capture config string");
465                 return WIMLIB_ERR_NOMEM;
466         }
467         prefix = STRDUP(_prefix);
468         if (!prefix) {
469                 FREE(config_str);
470                 return WIMLIB_ERR_NOMEM;
471         }
472
473         memcpy(config_str, _config_str, config_len);
474         next_p = config_str;
475         config->config_str = config_str;
476         config->prefix = prefix;
477         config->prefix_len = strlen(prefix);
478         while (bytes_remaining) {
479                 line_no++;
480                 p = next_p;
481                 eol = memchr(p, '\n', bytes_remaining);
482                 if (!eol) {
483                         ERROR("Expected end-of-line in capture config file on "
484                               "line %lu", line_no);
485                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
486                         goto out_destroy;
487                 }
488
489                 next_p = eol + 1;
490                 bytes_remaining -= (next_p - p);
491                 if (eol == p)
492                         continue;
493
494                 if (*(eol - 1) == '\r')
495                         eol--;
496                 *eol = '\0';
497
498                 /* Translate backslash to forward slash */
499                 for (char *pp = p; pp != eol; pp++)
500                         if (*pp == '\\')
501                                 *pp = '/';
502
503                 /* Remove drive letter */
504                 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
505                         p += 2;
506
507                 ret = 0;
508                 if (strcmp(p, "[ExclusionList]") == 0)
509                         type = EXCLUSION_LIST;
510                 else if (strcmp(p, "[ExclusionException]") == 0)
511                         type = EXCLUSION_EXCEPTION;
512                 else if (strcmp(p, "[CompressionExclusionList]") == 0)
513                         type = COMPRESSION_EXCLUSION_LIST;
514                 else if (strcmp(p, "[AlignmentList]") == 0)
515                         type = ALIGNMENT_LIST;
516                 else if (p[0] == '[' && strrchr(p, ']')) {
517                         ERROR("Unknown capture configuration section `%s'", p);
518                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
519                 } else switch (type) {
520                 case EXCLUSION_LIST:
521                         DEBUG("Adding pattern \"%s\" to exclusion list", p);
522                         ret = pattern_list_add_pattern(&config->exclusion_list, p);
523                         break;
524                 case EXCLUSION_EXCEPTION:
525                         DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
526                         ret = pattern_list_add_pattern(&config->exclusion_exception, p);
527                         break;
528                 case COMPRESSION_EXCLUSION_LIST:
529                         DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
530                         ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
531                         break;
532                 case ALIGNMENT_LIST:
533                         DEBUG("Adding pattern \"%s\" to alignment list", p);
534                         ret = pattern_list_add_pattern(&config->alignment_list, p);
535                         break;
536                 default:
537                         ERROR("Line %lu of capture configuration is not "
538                               "in a block (such as [ExclusionList])",
539                               line_no);
540                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
541                         break;
542                 }
543                 if (ret != 0)
544                         goto out_destroy;
545         }
546         return 0;
547 out_destroy:
548         destroy_capture_config(config);
549         return ret;
550 }
551
552 static bool match_pattern(const char *path, const char *path_basename,
553                           const struct pattern_list *list)
554 {
555         for (size_t i = 0; i < list->num_pats; i++) {
556                 const char *pat = list->pats[i];
557                 const char *string;
558                 if (pat[0] == '/')
559                         /* Absolute path from root of capture */
560                         string = path;
561                 else {
562                         if (strchr(pat, '/'))
563                                 /* Relative path from root of capture */
564                                 string = path + 1;
565                         else
566                                 /* A file name pattern */
567                                 string = path_basename;
568                 }
569                 if (fnmatch(pat, string, FNM_PATHNAME
570                         #ifdef FNM_CASEFOLD
571                                         | FNM_CASEFOLD
572                         #endif
573                         ) == 0)
574                 {
575                         DEBUG("`%s' matches the pattern \"%s\"",
576                               string, pat);
577                         return true;
578                 }
579         }
580         return false;
581 }
582
583 static void print_pattern_list(const struct pattern_list *list)
584 {
585         for (size_t i = 0; i < list->num_pats; i++)
586                 printf("    %s\n", list->pats[i]);
587 }
588
589 static void print_capture_config(const struct capture_config *config)
590 {
591         if (config->exclusion_list.num_pats) {
592                 puts("Files or folders excluded from image capture:");
593                 print_pattern_list(&config->exclusion_list);
594                 putchar('\n');
595         }
596 }
597
598 /* Return true if the image capture configuration file indicates we should
599  * exclude the filename @path from capture.
600  *
601  * If @exclude_prefix is %true, the part of the path up and including the name
602  * of the directory being captured is not included in the path for matching
603  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
604  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
605  * directory.
606  */
607 bool exclude_path(const char *path, const struct capture_config *config,
608                   bool exclude_prefix)
609 {
610         const char *basename = path_basename(path);
611         if (exclude_prefix) {
612                 wimlib_assert(strlen(path) >= config->prefix_len);
613                 if (memcmp(config->prefix, path, config->prefix_len) == 0
614                      && path[config->prefix_len] == '/')
615                         path += config->prefix_len;
616         }
617         return match_pattern(path, basename, &config->exclusion_list) &&
618                 !match_pattern(path, basename, &config->exclusion_exception);
619
620 }
621
622 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *source,
623                                const char *name, const char *config_str,
624                                size_t config_len, int add_image_flags,
625                                wimlib_progress_func_t progress_func)
626 {
627         int (*capture_tree)(struct dentry **, const char *,
628                             struct lookup_table *,
629                             struct wim_security_data *,
630                             const struct capture_config *,
631                             int, wimlib_progress_func_t, void *);
632         void *extra_arg;
633
634         struct dentry *root_dentry = NULL;
635         struct wim_security_data *sd;
636         struct capture_config config;
637         struct hlist_head inode_list;
638         int ret;
639
640         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
641 #ifdef WITH_NTFS_3G
642                 if (add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)) {
643                         ERROR("Cannot dereference files when capturing directly from NTFS");
644                         return WIMLIB_ERR_INVALID_PARAM;
645                 }
646                 capture_tree = build_dentry_tree_ntfs;
647                 extra_arg = &w->ntfs_vol;
648 #else
649                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
650                       "        cannot capture a WIM image directly from a NTFS volume!");
651                 return WIMLIB_ERR_UNSUPPORTED;
652 #endif
653         } else {
654                 capture_tree = build_dentry_tree;
655                 extra_arg = NULL;
656         }
657
658         DEBUG("Adding dentry tree from directory or NTFS volume `%s'.", source);
659
660         if (!name || !*name) {
661                 ERROR("Must specify a non-empty string for the image name");
662                 return WIMLIB_ERR_INVALID_PARAM;
663         }
664         if (!source || !*source) {
665                 ERROR("Must specify the name of a directory or NTFS volume");
666                 return WIMLIB_ERR_INVALID_PARAM;
667         }
668
669         if (w->hdr.total_parts != 1) {
670                 ERROR("Cannot add an image to a split WIM");
671                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
672         }
673
674         if (wimlib_image_name_in_use(w, name)) {
675                 ERROR("There is already an image named \"%s\" in `%s'",
676                       name, w->filename);
677                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
678         }
679
680         DEBUG("Initializing capture configuration");
681         if (!config_str) {
682                 DEBUG("Using default capture configuration");
683                 config_str = default_config;
684                 config_len = strlen(default_config);
685         }
686         ret = init_capture_config(config_str, config_len, source, &config);
687         if (ret != 0)
688                 return ret;
689         print_capture_config(&config);
690
691         DEBUG("Allocating security data");
692
693         sd = CALLOC(1, sizeof(struct wim_security_data));
694         if (!sd) {
695                 ret = WIMLIB_ERR_NOMEM;
696                 goto out_destroy_config;
697         }
698         sd->total_length = 8;
699         sd->refcnt = 1;
700
701         if (progress_func) {
702                 union wimlib_progress_info progress;
703                 progress.scan.source = source;
704                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
705         }
706
707         DEBUG("Building dentry tree.");
708         ret = (*capture_tree)(&root_dentry, source, w->lookup_table, sd,
709                               &config, add_image_flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
710                               progress_func, extra_arg);
711         destroy_capture_config(&config);
712
713         if (ret != 0) {
714                 ERROR("Failed to build dentry tree for `%s'", source);
715                 goto out_free_security_data;
716         }
717
718         if (progress_func) {
719                 union wimlib_progress_info progress;
720                 progress.scan.source = source;
721                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
722         }
723
724         DEBUG("Calculating full paths of dentries.");
725         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
726         if (ret != 0)
727                 goto out_free_dentry_tree;
728
729         ret = add_new_dentry_tree(w, root_dentry, sd);
730         if (ret != 0)
731                 goto out_free_dentry_tree;
732
733
734         ret = dentry_tree_fix_inodes(root_dentry, &inode_list);
735         if (ret != 0)
736                 goto out_destroy_imd;
737
738         DEBUG("Assigning hard link group IDs");
739         assign_inode_numbers(&inode_list);
740         w->image_metadata[w->hdr.image_count - 1].inode_list = inode_list;
741
742         ret = xml_add_image(w, name);
743         if (ret != 0)
744                 goto out_destroy_imd;
745
746         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
747                 wimlib_set_boot_idx(w, w->hdr.image_count);
748         return 0;
749 out_destroy_imd:
750         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
751                                w->lookup_table);
752         w->hdr.image_count--;
753         return ret;
754 out_free_dentry_tree:
755         free_dentry_tree(root_dentry, w->lookup_table);
756 out_free_security_data:
757         free_security_data(sd);
758 out_destroy_config:
759         destroy_capture_config(&config);
760         return ret;
761 }