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