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;
62 wimlib_assert(root_dentry != NULL);
64 DEBUG("Reallocating image metadata array for image_count = %u",
65 w->hdr.image_count + 1);
66 imd = CALLOC((w->hdr.image_count + 1), sizeof(struct image_metadata));
69 ERROR("Failed to allocate memory for new image metadata array");
73 memcpy(imd, w->image_metadata,
74 w->hdr.image_count * sizeof(struct image_metadata));
76 metadata_lte = new_lookup_table_entry();
80 metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
81 random_hash(metadata_lte->hash);
82 lookup_table_insert(w->lookup_table, metadata_lte);
84 new_imd = &imd[w->hdr.image_count];
86 new_imd->root_dentry = root_dentry;
87 new_imd->metadata_lte = metadata_lte;
88 new_imd->security_data = sd;
89 new_imd->modified = 1;
91 FREE(w->image_metadata);
92 w->image_metadata = imd;
98 return WIMLIB_ERR_NOMEM;
104 * Recursively builds a dentry tree from a directory tree on disk, outside the
107 * @root_ret: Place to return a pointer to the root of the dentry tree. Only
108 * modified if successful. NULL if the file or directory was
109 * excluded from capture.
111 * @root_disk_path: The path to the root of the directory tree on disk.
113 * @lookup_table: The lookup table for the WIM file. For each file added to the
114 * dentry tree being built, an entry is added to the lookup table,
115 * unless an identical stream is already in the lookup table.
116 * These lookup table entries that are added point to the path of
119 * @sd: Ignored. (Security data only captured in NTFS mode.)
122 * Configuration for files to be excluded from capture.
124 * @add_flags: Bitwise or of WIMLIB_ADD_IMAGE_FLAG_*
126 * @extra_arg: Ignored. (Only used in NTFS mode.)
128 * @return: 0 on success, nonzero on failure. It is a failure if any of
129 * the files cannot be `stat'ed, or if any of the needed
130 * directories cannot be opened or read. Failure to add the files
131 * to the WIM may still occur later when trying to actually read
132 * the on-disk files during a call to wimlib_write() or
133 * wimlib_overwrite().
135 static int build_dentry_tree(struct dentry **root_ret,
136 const char *root_disk_path,
137 struct lookup_table *lookup_table,
138 struct wim_security_data *sd,
139 const struct capture_config *config,
141 wimlib_progress_func_t progress_func,
144 struct stat root_stbuf;
146 int (*stat_fn)(const char *restrict, struct stat *restrict);
148 const char *filename;
151 if (exclude_path(root_disk_path, config, true)) {
152 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
153 ERROR("Cannot exclude the root directory from capture");
154 return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
156 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
159 union wimlib_progress_info info;
160 info.scan.cur_path = root_disk_path;
161 info.scan.excluded = true;
162 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
168 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
171 union wimlib_progress_info info;
172 info.scan.cur_path = root_disk_path;
173 info.scan.excluded = false;
174 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
177 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
182 ret = (*stat_fn)(root_disk_path, &root_stbuf);
184 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
185 return WIMLIB_ERR_STAT;
188 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
189 !S_ISDIR(root_stbuf.st_mode))
191 /* Do a dereference-stat in case the root is a symbolic link.
192 * This case is allowed, provided that the symbolic link points
194 ret = stat(root_disk_path, &root_stbuf);
196 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
197 return WIMLIB_ERR_STAT;
199 if (!S_ISDIR(root_stbuf.st_mode)) {
200 ERROR("`%s' is not a directory", root_disk_path);
201 return WIMLIB_ERR_NOTDIR;
204 if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
205 && !S_ISLNK(root_stbuf.st_mode)) {
206 ERROR("`%s' is not a regular file, directory, or symbolic link.",
208 return WIMLIB_ERR_SPECIAL_FILE;
211 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT)
214 filename = path_basename(root_disk_path);
216 root = new_dentry_with_timeless_inode(filename);
219 return WIMLIB_ERR_INVALID_UTF8_STRING;
221 return WIMLIB_ERR_NOMEM;
224 inode = root->d_inode;
226 #ifdef HAVE_STAT_NANOSECOND_PRECISION
227 inode->creation_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
228 inode->last_write_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
229 inode->last_access_time = timespec_to_wim_timestamp(&root_stbuf.st_atim);
231 inode->creation_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
232 inode->last_write_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
233 inode->last_access_time = unix_timestamp_to_wim(root_stbuf.st_atime);
235 if (sizeof(ino_t) >= 8)
236 inode->ino = (u64)root_stbuf.st_ino;
238 inode->ino = (u64)root_stbuf.st_ino |
239 ((u64)root_stbuf.st_dev << ((sizeof(ino_t) * 8) & 63));
241 add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
244 if (S_ISREG(root_stbuf.st_mode)) { /* Archiving a regular file */
246 struct lookup_table_entry *lte;
247 u8 hash[SHA1_HASH_SIZE];
249 inode->attributes = FILE_ATTRIBUTE_NORMAL;
251 /* Empty files do not have to have a lookup table entry. */
252 if (root_stbuf.st_size == 0)
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.
260 ret = sha1sum(root_disk_path, hash);
264 lte = __lookup_resource(lookup_table, hash);
267 DEBUG("Add lte reference %u for `%s'", lte->refcnt,
270 char *file_on_disk = STRDUP(root_disk_path);
272 ERROR("Failed to allocate memory for file path");
273 ret = WIMLIB_ERR_NOMEM;
276 lte = new_lookup_table_entry();
279 ret = WIMLIB_ERR_NOMEM;
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);
289 root->d_inode->lte = lte;
290 } else if (S_ISDIR(root_stbuf.st_mode)) { /* Archiving a directory */
292 inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
295 struct dirent entry, *result;
296 struct dentry *child;
298 dir = opendir(root_disk_path);
300 ERROR_WITH_ERRNO("Failed to open the directory `%s'",
302 ret = WIMLIB_ERR_OPEN;
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);
312 /* Create a dentry for each entry in the directory on disk, and recurse
313 * to any subdirectories. */
316 ret = readdir_r(dir, &entry, &result);
318 ret = WIMLIB_ERR_READ;
319 ERROR_WITH_ERRNO("Error reading the "
326 if (result->d_name[0] == '.' && (result->d_name[1] == '\0'
327 || (result->d_name[1] == '.' && result->d_name[2] == '\0')))
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);
336 dentry_add_child(root, child);
339 } else { /* Archiving a symbolic link */
340 inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
341 inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
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
350 char deref_name_buf[4096];
351 ssize_t deref_name_len;
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,
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.
370 if (stat(root_disk_path, &stbuf) == 0 &&
371 S_ISDIR(stbuf.st_mode))
373 inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
377 ERROR_WITH_ERRNO("Failed to read target of "
378 "symbolic link `%s'", root_disk_path);
379 ret = WIMLIB_ERR_READLINK;
386 free_dentry_tree(root, lookup_table);
395 COMPRESSION_EXCLUSION_LIST,
399 /* Default capture configuration file when none is specified. */
400 static const char *default_config =
405 "\\System Volume Information\n"
409 "[CompressionExclusionList]\n"
413 "\\WINDOWS\\inf\\*.pnf\n";
415 static void destroy_pattern_list(struct pattern_list *list)
420 static void destroy_capture_config(struct capture_config *config)
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));
431 static int pattern_list_add_pattern(struct pattern_list *list,
435 if (list->num_pats >= list->num_allocated_pats) {
436 pats = REALLOC(list->pats,
437 sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
439 return WIMLIB_ERR_NOMEM;
440 list->num_allocated_pats += 8;
443 list->pats[list->num_pats++] = pattern;
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)
457 size_t bytes_remaining;
458 enum pattern_type type = NONE;
460 unsigned long line_no = 0;
462 DEBUG("config_len = %zu", config_len);
463 bytes_remaining = config_len;
464 memset(config, 0, sizeof(*config));
465 config_str = MALLOC(config_len);
467 ERROR("Could not duplicate capture config string");
468 return WIMLIB_ERR_NOMEM;
470 prefix = STRDUP(_prefix);
473 return WIMLIB_ERR_NOMEM;
476 memcpy(config_str, _config_str, config_len);
478 config->config_str = config_str;
479 config->prefix = prefix;
480 config->prefix_len = strlen(prefix);
481 while (bytes_remaining) {
484 eol = memchr(p, '\n', bytes_remaining);
486 ERROR("Expected end-of-line in capture config file on "
487 "line %lu", line_no);
488 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
493 bytes_remaining -= (next_p - p);
497 if (*(eol - 1) == '\r')
501 /* Translate backslash to forward slash */
502 for (char *pp = p; pp != eol; pp++)
506 /* Remove drive letter */
507 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
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) {
524 DEBUG("Adding pattern \"%s\" to exclusion list", p);
525 ret = pattern_list_add_pattern(&config->exclusion_list, p);
527 case EXCLUSION_EXCEPTION:
528 DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
529 ret = pattern_list_add_pattern(&config->exclusion_exception, p);
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);
536 DEBUG("Adding pattern \"%s\" to alignment list", p);
537 ret = pattern_list_add_pattern(&config->alignment_list, p);
540 ERROR("Line %lu of capture configuration is not "
541 "in a block (such as [ExclusionList])",
543 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
551 destroy_capture_config(config);
555 static bool match_pattern(const char *path, const char *path_basename,
556 const struct pattern_list *list)
558 for (size_t i = 0; i < list->num_pats; i++) {
559 const char *pat = list->pats[i];
562 /* Absolute path from root of capture */
565 if (strchr(pat, '/'))
566 /* Relative path from root of capture */
569 /* A file name pattern */
570 string = path_basename;
572 if (fnmatch(pat, string, FNM_PATHNAME
578 DEBUG("`%s' matches the pattern \"%s\"",
586 static void print_pattern_list(const struct pattern_list *list)
588 for (size_t i = 0; i < list->num_pats; i++)
589 printf(" %s\n", list->pats[i]);
592 static void print_capture_config(const struct capture_config *config)
594 if (config->exclusion_list.num_pats) {
595 puts("Files or folders excluded from image capture:");
596 print_pattern_list(&config->exclusion_list);
601 /* Return true if the image capture configuration file indicates we should
602 * exclude the filename @path from capture.
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
610 bool exclude_path(const char *path, const struct capture_config *config,
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;
620 return match_pattern(path, basename, &config->exclusion_list) &&
621 !match_pattern(path, basename, &config->exclusion_exception);
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)
630 int (*capture_tree)(struct dentry **, const char *,
631 struct lookup_table *,
632 struct wim_security_data *,
633 const struct capture_config *,
634 int, wimlib_progress_func_t, void *);
637 struct dentry *root_dentry = NULL;
638 struct wim_security_data *sd;
639 struct capture_config config;
640 struct image_metadata *imd;
643 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
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;
649 capture_tree = build_dentry_tree_ntfs;
650 extra_arg = &w->ntfs_vol;
652 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
653 " cannot capture a WIM image directly from a NTFS volume!");
654 return WIMLIB_ERR_UNSUPPORTED;
657 capture_tree = build_dentry_tree;
661 DEBUG("Adding dentry tree from directory or NTFS volume `%s'.", source);
663 if (!name || !*name) {
664 ERROR("Must specify a non-empty string for the image name");
665 return WIMLIB_ERR_INVALID_PARAM;
667 if (!source || !*source) {
668 ERROR("Must specify the name of a directory or NTFS volume");
669 return WIMLIB_ERR_INVALID_PARAM;
672 if (w->hdr.total_parts != 1) {
673 ERROR("Cannot add an image to a split WIM");
674 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
677 if (wimlib_image_name_in_use(w, name)) {
678 ERROR("There is already an image named \"%s\" in `%s'",
680 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
683 DEBUG("Initializing capture configuration");
685 DEBUG("Using default capture configuration");
686 config_str = default_config;
687 config_len = strlen(default_config);
689 ret = init_capture_config(config_str, config_len, source, &config);
692 print_capture_config(&config);
694 DEBUG("Allocating security data");
696 sd = CALLOC(1, sizeof(struct wim_security_data));
698 ret = WIMLIB_ERR_NOMEM;
699 goto out_destroy_config;
701 sd->total_length = 8;
705 union wimlib_progress_info progress;
706 progress.scan.source = source;
707 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
710 DEBUG("Building dentry tree.");
711 ret = (*capture_tree)(&root_dentry, source, w->lookup_table, sd,
712 &config, add_image_flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
713 progress_func, extra_arg);
714 destroy_capture_config(&config);
717 ERROR("Failed to build dentry tree for `%s'", source);
718 goto out_free_security_data;
722 union wimlib_progress_info progress;
723 progress.scan.source = source;
724 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
727 DEBUG("Calculating full paths of dentries.");
728 ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
730 goto out_free_dentry_tree;
732 ret = add_new_dentry_tree(w, root_dentry, sd);
734 goto out_free_dentry_tree;
736 imd = &w->image_metadata[w->hdr.image_count - 1];
738 ret = dentry_tree_fix_inodes(root_dentry, &imd->inode_list);
740 goto out_destroy_imd;
742 DEBUG("Assigning hard link group IDs");
743 assign_inode_numbers(&imd->inode_list);
745 ret = xml_add_image(w, name);
747 goto out_destroy_imd;
749 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
750 wimlib_set_boot_idx(w, w->hdr.image_count);
753 destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
755 w->hdr.image_count--;
757 out_free_dentry_tree:
758 free_dentry_tree(root_dentry, w->lookup_table);
759 out_free_security_data:
760 free_security_data(sd);
762 destroy_capture_config(&config);