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