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