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 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.
46 * Does not update the XML data.
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.
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.
55 int add_new_dentry_tree(WIMStruct *w, struct dentry *root_dentry,
56 struct wim_security_data *sd)
58 struct lookup_table_entry *metadata_lte;
59 struct image_metadata *imd;
60 struct image_metadata *new_imd;
63 wimlib_assert(root_dentry != NULL);
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));
70 ERROR("Failed to allocate memory for new image metadata array");
74 memcpy(imd, w->image_metadata,
75 w->hdr.image_count * sizeof(struct image_metadata));
77 metadata_lte = new_lookup_table_entry();
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);
85 new_imd = &imd[w->hdr.image_count];
87 new_imd->root_dentry = root_dentry;
88 new_imd->metadata_lte = metadata_lte;
89 new_imd->security_data = sd;
90 new_imd->modified = 1;
92 FREE(w->image_metadata);
93 w->image_metadata = imd;
99 return WIMLIB_ERR_NOMEM;
105 * Recursively builds a dentry tree from a directory tree on disk, outside the
108 * @root_ret: Place to return a pointer to the root of the dentry tree. Only
109 * modified if successful. NULL if the file or directory was
110 * excluded from capture.
112 * @root_disk_path: The path to the root of the directory tree on disk.
114 * @lookup_table: The lookup table for the WIM file. For each file added to the
115 * dentry tree being built, an entry is added to the lookup table,
116 * unless an identical stream is already in the lookup table.
117 * These lookup table entries that are added point to the path of
120 * @sd: Ignored. (Security data only captured in NTFS mode.)
123 * Configuration for files to be excluded from capture.
125 * @add_flags: Bitwise or of WIMLIB_ADD_IMAGE_FLAG_*
127 * @extra_arg: Ignored. (Only used in NTFS mode.)
129 * @return: 0 on success, nonzero on failure. It is a failure if any of
130 * the files cannot be `stat'ed, or if any of the needed
131 * directories cannot be opened or read. Failure to add the files
132 * to the WIM may still occur later when trying to actually read
133 * the on-disk files during a call to wimlib_write() or
134 * wimlib_overwrite().
136 static int build_dentry_tree(struct dentry **root_ret,
137 const char *root_disk_path,
138 struct lookup_table *lookup_table,
139 struct wim_security_data *sd,
140 const struct capture_config *config,
142 wimlib_progress_func_t progress_func,
145 struct stat root_stbuf;
147 int (*stat_fn)(const char *restrict, struct stat *restrict);
149 const char *filename;
152 if (exclude_path(root_disk_path, config, true)) {
153 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
154 ERROR("Cannot exclude the root directory from capture");
155 return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
157 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
160 union wimlib_progress_info info;
161 info.scan.cur_path = root_disk_path;
162 info.scan.excluded = true;
163 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
169 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
172 union wimlib_progress_info info;
173 info.scan.cur_path = root_disk_path;
174 info.scan.excluded = false;
175 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
178 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
183 ret = (*stat_fn)(root_disk_path, &root_stbuf);
185 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
186 return WIMLIB_ERR_STAT;
189 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
190 !S_ISDIR(root_stbuf.st_mode))
192 /* Do a dereference-stat in case the root is a symbolic link.
193 * This case is allowed, provided that the symbolic link points
195 ret = stat(root_disk_path, &root_stbuf);
197 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
198 return WIMLIB_ERR_STAT;
200 if (!S_ISDIR(root_stbuf.st_mode)) {
201 ERROR("`%s' is not a directory", root_disk_path);
202 return WIMLIB_ERR_NOTDIR;
205 if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
206 && !S_ISLNK(root_stbuf.st_mode)) {
207 ERROR("`%s' is not a regular file, directory, or symbolic link.",
209 return WIMLIB_ERR_SPECIAL_FILE;
212 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT)
215 filename = path_basename(root_disk_path);
217 root = new_dentry_with_timeless_inode(filename);
219 return WIMLIB_ERR_NOMEM;
221 inode = root->d_inode;
223 #ifdef HAVE_STAT_NANOSECOND_PRECISION
224 inode->creation_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
225 inode->last_write_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
226 inode->last_access_time = timespec_to_wim_timestamp(&root_stbuf.st_atim);
228 inode->creation_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
229 inode->last_write_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
230 inode->last_access_time = unix_timestamp_to_wim(root_stbuf.st_atime);
232 if (sizeof(ino_t) >= 8)
233 inode->ino = (u64)root_stbuf.st_ino;
235 inode->ino = (u64)root_stbuf.st_ino |
236 ((u64)root_stbuf.st_dev << ((sizeof(ino_t) * 8) & 63));
238 add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
241 if (S_ISREG(root_stbuf.st_mode)) { /* Archiving a regular file */
243 struct lookup_table_entry *lte;
244 u8 hash[SHA1_HASH_SIZE];
246 inode->attributes = FILE_ATTRIBUTE_NORMAL;
248 /* Empty files do not have to have a lookup table entry. */
249 if (root_stbuf.st_size == 0)
252 /* For each regular file, we must check to see if the file is in
253 * the lookup table already; if it is, we increment its refcnt;
254 * otherwise, we create a new lookup table entry and insert it.
257 ret = sha1sum(root_disk_path, hash);
261 lte = __lookup_resource(lookup_table, hash);
264 DEBUG("Add lte reference %u for `%s'", lte->refcnt,
267 char *file_on_disk = STRDUP(root_disk_path);
269 ERROR("Failed to allocate memory for file path");
270 ret = WIMLIB_ERR_NOMEM;
273 lte = new_lookup_table_entry();
276 ret = WIMLIB_ERR_NOMEM;
279 lte->file_on_disk = file_on_disk;
280 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
281 lte->resource_entry.original_size = root_stbuf.st_size;
282 lte->resource_entry.size = root_stbuf.st_size;
283 copy_hash(lte->hash, hash);
284 lookup_table_insert(lookup_table, lte);
286 root->d_inode->lte = lte;
287 } else if (S_ISDIR(root_stbuf.st_mode)) { /* Archiving a directory */
289 inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
292 struct dirent entry, *result;
293 struct dentry *child;
295 dir = opendir(root_disk_path);
297 ERROR_WITH_ERRNO("Failed to open the directory `%s'",
299 ret = WIMLIB_ERR_OPEN;
303 /* Buffer for names of files in directory. */
304 size_t len = strlen(root_disk_path);
305 char name[len + 1 + FILENAME_MAX + 1];
306 memcpy(name, root_disk_path, len);
309 /* Create a dentry for each entry in the directory on disk, and recurse
310 * to any subdirectories. */
313 ret = readdir_r(dir, &entry, &result);
315 ret = WIMLIB_ERR_READ;
316 ERROR_WITH_ERRNO("Error reading the "
323 if (result->d_name[0] == '.' && (result->d_name[1] == '\0'
324 || (result->d_name[1] == '.' && result->d_name[2] == '\0')))
326 strcpy(name + len + 1, result->d_name);
327 ret = build_dentry_tree(&child, name, lookup_table,
328 NULL, config, add_image_flags,
329 progress_func, NULL);
333 dentry_add_child(root, child);
336 } else { /* Archiving a symbolic link */
337 inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
338 inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
340 /* The idea here is to call readlink() to get the UNIX target of
341 * the symbolic link, then turn the target into a reparse point
342 * data buffer that contains a relative or absolute symbolic
343 * link (NOT a junction point or *full* path symbolic link with
347 char deref_name_buf[4096];
348 ssize_t deref_name_len;
350 deref_name_len = readlink(root_disk_path, deref_name_buf,
351 sizeof(deref_name_buf) - 1);
352 if (deref_name_len >= 0) {
353 deref_name_buf[deref_name_len] = '\0';
354 DEBUG("Read symlink `%s'", deref_name_buf);
355 ret = inode_set_symlink(root->d_inode, deref_name_buf,
359 * Unfortunately, Windows seems to have the
360 * concept of "file" symbolic links as being
361 * different from "directory" symbolic links...
362 * so FILE_ATTRIBUTE_DIRECTORY needs to be set
363 * on the symbolic link if the *target* of the
364 * symbolic link is a directory.
367 if (stat(root_disk_path, &stbuf) == 0 &&
368 S_ISDIR(stbuf.st_mode))
370 inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
374 ERROR_WITH_ERRNO("Failed to read target of "
375 "symbolic link `%s'", root_disk_path);
376 ret = WIMLIB_ERR_READLINK;
383 free_dentry_tree(root, lookup_table);
392 COMPRESSION_EXCLUSION_LIST,
396 /* Default capture configuration file when none is specified. */
397 static const char *default_config =
402 "\\System Volume Information\n"
406 "[CompressionExclusionList]\n"
410 "\\WINDOWS\\inf\\*.pnf\n";
412 static void destroy_pattern_list(struct pattern_list *list)
417 static void destroy_capture_config(struct capture_config *config)
419 destroy_pattern_list(&config->exclusion_list);
420 destroy_pattern_list(&config->exclusion_exception);
421 destroy_pattern_list(&config->compression_exclusion_list);
422 destroy_pattern_list(&config->alignment_list);
423 FREE(config->config_str);
424 FREE(config->prefix);
425 memset(config, 0, sizeof(*config));
428 static int pattern_list_add_pattern(struct pattern_list *list,
432 if (list->num_pats >= list->num_allocated_pats) {
433 pats = REALLOC(list->pats,
434 sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
436 return WIMLIB_ERR_NOMEM;
437 list->num_allocated_pats += 8;
440 list->pats[list->num_pats++] = pattern;
444 /* Parses the contents of the image capture configuration file and fills in a
445 * `struct capture_config'. */
446 static int init_capture_config(const char *_config_str, size_t config_len,
447 const char *_prefix, struct capture_config *config)
454 size_t bytes_remaining;
455 enum pattern_type type = NONE;
457 unsigned long line_no = 0;
459 DEBUG("config_len = %zu", config_len);
460 bytes_remaining = config_len;
461 memset(config, 0, sizeof(*config));
462 config_str = MALLOC(config_len);
464 ERROR("Could not duplicate capture config string");
465 return WIMLIB_ERR_NOMEM;
467 prefix = STRDUP(_prefix);
470 return WIMLIB_ERR_NOMEM;
473 memcpy(config_str, _config_str, config_len);
475 config->config_str = config_str;
476 config->prefix = prefix;
477 config->prefix_len = strlen(prefix);
478 while (bytes_remaining) {
481 eol = memchr(p, '\n', bytes_remaining);
483 ERROR("Expected end-of-line in capture config file on "
484 "line %lu", line_no);
485 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
490 bytes_remaining -= (next_p - p);
494 if (*(eol - 1) == '\r')
498 /* Translate backslash to forward slash */
499 for (char *pp = p; pp != eol; pp++)
503 /* Remove drive letter */
504 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
508 if (strcmp(p, "[ExclusionList]") == 0)
509 type = EXCLUSION_LIST;
510 else if (strcmp(p, "[ExclusionException]") == 0)
511 type = EXCLUSION_EXCEPTION;
512 else if (strcmp(p, "[CompressionExclusionList]") == 0)
513 type = COMPRESSION_EXCLUSION_LIST;
514 else if (strcmp(p, "[AlignmentList]") == 0)
515 type = ALIGNMENT_LIST;
516 else if (p[0] == '[' && strrchr(p, ']')) {
517 ERROR("Unknown capture configuration section `%s'", p);
518 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
519 } else switch (type) {
521 DEBUG("Adding pattern \"%s\" to exclusion list", p);
522 ret = pattern_list_add_pattern(&config->exclusion_list, p);
524 case EXCLUSION_EXCEPTION:
525 DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
526 ret = pattern_list_add_pattern(&config->exclusion_exception, p);
528 case COMPRESSION_EXCLUSION_LIST:
529 DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
530 ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
533 DEBUG("Adding pattern \"%s\" to alignment list", p);
534 ret = pattern_list_add_pattern(&config->alignment_list, p);
537 ERROR("Line %lu of capture configuration is not "
538 "in a block (such as [ExclusionList])",
540 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
548 destroy_capture_config(config);
552 static bool match_pattern(const char *path, const char *path_basename,
553 const struct pattern_list *list)
555 for (size_t i = 0; i < list->num_pats; i++) {
556 const char *pat = list->pats[i];
559 /* Absolute path from root of capture */
562 if (strchr(pat, '/'))
563 /* Relative path from root of capture */
566 /* A file name pattern */
567 string = path_basename;
569 if (fnmatch(pat, string, FNM_PATHNAME
575 DEBUG("`%s' matches the pattern \"%s\"",
583 static void print_pattern_list(const struct pattern_list *list)
585 for (size_t i = 0; i < list->num_pats; i++)
586 printf(" %s\n", list->pats[i]);
589 static void print_capture_config(const struct capture_config *config)
591 if (config->exclusion_list.num_pats) {
592 puts("Files or folders excluded from image capture:");
593 print_pattern_list(&config->exclusion_list);
598 /* Return true if the image capture configuration file indicates we should
599 * exclude the filename @path from capture.
601 * If @exclude_prefix is %true, the part of the path up and including the name
602 * of the directory being captured is not included in the path for matching
603 * purposes. This allows, for example, a pattern like /hiberfil.sys to match a
604 * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
607 bool exclude_path(const char *path, const struct capture_config *config,
610 const char *basename = path_basename(path);
611 if (exclude_prefix) {
612 wimlib_assert(strlen(path) >= config->prefix_len);
613 if (memcmp(config->prefix, path, config->prefix_len) == 0
614 && path[config->prefix_len] == '/')
615 path += config->prefix_len;
617 return match_pattern(path, basename, &config->exclusion_list) &&
618 !match_pattern(path, basename, &config->exclusion_exception);
622 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *source,
623 const char *name, const char *config_str,
624 size_t config_len, int add_image_flags,
625 wimlib_progress_func_t progress_func)
627 int (*capture_tree)(struct dentry **, const char *,
628 struct lookup_table *,
629 struct wim_security_data *,
630 const struct capture_config *,
631 int, wimlib_progress_func_t, void *);
634 struct dentry *root_dentry = NULL;
635 struct wim_security_data *sd;
636 struct capture_config config;
637 struct hlist_head inode_list;
640 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
642 if (add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)) {
643 ERROR("Cannot dereference files when capturing directly from NTFS");
644 return WIMLIB_ERR_INVALID_PARAM;
646 capture_tree = build_dentry_tree_ntfs;
647 extra_arg = &w->ntfs_vol;
649 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
650 " cannot capture a WIM image directly from a NTFS volume!");
651 return WIMLIB_ERR_UNSUPPORTED;
654 capture_tree = build_dentry_tree;
658 DEBUG("Adding dentry tree from directory or NTFS volume `%s'.", source);
660 if (!name || !*name) {
661 ERROR("Must specify a non-empty string for the image name");
662 return WIMLIB_ERR_INVALID_PARAM;
664 if (!source || !*source) {
665 ERROR("Must specify the name of a directory or NTFS volume");
666 return WIMLIB_ERR_INVALID_PARAM;
669 if (w->hdr.total_parts != 1) {
670 ERROR("Cannot add an image to a split WIM");
671 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
674 if (wimlib_image_name_in_use(w, name)) {
675 ERROR("There is already an image named \"%s\" in `%s'",
677 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
680 DEBUG("Initializing capture configuration");
682 DEBUG("Using default capture configuration");
683 config_str = default_config;
684 config_len = strlen(default_config);
686 ret = init_capture_config(config_str, config_len, source, &config);
689 print_capture_config(&config);
691 DEBUG("Allocating security data");
693 sd = CALLOC(1, sizeof(struct wim_security_data));
695 ret = WIMLIB_ERR_NOMEM;
696 goto out_destroy_config;
698 sd->total_length = 8;
702 union wimlib_progress_info progress;
703 progress.scan.source = source;
704 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
707 DEBUG("Building dentry tree.");
708 ret = (*capture_tree)(&root_dentry, source, w->lookup_table, sd,
709 &config, add_image_flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
710 progress_func, extra_arg);
711 destroy_capture_config(&config);
714 ERROR("Failed to build dentry tree for `%s'", source);
715 goto out_free_security_data;
719 union wimlib_progress_info progress;
720 progress.scan.source = source;
721 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
724 DEBUG("Calculating full paths of dentries.");
725 ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
727 goto out_free_dentry_tree;
729 ret = add_new_dentry_tree(w, root_dentry, sd);
731 goto out_free_dentry_tree;
734 ret = dentry_tree_fix_inodes(root_dentry, &inode_list);
736 goto out_destroy_imd;
738 DEBUG("Assigning hard link group IDs");
739 assign_inode_numbers(&inode_list);
740 w->image_metadata[w->hdr.image_count - 1].inode_list = inode_list;
742 ret = xml_add_image(w, name);
744 goto out_destroy_imd;
746 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
747 wimlib_set_boot_idx(w, w->hdr.image_count);
750 destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
752 w->hdr.image_count--;
754 out_free_dentry_tree:
755 free_dentry_tree(root_dentry, w->lookup_table);
756 out_free_security_data:
757 free_security_data(sd);
759 destroy_capture_config(&config);