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