4 * Support for modifying WIM files with image-level operations (delete an image,
5 * add an image, export an imagex from one WIM to another.) There is nothing
6 * here that lets you change individual files in the WIM; for that you will need
7 * to look at the filesystem implementation in mount.c.
11 * Copyright (C) 2012 Eric Biggers
13 * This file is part of wimlib, a library for working with WIM files.
15 * wimlib is free software; you can redistribute it and/or modify it under the
16 * terms of the GNU General Public License as published by the Free
17 * Software Foundation; either version 3 of the License, or (at your option)
20 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
21 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
22 * A PARTICULAR PURPOSE. See the GNU General Public License for more
25 * You should have received a copy of the GNU General Public License
26 * along with wimlib; if not, see http://www.gnu.org/licenses/.
29 #include "wimlib_internal.h"
34 #include "lookup_table.h"
43 /** Private flag: Used to mark that we currently adding the root directory of
45 #define WIMLIB_ADD_IMAGE_FLAG_ROOT 0x80000000
47 void destroy_image_metadata(struct image_metadata *imd,struct lookup_table *lt)
49 free_dentry_tree(imd->root_dentry, lt);
50 free_security_data(imd->security_data);
51 free_link_group_table(imd->lgt);
53 /* Get rid of the lookup table entry for this image's metadata resource
56 lookup_table_remove(lt, imd->metadata_lte);
60 * Recursively builds a dentry tree from a directory tree on disk, outside the
63 * @root: A dentry that has already been created for the root of the dentry
65 * @root_disk_path: The path to the root of the tree on disk.
66 * @lookup_table: The lookup table for the WIM file. For each file added to the
67 * dentry tree being built, an entry is added to the lookup table,
68 * unless an identical file is already in the lookup table. These
69 * lookup table entries that are added point to the file on disk.
71 * @return: 0 on success, nonzero on failure. It is a failure if any of
72 * the files cannot be `stat'ed, or if any of the needed
73 * directories cannot be opened or read. Failure to add the files
74 * to the WIM may still occur later when trying to actually read
75 * the regular files in the tree into the WIM as file resources.
77 static int build_dentry_tree(struct dentry **root_ret, const char *root_disk_path,
78 struct lookup_table *lookup_table,
79 struct wim_security_data *sd,
80 const struct capture_config *config,
84 struct stat root_stbuf;
86 int (*stat_fn)(const char *restrict, struct stat *restrict);
90 if (exclude_path(root_disk_path, config, true)) {
91 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
92 printf("Excluding file `%s' from capture\n",
99 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
104 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
105 printf("Scanning `%s'\n", root_disk_path);
108 ret = (*stat_fn)(root_disk_path, &root_stbuf);
110 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
111 return WIMLIB_ERR_STAT;
114 if ((add_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
115 !S_ISDIR(root_stbuf.st_mode)) {
116 ERROR("`%s' is not a directory", root_disk_path);
117 return WIMLIB_ERR_NOTDIR;
119 if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
120 && !S_ISLNK(root_stbuf.st_mode)) {
121 ERROR("`%s' is not a regular file, directory, or symbolic link.",
123 return WIMLIB_ERR_SPECIAL_FILE;
126 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT)
129 filename = path_basename(root_disk_path);
131 root = new_dentry(filename);
133 return WIMLIB_ERR_NOMEM;
135 stbuf_to_dentry(&root_stbuf, root);
136 add_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
137 root->resolved = true;
139 if (dentry_is_directory(root)) {
140 /* Open the directory on disk */
143 struct dentry *child;
145 dir = opendir(root_disk_path);
147 ERROR_WITH_ERRNO("Failed to open the directory `%s'",
149 return WIMLIB_ERR_OPEN;
152 /* Buffer for names of files in directory. */
153 size_t len = strlen(root_disk_path);
154 char name[len + 1 + FILENAME_MAX + 1];
155 memcpy(name, root_disk_path, len);
158 /* Create a dentry for each entry in the directory on disk, and recurse
159 * to any subdirectories. */
160 while ((p = readdir(dir)) != NULL) {
161 if (p->d_name[0] == '.' && (p->d_name[1] == '\0'
162 || (p->d_name[1] == '.' && p->d_name[2] == '\0')))
164 strcpy(name + len + 1, p->d_name);
165 ret = build_dentry_tree(&child, name, lookup_table,
167 add_flags, extra_arg);
171 link_dentry(child, root);
174 } else if (dentry_is_symlink(root)) {
175 /* Archiving a symbolic link */
176 char deref_name_buf[4096];
177 ssize_t deref_name_len;
179 deref_name_len = readlink(root_disk_path, deref_name_buf,
180 sizeof(deref_name_buf) - 1);
181 if (deref_name_len == -1) {
182 ERROR_WITH_ERRNO("Failed to read target of "
183 "symbolic link `%s'", root_disk_path);
184 return WIMLIB_ERR_READLINK;
186 deref_name_buf[deref_name_len] = '\0';
187 DEBUG("Read symlink `%s'", deref_name_buf);
188 ret = dentry_set_symlink(root, deref_name_buf,
192 struct lookup_table_entry *lte;
193 u8 hash[SHA1_HASH_SIZE];
195 /* Empty files do not have to have a lookup table entry. */
196 if (root_stbuf.st_size == 0)
199 /* For each regular file, we must check to see if the file is in
200 * the lookup table already; if it is, we increment its refcnt;
201 * otherwise, we create a new lookup table entry and insert it.
203 ret = sha1sum(root_disk_path, hash);
207 lte = __lookup_resource(lookup_table, hash);
210 DEBUG("Add lte reference %u for `%s'", lte->refcnt,
213 char *file_on_disk = STRDUP(root_disk_path);
215 ERROR("Failed to allocate memory for file path");
216 return WIMLIB_ERR_NOMEM;
218 lte = new_lookup_table_entry();
221 return WIMLIB_ERR_NOMEM;
223 lte->file_on_disk = file_on_disk;
224 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
225 lte->resource_entry.original_size = root_stbuf.st_size;
226 lte->resource_entry.size = root_stbuf.st_size;
227 copy_hash(lte->hash, hash);
228 lookup_table_insert(lookup_table, lte);
243 * This function takes in a dentry that was previously located only in image(s)
244 * in @src_wim, but now is being added to @dest_wim. If there is in fact already a
245 * lookup table entry for this file in the lookup table of the destination WIM
246 * file, we simply increment its reference count. Otherwise, a new lookup table
247 * entry is created that references the location of the file resource in the
248 * source WIM file through the other_wim_fp field of the lookup table entry.
250 static int add_lte_to_dest_wim(struct dentry *dentry, void *arg)
252 WIMStruct *src_wim, *dest_wim;
254 src_wim = ((struct wim_pair*)arg)->src_wim;
255 dest_wim = ((struct wim_pair*)arg)->dest_wim;
257 wimlib_assert(!dentry->resolved);
259 for (unsigned i = 0; i < (unsigned)dentry->num_ads + 1; i++) {
260 struct lookup_table_entry *src_lte, *dest_lte;
261 src_lte = dentry_stream_lte_unresolved(dentry, i,
262 src_wim->lookup_table);
265 dest_lte = dentry_stream_lte_unresolved(dentry, i,
266 dest_wim->lookup_table);
270 dest_lte = new_lookup_table_entry();
272 return WIMLIB_ERR_NOMEM;
273 dest_lte->resource_location = RESOURCE_IN_WIM;
274 dest_lte->wim = src_wim;
275 memcpy(&dest_lte->resource_entry,
276 &src_lte->resource_entry,
277 sizeof(struct resource_entry));
278 copy_hash(dest_lte->hash,
279 dentry_stream_hash_unresolved(dentry, i));
280 lookup_table_insert(dest_wim->lookup_table, dest_lte);
287 * Adds an image (given by its dentry tree) to the image metadata array of a WIM
288 * file, adds an entry to the lookup table for the image metadata, updates the
289 * image count in the header, and selects the new image.
291 * Does not update the XML data.
293 * @w: The WIMStruct for the WIM file.
294 * @root_dentry: The root of the directory tree for the image.
295 * @sd: The security data for the image.
297 static int add_new_dentry_tree(WIMStruct *w, struct dentry *root_dentry,
298 struct wim_security_data *sd)
300 struct lookup_table_entry *metadata_lte;
301 struct image_metadata *imd;
302 struct image_metadata *new_imd;
303 struct link_group_table *lgt;
305 DEBUG("Reallocating image metadata array for image_count = %u",
306 w->hdr.image_count + 1);
307 imd = CALLOC((w->hdr.image_count + 1), sizeof(struct image_metadata));
310 ERROR("Failed to allocate memory for new image metadata array");
311 return WIMLIB_ERR_NOMEM;
314 memcpy(imd, w->image_metadata,
315 w->hdr.image_count * sizeof(struct image_metadata));
317 metadata_lte = new_lookup_table_entry();
321 lgt = new_link_group_table(9001);
323 goto out_free_metadata_lte;
325 metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
326 random_hash(metadata_lte->hash);
327 lookup_table_insert(w->lookup_table, metadata_lte);
329 new_imd = &imd[w->hdr.image_count];
331 new_imd->root_dentry = root_dentry;
332 new_imd->metadata_lte = metadata_lte;
333 new_imd->security_data = sd;
335 new_imd->modified = true;
337 FREE(w->image_metadata);
338 w->image_metadata = imd;
339 w->hdr.image_count++;
341 /* Change the current image to the new one. */
342 return wimlib_select_image(w, w->hdr.image_count);
343 out_free_metadata_lte:
347 return WIMLIB_ERR_NOMEM;
352 * Copies an image, or all the images, from a WIM file, into another WIM file.
354 WIMLIBAPI int wimlib_export_image(WIMStruct *src_wim,
357 const char *dest_name,
358 const char *dest_description,
364 struct wim_pair wims;
365 struct wim_security_data *sd;
367 if (src_image == WIM_ALL_IMAGES) {
368 if (src_wim->hdr.image_count > 1) {
370 /* multi-image export. */
372 if ((flags & WIMLIB_EXPORT_FLAG_BOOT) &&
373 (src_wim->hdr.boot_idx == 0))
375 /* Specifying the boot flag on a multi-image
376 * source WIM makes the boot index default to
377 * the bootable image in the source WIM. It is
378 * an error if there is no such bootable image.
380 ERROR("Cannot specify `boot' flag when "
381 "exporting multiple images from a WIM "
382 "with no bootable images");
383 return WIMLIB_ERR_INVALID_PARAM;
385 if (dest_name || dest_description) {
386 ERROR("Image name or image description was "
387 "specified, but we are exporting "
389 return WIMLIB_ERR_INVALID_PARAM;
391 for (i = 1; i <= src_wim->hdr.image_count; i++) {
392 int export_flags = flags;
394 if (i != src_wim->hdr.boot_idx)
395 export_flags &= ~WIMLIB_EXPORT_FLAG_BOOT;
397 ret = wimlib_export_image(src_wim, i, dest_wim,
410 ret = wimlib_select_image(src_wim, src_image);
412 ERROR("Could not select image %d from the WIM `%s' "
413 "to export it", src_image, src_wim->filename);
418 dest_name = wimlib_get_image_name(src_wim, src_image);
419 DEBUG("Using name `%s' for source image %d",
420 dest_name, src_image);
423 DEBUG("Exporting image %d from `%s'", src_image, src_wim->filename);
425 if (wimlib_image_name_in_use(dest_wim, dest_name)) {
426 ERROR("There is already an image named `%s' in the "
427 "destination WIM", dest_name);
428 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
432 /* Cleaning up here on failure would be hard. For example, we could
433 * fail to allocate memory in add_lte_to_dest_wim(),
434 * leaving the lookup table entries in the destination WIM in an
435 * inconsistent state. Until these issues can be resolved,
436 * wimlib_export_image() is documented as leaving dest_wim is an
437 * indeterminate state. */
438 root = wim_root_dentry(src_wim);
439 sd = wim_security_data(src_wim);
440 for_dentry_in_tree(root, increment_dentry_refcnt, NULL);
441 wims.src_wim = src_wim;
442 wims.dest_wim = dest_wim;
443 ret = for_dentry_in_tree(root, add_lte_to_dest_wim, &wims);
446 ret = add_new_dentry_tree(dest_wim, root, sd);
451 if (flags & WIMLIB_EXPORT_FLAG_BOOT) {
452 DEBUG("Setting boot_idx to %d", dest_wim->hdr.image_count);
453 dest_wim->hdr.boot_idx = dest_wim->hdr.image_count;
456 return xml_export_image(src_wim->wim_info, src_image, &dest_wim->wim_info,
457 dest_name, dest_description);
461 * Deletes an image from the WIM.
463 WIMLIBAPI int wimlib_delete_image(WIMStruct *w, int image)
469 if (image == WIM_ALL_IMAGES) {
470 num_images = w->hdr.image_count;
471 for (i = 1; i <= num_images; i++) {
472 /* Always delete the first image, since by the end
473 * there won't be any more than that! */
474 ret = wimlib_delete_image(w, 1);
481 DEBUG("Deleting image %d", image);
483 /* Even if the dentry tree is not allocated, we must select it (and
484 * therefore allocate it) so that we can decrement the reference counts
485 * in the lookup table. */
486 ret = wimlib_select_image(w, image);
490 /* Free the dentry tree, any lookup table entries that have their
491 * refcnt decremented to 0, and the security data. */
492 destroy_image_metadata(wim_get_current_image_metadata(w),
495 /* Get rid of the empty slot in the image metadata array. */
496 memmove(&w->image_metadata[image - 1], &w->image_metadata[image],
497 (w->hdr.image_count - image) * sizeof(struct image_metadata));
499 /* Decrement the image count. */
500 if (--w->hdr.image_count == 0) {
501 FREE(w->image_metadata);
502 w->image_metadata = NULL;
505 /* Fix the boot index. */
506 if (w->hdr.boot_idx == image)
508 else if (w->hdr.boot_idx > image)
511 w->current_image = WIM_NO_IMAGE;
513 /* Remove the image from the XML information. */
514 xml_delete_image(&w->wim_info, image);
522 COMPRESSION_EXCLUSION_LIST,
526 /* Default capture configuration file when none is specified. */
527 static const char *default_config =
532 "\\System Volume Information\n"
536 "[CompressionExclusionList]\n"
540 "\\WINDOWS\\inf\\*.pnf\n";
542 static void destroy_pattern_list(struct pattern_list *list)
547 static void destroy_capture_config(struct capture_config *config)
549 destroy_pattern_list(&config->exclusion_list);
550 destroy_pattern_list(&config->exclusion_exception);
551 destroy_pattern_list(&config->compression_exclusion_list);
552 destroy_pattern_list(&config->alignment_list);
553 FREE(config->config_str);
554 FREE(config->prefix);
555 memset(config, 0, sizeof(*config));
558 static int pattern_list_add_pattern(struct pattern_list *list,
562 if (list->num_pats >= list->num_allocated_pats) {
563 pats = REALLOC(list->pats,
564 sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
566 return WIMLIB_ERR_NOMEM;
567 list->num_allocated_pats += 8;
570 list->pats[list->num_pats++] = pattern;
574 /* Parses the contents of the image capture configuration file and fills in a
575 * `struct capture_config'. */
576 static int init_capture_config(const char *_config_str, size_t config_len,
577 const char *_prefix, struct capture_config *config)
584 size_t bytes_remaining;
585 enum pattern_type type = NONE;
587 unsigned long line_no = 0;
589 DEBUG("config_len = %zu", config_len);
590 bytes_remaining = config_len;
591 memset(config, 0, sizeof(*config));
592 config_str = MALLOC(config_len);
594 ERROR("Could not duplicate capture config string");
595 return WIMLIB_ERR_NOMEM;
597 prefix = STRDUP(_prefix);
600 return WIMLIB_ERR_NOMEM;
603 memcpy(config_str, _config_str, config_len);
605 config->config_str = config_str;
606 config->prefix = prefix;
607 config->prefix_len = strlen(prefix);
608 while (bytes_remaining) {
611 eol = memchr(p, '\n', bytes_remaining);
613 ERROR("Expected end-of-line in capture config file on "
614 "line %lu", line_no);
615 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
620 bytes_remaining -= (eol - p) + 1;
624 if (*(eol - 1) == '\r')
628 /* Translate backslash to forward slash */
629 for (char *pp = p; pp != eol; pp++)
633 /* Remove drive letter */
634 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
638 if (strcmp(p, "[ExclusionList]") == 0)
639 type = EXCLUSION_LIST;
640 else if (strcmp(p, "[ExclusionException]") == 0)
641 type = EXCLUSION_EXCEPTION;
642 else if (strcmp(p, "[CompressionExclusionList]") == 0)
643 type = COMPRESSION_EXCLUSION_LIST;
644 else if (strcmp(p, "[AlignmentList]") == 0)
645 type = ALIGNMENT_LIST;
646 else if (p[0] == '[' && strrchr(p, ']')) {
647 ERROR("Unknown capture configuration section `%s'", p);
648 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
650 } else switch (type) {
652 DEBUG("Adding pattern \"%s\" to exclusion list", p);
653 ret = pattern_list_add_pattern(&config->exclusion_list, p);
655 case EXCLUSION_EXCEPTION:
656 DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
657 ret = pattern_list_add_pattern(&config->exclusion_exception, p);
659 case COMPRESSION_EXCLUSION_LIST:
660 DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
661 ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
664 DEBUG("Adding pattern \"%s\" to alignment list", p);
665 ret = pattern_list_add_pattern(&config->alignment_list, p);
668 ERROR("Line %lu of capture configuration is not "
669 "in a block (such as [ExclusionList])",
671 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
679 destroy_capture_config(config);
683 static bool match_pattern(const char *path, const char *path_basename,
684 const struct pattern_list *list)
686 for (size_t i = 0; i < list->num_pats; i++) {
687 const char *pat = list->pats[i];
690 /* Absolute path from root of capture */
693 if (strchr(pat, '/'))
694 /* Relative path from root of capture */
697 /* A file name pattern */
698 string = path_basename;
700 if (fnmatch(pat, string, FNM_PATHNAME
706 DEBUG("`%s' matches the pattern \"%s\"",
714 static void print_pattern_list(const struct pattern_list *list)
716 for (size_t i = 0; i < list->num_pats; i++)
717 printf(" %s\n", list->pats[i]);
720 static void print_capture_config(const struct capture_config *config)
722 if (config->exclusion_list.num_pats) {
723 puts("Files or folders excluded from image capture:");
724 print_pattern_list(&config->exclusion_list);
729 /* Return true if the image capture configuration file indicates we should
730 * exclude the filename @path from capture.
732 * If @exclude_prefix is %true, the part of the path up and including the name
733 * of the directory being captured is not included in the path for matching
734 * purposes. This allows, for example, a pattern like /hiberfil.sys to match a
735 * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
738 bool exclude_path(const char *path, const struct capture_config *config,
741 const char *basename = path_basename(path);
742 if (exclude_prefix) {
743 wimlib_assert(strlen(path) >= config->prefix_len);
744 if (memcmp(config->prefix, path, config->prefix_len) == 0
745 && path[config->prefix_len] == '/')
746 path += config->prefix_len;
748 return match_pattern(path, basename, &config->exclusion_list) &&
749 !match_pattern(path, basename, &config->exclusion_exception);
756 * Adds an image to the WIM, delegating the capture of the dentry tree and
757 * security data to the function @capture_tree passed as a parameter.
758 * Currently, @capture_tree may be build_dentry_tree() for capturing a "regular"
759 * directory tree on disk, or build_dentry_tree_ntfs() for capturing a WIM image
760 * directory from a NTFS volume using libntfs-3g.
762 * The @capture_tree function is also expected to create lookup table entries
763 * for all the file streams it captures and insert them into @lookup_table,
764 * being careful to look for identical entries that already exist and simply
765 * increment the reference count for them rather than duplicating the entry.
767 int do_add_image(WIMStruct *w, const char *dir, const char *name,
768 const char *config_str, size_t config_len,
770 int (*capture_tree)(struct dentry **, const char *,
771 struct lookup_table *,
772 struct wim_security_data *,
773 const struct capture_config *,
777 struct dentry *root_dentry = NULL;
778 struct wim_security_data *sd;
779 struct capture_config config;
780 struct link_group_table *lgt;
783 DEBUG("Adding dentry tree from directory or NTFS volume `%s'.", dir);
785 if (!name || !*name) {
786 ERROR("Must specify a non-empty string for the image name");
787 return WIMLIB_ERR_INVALID_PARAM;
790 ERROR("Must specify the name of a directory or NTFS volume");
791 return WIMLIB_ERR_INVALID_PARAM;
794 if (wimlib_image_name_in_use(w, name)) {
795 ERROR("There is already an image named \"%s\" in `%s'",
797 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
800 DEBUG("Initializing capture configuration");
802 DEBUG("Using default capture configuration");
803 config_str = default_config;
804 config_len = strlen(default_config);
806 ret = init_capture_config(config_str, config_len, dir, &config);
809 print_capture_config(&config);
811 DEBUG("Allocating security data");
813 sd = CALLOC(1, sizeof(struct wim_security_data));
815 goto out_destroy_config;
816 sd->total_length = 8;
819 DEBUG("Building dentry tree.");
820 ret = (*capture_tree)(&root_dentry, dir, w->lookup_table, sd,
821 &config, flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
823 destroy_capture_config(&config);
826 ERROR("Failed to build dentry tree for `%s'", dir);
827 goto out_free_dentry_tree;
830 DEBUG("Calculating full paths of dentries.");
831 ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
833 goto out_free_dentry_tree;
835 ret = add_new_dentry_tree(w, root_dentry, sd);
837 goto out_free_dentry_tree;
839 lgt = w->image_metadata[w->hdr.image_count - 1].lgt;
840 DEBUG("Inserting dentries into hard link group table");
841 ret = for_dentry_in_tree(root_dentry, link_group_table_insert, lgt);
844 goto out_destroy_imd;
846 DEBUG("Cleanup up the hard link groups");
847 ret = fix_link_groups(lgt);
849 goto out_destroy_imd;
851 DEBUG("Assigning hard link group IDs");
852 assign_link_group_ids(w->image_metadata[w->hdr.image_count - 1].lgt);
854 if (flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
855 wimlib_set_boot_idx(w, w->hdr.image_count);
857 ret = xml_add_image(w, root_dentry, name);
859 goto out_destroy_imd;
863 destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
865 w->hdr.image_count--;
867 out_free_dentry_tree:
868 free_dentry_tree(root_dentry, w->lookup_table);
869 free_security_data(sd);
871 destroy_capture_config(&config);
876 * Adds an image to a WIM file from a directory tree on disk.
878 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *dir,
879 const char *name, const char *config_str,
880 size_t config_len, int flags)
882 return do_add_image(w, dir, name, config_str, config_len, flags,
883 build_dentry_tree, NULL);