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