6 * Copyright (C) 2012 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
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)
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
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/.
24 #include "wimlib_internal.h"
26 #include "timestamp.h"
27 #include "lookup_table.h"
37 /** Private flag: Used to mark that we currently adding the root directory of
39 #define WIMLIB_ADD_IMAGE_FLAG_ROOT 0x80000000
42 * Adds the dentry tree and security data for a new image to the image metadata
43 * array of the WIMStruct.
45 int add_new_dentry_tree(WIMStruct *w, struct wim_dentry *root_dentry,
46 struct wim_security_data *sd)
48 struct wim_lookup_table_entry *metadata_lte;
49 struct image_metadata *imd;
50 struct image_metadata *new_imd;
52 wimlib_assert(root_dentry != NULL);
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 image_metadata));
59 ERROR("Failed to allocate memory for new image metadata array");
63 memcpy(imd, w->image_metadata,
64 w->hdr.image_count * sizeof(struct image_metadata));
66 metadata_lte = new_lookup_table_entry();
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);
74 new_imd = &imd[w->hdr.image_count];
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;
81 FREE(w->image_metadata);
82 w->image_metadata = imd;
88 return WIMLIB_ERR_NOMEM;
94 * build_dentry_tree: - Recursively builds a tree of `struct wim_dentry tree
95 * from an on-disk directory tree.
97 * @root_ret: Place to return a pointer to the root of the dentry tree. Only
98 * modified if successful. Set to NULL if the file or directory was
99 * excluded from capture.
101 * @root_disk_path: The path to the root of the directory tree on disk.
103 * @lookup_table: The lookup table for the WIM file. For each file added to the
104 * dentry tree being built, an entry is added to the lookup table,
105 * unless an identical stream is already in the lookup table.
106 * These lookup table entries that are added point to the path of
109 * @sd: Ignored. (Security data only captured in NTFS mode.)
112 * Configuration for files to be excluded from capture.
114 * @add_flags: Bitwise or of WIMLIB_ADD_IMAGE_FLAG_*
116 * @extra_arg: Ignored. (Only used in NTFS mode.)
118 * @return: 0 on success, nonzero on failure. It is a failure if any of
119 * the files cannot be `stat'ed, or if any of the needed
120 * directories cannot be opened or read. Failure to add the files
121 * to the WIM may still occur later when trying to actually read
122 * the on-disk files during a call to wimlib_write() or
123 * wimlib_overwrite().
125 static int build_dentry_tree(struct wim_dentry **root_ret,
126 const char *root_disk_path,
127 struct wim_lookup_table *lookup_table,
128 struct wim_security_data *sd,
129 const struct capture_config *config,
131 wimlib_progress_func_t progress_func,
134 struct stat root_stbuf;
136 int (*stat_fn)(const char *restrict, struct stat *restrict);
137 struct wim_dentry *root;
138 const char *filename;
139 struct wim_inode *inode;
141 if (exclude_path(root_disk_path, config, true)) {
142 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
143 ERROR("Cannot exclude the root directory from capture");
144 return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
146 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
149 union wimlib_progress_info info;
150 info.scan.cur_path = root_disk_path;
151 info.scan.excluded = true;
152 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
158 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
161 union wimlib_progress_info info;
162 info.scan.cur_path = root_disk_path;
163 info.scan.excluded = false;
164 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
167 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
172 ret = (*stat_fn)(root_disk_path, &root_stbuf);
174 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
175 return WIMLIB_ERR_STAT;
178 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
179 !S_ISDIR(root_stbuf.st_mode))
181 /* Do a dereference-stat in case the root is a symbolic link.
182 * This case is allowed, provided that the symbolic link points
184 ret = stat(root_disk_path, &root_stbuf);
186 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
187 return WIMLIB_ERR_STAT;
189 if (!S_ISDIR(root_stbuf.st_mode)) {
190 ERROR("`%s' is not a directory", root_disk_path);
191 return WIMLIB_ERR_NOTDIR;
194 if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
195 && !S_ISLNK(root_stbuf.st_mode)) {
196 ERROR("`%s' is not a regular file, directory, or symbolic link.",
198 return WIMLIB_ERR_SPECIAL_FILE;
201 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT)
204 filename = path_basename(root_disk_path);
206 root = new_dentry_with_timeless_inode(filename);
209 return WIMLIB_ERR_INVALID_UTF8_STRING;
210 else if (errno == ENOMEM)
211 return WIMLIB_ERR_NOMEM;
213 return WIMLIB_ERR_ICONV_NOT_AVAILABLE;
216 inode = root->d_inode;
218 #ifdef HAVE_STAT_NANOSECOND_PRECISION
219 inode->i_creation_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
220 inode->i_last_write_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
221 inode->i_last_access_time = timespec_to_wim_timestamp(&root_stbuf.st_atim);
223 inode->i_creation_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
224 inode->i_last_write_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
225 inode->i_last_access_time = unix_timestamp_to_wim(root_stbuf.st_atime);
227 if (sizeof(ino_t) >= 8)
228 inode->i_ino = (u64)root_stbuf.st_ino;
230 inode->i_ino = (u64)root_stbuf.st_ino |
231 ((u64)root_stbuf.st_dev << ((sizeof(ino_t) * 8) & 63));
233 add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
234 inode->i_resolved = 1;
236 if (S_ISREG(root_stbuf.st_mode)) { /* Archiving a regular file */
238 struct wim_lookup_table_entry *lte;
239 u8 hash[SHA1_HASH_SIZE];
241 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
243 /* Empty files do not have to have a lookup table entry. */
244 if (root_stbuf.st_size == 0)
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.
252 ret = sha1sum(root_disk_path, hash);
256 lte = __lookup_resource(lookup_table, hash);
259 DEBUG("Add lte reference %u for `%s'", lte->refcnt,
262 char *file_on_disk = STRDUP(root_disk_path);
264 ERROR("Failed to allocate memory for file path");
265 ret = WIMLIB_ERR_NOMEM;
268 lte = new_lookup_table_entry();
271 ret = WIMLIB_ERR_NOMEM;
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);
281 root->d_inode->i_lte = lte;
282 } else if (S_ISDIR(root_stbuf.st_mode)) { /* Archiving a directory */
284 inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
287 struct dirent entry, *result;
288 struct wim_dentry *child;
290 dir = opendir(root_disk_path);
292 ERROR_WITH_ERRNO("Failed to open the directory `%s'",
294 ret = WIMLIB_ERR_OPEN;
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);
304 /* Create a dentry for each entry in the directory on disk, and recurse
305 * to any subdirectories. */
308 ret = readdir_r(dir, &entry, &result);
310 ret = WIMLIB_ERR_READ;
311 ERROR_WITH_ERRNO("Error reading the "
318 if (result->d_name[0] == '.' && (result->d_name[1] == '\0'
319 || (result->d_name[1] == '.' && result->d_name[2] == '\0')))
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);
328 dentry_add_child(root, child);
331 } else { /* Archiving a symbolic link */
332 inode->i_attributes = FILE_ATTRIBUTE_REPARSE_POINT;
333 inode->i_reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
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
342 char deref_name_buf[4096];
343 ssize_t deref_name_len;
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,
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.
362 if (stat(root_disk_path, &stbuf) == 0 &&
363 S_ISDIR(stbuf.st_mode))
365 inode->i_attributes |= FILE_ATTRIBUTE_DIRECTORY;
369 ERROR_WITH_ERRNO("Failed to read target of "
370 "symbolic link `%s'", root_disk_path);
371 ret = WIMLIB_ERR_READLINK;
378 free_dentry_tree(root, lookup_table);
387 COMPRESSION_EXCLUSION_LIST,
391 /* Default capture configuration file when none is specified. */
392 static const char *default_config =
397 "\\System Volume Information\n"
401 "[CompressionExclusionList]\n"
405 "\\WINDOWS\\inf\\*.pnf\n";
407 static void destroy_pattern_list(struct pattern_list *list)
412 static void destroy_capture_config(struct capture_config *config)
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));
423 static int pattern_list_add_pattern(struct pattern_list *list,
427 if (list->num_pats >= list->num_allocated_pats) {
428 pats = REALLOC(list->pats,
429 sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
431 return WIMLIB_ERR_NOMEM;
432 list->num_allocated_pats += 8;
435 list->pats[list->num_pats++] = pattern;
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)
449 size_t bytes_remaining;
450 enum pattern_type type = NONE;
452 unsigned long line_no = 0;
454 DEBUG("config_len = %zu", config_len);
455 bytes_remaining = config_len;
456 memset(config, 0, sizeof(*config));
457 config_str = MALLOC(config_len);
459 ERROR("Could not duplicate capture config string");
460 return WIMLIB_ERR_NOMEM;
462 prefix = STRDUP(_prefix);
465 return WIMLIB_ERR_NOMEM;
468 memcpy(config_str, _config_str, config_len);
470 config->config_str = config_str;
471 config->prefix = prefix;
472 config->prefix_len = strlen(prefix);
473 while (bytes_remaining) {
476 eol = memchr(p, '\n', bytes_remaining);
478 ERROR("Expected end-of-line in capture config file on "
479 "line %lu", line_no);
480 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
485 bytes_remaining -= (next_p - p);
489 if (*(eol - 1) == '\r')
493 /* Translate backslash to forward slash */
494 for (char *pp = p; pp != eol; pp++)
498 /* Remove drive letter */
499 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
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) {
516 DEBUG("Adding pattern \"%s\" to exclusion list", p);
517 ret = pattern_list_add_pattern(&config->exclusion_list, p);
519 case EXCLUSION_EXCEPTION:
520 DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
521 ret = pattern_list_add_pattern(&config->exclusion_exception, p);
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);
528 DEBUG("Adding pattern \"%s\" to alignment list", p);
529 ret = pattern_list_add_pattern(&config->alignment_list, p);
532 ERROR("Line %lu of capture configuration is not "
533 "in a block (such as [ExclusionList])",
535 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
543 destroy_capture_config(config);
547 static bool match_pattern(const char *path, const char *path_basename,
548 const struct pattern_list *list)
550 for (size_t i = 0; i < list->num_pats; i++) {
551 const char *pat = list->pats[i];
554 /* Absolute path from root of capture */
557 if (strchr(pat, '/'))
558 /* Relative path from root of capture */
561 /* A file name pattern */
562 string = path_basename;
564 if (fnmatch(pat, string, FNM_PATHNAME
570 DEBUG("`%s' matches the pattern \"%s\"",
578 static void print_pattern_list(const struct pattern_list *list)
580 for (size_t i = 0; i < list->num_pats; i++)
581 printf(" %s\n", list->pats[i]);
584 static void print_capture_config(const struct capture_config *config)
586 if (config->exclusion_list.num_pats) {
587 puts("Files or folders excluded from image capture:");
588 print_pattern_list(&config->exclusion_list);
593 /* Return true if the image capture configuration file indicates we should
594 * exclude the filename @path from capture.
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
602 bool exclude_path(const char *path, const struct capture_config *config,
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;
612 return match_pattern(path, basename, &config->exclusion_list) &&
613 !match_pattern(path, basename, &config->exclusion_exception);
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)
622 int (*capture_tree)(struct wim_dentry **, const char *,
623 struct wim_lookup_table *,
624 struct wim_security_data *,
625 const struct capture_config *,
626 int, wimlib_progress_func_t, void *);
629 struct wim_dentry *root_dentry = NULL;
630 struct wim_security_data *sd;
631 struct capture_config config;
632 struct image_metadata *imd;
635 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
637 if (add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)) {
638 ERROR("Cannot dereference files when capturing directly from NTFS");
639 return WIMLIB_ERR_INVALID_PARAM;
641 capture_tree = build_dentry_tree_ntfs;
642 extra_arg = &w->ntfs_vol;
644 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
645 " cannot capture a WIM image directly from a NTFS volume!");
646 return WIMLIB_ERR_UNSUPPORTED;
649 capture_tree = build_dentry_tree;
653 DEBUG("Adding dentry tree from directory or NTFS volume `%s'.", source);
655 if (!name || !*name) {
656 ERROR("Must specify a non-empty string for the image name");
657 return WIMLIB_ERR_INVALID_PARAM;
659 if (!source || !*source) {
660 ERROR("Must specify the name of a directory or NTFS volume");
661 return WIMLIB_ERR_INVALID_PARAM;
664 if (w->hdr.total_parts != 1) {
665 ERROR("Cannot add an image to a split WIM");
666 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
669 if (wimlib_image_name_in_use(w, name)) {
670 ERROR("There is already an image named \"%s\" in `%s'",
672 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
675 DEBUG("Initializing capture configuration");
677 DEBUG("Using default capture configuration");
678 config_str = default_config;
679 config_len = strlen(default_config);
681 ret = init_capture_config(config_str, config_len, source, &config);
684 print_capture_config(&config);
686 DEBUG("Allocating security data");
688 sd = CALLOC(1, sizeof(struct wim_security_data));
690 ret = WIMLIB_ERR_NOMEM;
691 goto out_destroy_config;
693 sd->total_length = 8;
697 union wimlib_progress_info progress;
698 progress.scan.source = source;
699 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
702 DEBUG("Building dentry tree.");
703 ret = (*capture_tree)(&root_dentry, source, w->lookup_table, sd,
704 &config, add_image_flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
705 progress_func, extra_arg);
706 destroy_capture_config(&config);
709 ERROR("Failed to build dentry tree for `%s'", source);
710 goto out_free_security_data;
714 union wimlib_progress_info progress;
715 progress.scan.source = source;
716 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
719 DEBUG("Calculating full paths of dentries.");
720 ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
722 goto out_free_dentry_tree;
724 ret = add_new_dentry_tree(w, root_dentry, sd);
726 goto out_free_dentry_tree;
728 imd = &w->image_metadata[w->hdr.image_count - 1];
730 ret = dentry_tree_fix_inodes(root_dentry, &imd->inode_list);
732 goto out_destroy_imd;
734 DEBUG("Assigning hard link group IDs");
735 assign_inode_numbers(&imd->inode_list);
737 ret = xml_add_image(w, name);
739 goto out_destroy_imd;
741 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
742 wimlib_set_boot_idx(w, w->hdr.image_count);
745 destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
747 w->hdr.image_count--;
749 out_free_dentry_tree:
750 free_dentry_tree(root_dentry, w->lookup_table);
751 out_free_security_data:
752 free_security_data(sd);
754 destroy_capture_config(&config);