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 Lesser General Public License as published by the Free
17 * Software Foundation; either version 2.1 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 Lesser General Public License for more
25 * You should have received a copy of the GNU Lesser 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"
42 /** Private flag: Used to mark that we currently adding the root directory of
44 #define WIMLIB_ADD_IMAGE_FLAG_ROOT 0x80000000
46 void destroy_image_metadata(struct image_metadata *imd,struct lookup_table *lt)
48 free_dentry_tree(imd->root_dentry, lt);
49 free_security_data(imd->security_data);
50 free_link_group_table(imd->lgt);
52 /* Get rid of the lookup table entry for this image's metadata resource
55 lookup_table_remove(lt, imd->metadata_lte);
59 * Recursively builds a dentry tree from a directory tree on disk, outside the
62 * @root: A dentry that has already been created for the root of the dentry
64 * @root_disk_path: The path to the root of the tree on disk.
65 * @lookup_table: The lookup table for the WIM file. For each file added to the
66 * dentry tree being built, an entry is added to the lookup table,
67 * unless an identical file is already in the lookup table. These
68 * lookup table entries that are added point to the file on disk.
70 * @return: 0 on success, nonzero on failure. It is a failure if any of
71 * the files cannot be `stat'ed, or if any of the needed
72 * directories cannot be opened or read. Failure to add the files
73 * to the WIM may still occur later when trying to actually read
74 * the regular files in the tree into the WIM as file resources.
76 static int build_dentry_tree(struct dentry **root_ret, const char *root_disk_path,
77 struct lookup_table *lookup_table,
78 struct wim_security_data *sd,
79 const struct capture_config *config,
83 struct stat root_stbuf;
85 int (*stat_fn)(const char *restrict, struct stat *restrict);
88 if (exclude_path(root_disk_path, config, true)) {
89 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
90 printf("Excluding file `%s' from capture\n",
97 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
102 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
103 printf("Scanning `%s'\n", root_disk_path);
106 ret = (*stat_fn)(root_disk_path, &root_stbuf);
108 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
109 return WIMLIB_ERR_STAT;
112 if ((add_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
113 !S_ISDIR(root_stbuf.st_mode)) {
114 ERROR("`%s' is not a directory", root_disk_path);
115 return WIMLIB_ERR_NOTDIR;
117 if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
118 && !S_ISLNK(root_stbuf.st_mode)) {
119 ERROR("`%s' is not a regular file, directory, or symbolic link.");
120 return WIMLIB_ERR_SPECIAL_FILE;
123 root = new_dentry(path_basename(root_disk_path));
125 return WIMLIB_ERR_NOMEM;
127 stbuf_to_dentry(&root_stbuf, root);
128 add_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
129 root->resolved = true;
131 if (dentry_is_directory(root)) {
132 /* Open the directory on disk */
135 struct dentry *child;
137 dir = opendir(root_disk_path);
139 ERROR_WITH_ERRNO("Failed to open the directory `%s'",
141 return WIMLIB_ERR_OPEN;
144 /* Buffer for names of files in directory. */
145 size_t len = strlen(root_disk_path);
146 char name[len + 1 + FILENAME_MAX + 1];
147 memcpy(name, root_disk_path, len);
150 /* Create a dentry for each entry in the directory on disk, and recurse
151 * to any subdirectories. */
152 while ((p = readdir(dir)) != NULL) {
153 if (p->d_name[0] == '.' && (p->d_name[1] == '\0'
154 || (p->d_name[1] == '.' && p->d_name[2] == '\0')))
156 strcpy(name + len + 1, p->d_name);
157 ret = build_dentry_tree(&child, name, lookup_table,
159 add_flags, extra_arg);
163 link_dentry(child, root);
166 } else if (dentry_is_symlink(root)) {
167 /* Archiving a symbolic link */
168 size_t symlink_buf_len;
169 char deref_name_buf[4096];
170 ssize_t deref_name_len;
172 deref_name_len = readlink(root_disk_path, deref_name_buf,
173 sizeof(deref_name_buf) - 1);
174 if (deref_name_len == -1) {
175 ERROR_WITH_ERRNO("Failed to read target of "
176 "symbolic link `%s'", root_disk_path);
177 return WIMLIB_ERR_READLINK;
179 deref_name_buf[deref_name_len] = '\0';
180 DEBUG("Read symlink `%s'", deref_name_buf);
181 ret = dentry_set_symlink(root, deref_name_buf,
185 struct lookup_table_entry *lte;
186 u8 hash[SHA1_HASH_SIZE];
188 /* For each regular file, we must check to see if the file is in
189 * the lookup table already; if it is, we increment its refcnt;
190 * otherwise, we create a new lookup table entry and insert it.
192 ret = sha1sum(root_disk_path, hash);
196 lte = __lookup_resource(lookup_table, hash);
199 DEBUG("Add lte reference %u for `%s'", lte->refcnt,
202 char *file_on_disk = STRDUP(root_disk_path);
204 ERROR("Failed to allocate memory for file path");
205 return WIMLIB_ERR_NOMEM;
207 lte = new_lookup_table_entry();
210 return WIMLIB_ERR_NOMEM;
212 lte->file_on_disk = file_on_disk;
213 lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
214 lte->resource_entry.original_size = root_stbuf.st_size;
215 lte->resource_entry.size = root_stbuf.st_size;
216 copy_hash(lte->hash, hash);
217 lookup_table_insert(lookup_table, lte);
231 * This function takes in a dentry that was previously located only in image(s)
232 * in @src_wim, but now is being added to @dest_wim. If there is in fact already a
233 * lookup table entry for this file in the lookup table of the destination WIM
234 * file, we simply increment its reference count. Otherwise, a new lookup table
235 * entry is created that references the location of the file resource in the
236 * source WIM file through the other_wim_fp field of the lookup table entry.
238 static int add_lte_to_dest_wim(struct dentry *dentry, void *arg)
240 WIMStruct *src_wim, *dest_wim;
242 src_wim = ((struct wim_pair*)arg)->src_wim;
243 dest_wim = ((struct wim_pair*)arg)->dest_wim;
245 wimlib_assert(!dentry->resolved);
247 for (unsigned i = 0; i < (unsigned)dentry->num_ads + 1; i++) {
248 struct lookup_table_entry *src_lte, *dest_lte;
249 src_lte = dentry_stream_lte_unresolved(dentry, i,
250 src_wim->lookup_table);
253 dest_lte = dentry_stream_lte_unresolved(dentry, i,
254 dest_wim->lookup_table);
258 dest_lte = new_lookup_table_entry();
260 return WIMLIB_ERR_NOMEM;
261 dest_lte->resource_location = RESOURCE_IN_WIM;
262 dest_lte->wim = src_wim;
263 memcpy(&dest_lte->resource_entry,
264 &src_lte->resource_entry,
265 sizeof(struct resource_entry));
266 copy_hash(dest_lte->hash,
267 dentry_stream_hash_unresolved(dentry, i));
268 lookup_table_insert(dest_wim->lookup_table, dest_lte);
275 * Adds an image (given by its dentry tree) to the image metadata array of a WIM
276 * file, adds an entry to the lookup table for the image metadata, updates the
277 * image count in the header, and selects the new image.
279 * Does not update the XML data.
281 * @w: The WIMStruct for the WIM file.
282 * @root_dentry: The root of the directory tree for the image.
284 static int add_new_dentry_tree(WIMStruct *w, struct dentry *root_dentry,
285 struct wim_security_data *sd)
287 struct lookup_table_entry *metadata_lte;
288 struct image_metadata *imd;
289 struct image_metadata *new_imd;
290 struct link_group_table *lgt;
292 DEBUG("Reallocating image metadata array for image_count = %u",
293 w->hdr.image_count + 1);
294 imd = CALLOC((w->hdr.image_count + 1), sizeof(struct image_metadata));
297 ERROR("Failed to allocate memory for new image metadata array");
298 return WIMLIB_ERR_NOMEM;
301 memcpy(imd, w->image_metadata,
302 w->hdr.image_count * sizeof(struct image_metadata));
304 metadata_lte = new_lookup_table_entry();
308 lgt = new_link_group_table(9001);
310 goto out_free_security_data;
312 metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
313 random_hash(metadata_lte->hash);
314 lookup_table_insert(w->lookup_table, metadata_lte);
316 new_imd = &imd[w->hdr.image_count];
318 new_imd->root_dentry = root_dentry;
319 new_imd->metadata_lte = metadata_lte;
320 new_imd->security_data = sd;
322 new_imd->modified = true;
324 FREE(w->image_metadata);
325 w->image_metadata = imd;
326 w->hdr.image_count++;
328 /* Change the current image to the new one. */
329 return wimlib_select_image(w, w->hdr.image_count);
330 out_free_security_data:
332 out_free_metadata_lte:
336 return WIMLIB_ERR_NOMEM;
341 * Copies an image, or all the images, from a WIM file, into another WIM file.
343 WIMLIBAPI int wimlib_export_image(WIMStruct *src_wim,
346 const char *dest_name,
347 const char *dest_description,
353 struct wim_pair wims;
354 struct wim_security_data *sd;
356 if (src_image == WIM_ALL_IMAGES) {
357 if (src_wim->hdr.image_count > 1) {
359 /* multi-image export. */
361 if ((flags & WIMLIB_EXPORT_FLAG_BOOT) &&
362 (src_wim->hdr.boot_idx == 0))
364 /* Specifying the boot flag on a multi-image
365 * source WIM makes the boot index default to
366 * the bootable image in the source WIM. It is
367 * an error if there is no such bootable image.
369 ERROR("Cannot specify `boot' flag when "
370 "exporting multiple images from a WIM "
371 "with no bootable images");
372 return WIMLIB_ERR_INVALID_PARAM;
374 if (dest_name || dest_description) {
375 ERROR("Image name or image description was "
376 "specified, but we are exporting "
378 return WIMLIB_ERR_INVALID_PARAM;
380 for (i = 1; i <= src_wim->hdr.image_count; i++) {
381 int export_flags = flags;
383 if (i != src_wim->hdr.boot_idx)
384 export_flags &= ~WIMLIB_EXPORT_FLAG_BOOT;
386 ret = wimlib_export_image(src_wim, i, dest_wim,
399 ret = wimlib_select_image(src_wim, src_image);
401 ERROR("Could not select image %d from the WIM `%s' "
402 "to export it", src_image, src_wim->filename);
407 dest_name = wimlib_get_image_name(src_wim, src_image);
408 DEBUG("Using name `%s' for source image %d",
409 dest_name, src_image);
412 DEBUG("Exporting image %d from `%s'", src_image, src_wim->filename);
414 if (wimlib_image_name_in_use(dest_wim, dest_name)) {
415 ERROR("There is already an image named `%s' in the "
416 "destination WIM", dest_name);
417 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
421 /* Cleaning up here on failure would be hard. For example, we could
422 * fail to allocate memory in add_lte_to_dest_wim(),
423 * leaving the lookup table entries in the destination WIM in an
424 * inconsistent state. Until these issues can be resolved,
425 * wimlib_export_image() is documented as leaving dest_wim is an
426 * indeterminate state. */
427 root = wim_root_dentry(src_wim);
428 sd = wim_security_data(src_wim);
429 for_dentry_in_tree(root, increment_dentry_refcnt, NULL);
430 wims.src_wim = src_wim;
431 wims.dest_wim = dest_wim;
432 ret = for_dentry_in_tree(root, add_lte_to_dest_wim, &wims);
435 ret = add_new_dentry_tree(dest_wim, root, sd);
440 if (flags & WIMLIB_EXPORT_FLAG_BOOT) {
441 DEBUG("Setting boot_idx to %d", dest_wim->hdr.image_count);
442 dest_wim->hdr.boot_idx = dest_wim->hdr.image_count;
445 return xml_export_image(src_wim->wim_info, src_image, &dest_wim->wim_info,
446 dest_name, dest_description);
450 * Deletes an image from the WIM.
452 WIMLIBAPI int wimlib_delete_image(WIMStruct *w, int image)
458 if (image == WIM_ALL_IMAGES) {
459 num_images = w->hdr.image_count;
460 for (i = 1; i <= num_images; i++) {
461 /* Always delete the first image, since by the end
462 * there won't be any more than that! */
463 ret = wimlib_delete_image(w, 1);
470 DEBUG("Deleting image %d", image);
472 /* Even if the dentry tree is not allocated, we must select it (and
473 * therefore allocate it) so that we can decrement the reference counts
474 * in the lookup table. */
475 ret = wimlib_select_image(w, image);
479 /* Free the dentry tree, any lookup table entries that have their
480 * refcnt decremented to 0, and the security data. */
481 destroy_image_metadata(wim_get_current_image_metadata(w),
484 /* Get rid of the empty slot in the image metadata array. */
485 memmove(&w->image_metadata[image - 1], &w->image_metadata[image],
486 (w->hdr.image_count - image) * sizeof(struct image_metadata));
488 /* Decrement the image count. */
489 if (--w->hdr.image_count == 0) {
490 FREE(w->image_metadata);
491 w->image_metadata = NULL;
494 /* Fix the boot index. */
495 if (w->hdr.boot_idx == image)
497 else if (w->hdr.boot_idx > image)
500 w->current_image = WIM_NO_IMAGE;
502 /* Remove the image from the XML information. */
503 xml_delete_image(&w->wim_info, image);
511 COMPRESSION_EXCLUSION_LIST,
515 static const char *default_config =
520 "\"\\System Volume Information\"\n"
524 "[CompressionExclusionList]\n"
528 "\\WINDOWS\\inf\\*.pnf\n";
530 static void destroy_pattern_list(struct pattern_list *list)
535 static void destroy_capture_config(struct capture_config *config)
537 destroy_pattern_list(&config->exclusion_list);
538 destroy_pattern_list(&config->exclusion_exception);
539 destroy_pattern_list(&config->compression_exclusion_list);
540 destroy_pattern_list(&config->alignment_list);
541 FREE(config->config_str);
542 FREE(config->prefix);
543 memset(config, 0, sizeof(*config));
546 static int pattern_list_add_pattern(struct pattern_list *list,
550 if (list->num_pats >= list->num_allocated_pats) {
551 pats = REALLOC(list->pats,
552 sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
554 return WIMLIB_ERR_NOMEM;
555 list->num_allocated_pats += 8;
558 list->pats[list->num_pats++] = pattern;
562 static int init_capture_config(const char *_config_str, size_t config_len,
563 const char *_prefix, struct capture_config *config)
570 size_t next_bytes_remaining;
571 size_t bytes_remaining;
572 enum pattern_type type = NONE;
574 unsigned long line_no = 0;
576 DEBUG("config_len = %zu", config_len);
577 bytes_remaining = config_len;
578 memset(config, 0, sizeof(*config));
579 config_str = MALLOC(config_len);
581 ERROR("Could not duplicate capture config string");
582 return WIMLIB_ERR_NOMEM;
584 prefix = STRDUP(_prefix);
587 return WIMLIB_ERR_NOMEM;
590 memcpy(config_str, _config_str, config_len);
592 config->config_str = config_str;
593 config->prefix = prefix;
594 config->prefix_len = strlen(prefix);
595 while (bytes_remaining) {
598 eol = memchr(p, '\n', bytes_remaining);
600 ERROR("Expected end-of-line in capture config file on "
601 "line %lu", line_no);
602 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
607 bytes_remaining -= (eol - p) + 1;
611 if (*(eol - 1) == '\r')
615 /* Translate backslash to forward slash */
616 for (char *pp = p; pp != eol; pp++)
620 if (strcmp(p, "[ExclusionList]") == 0)
621 type = EXCLUSION_LIST;
622 else if (strcmp(p, "[ExclusionException]") == 0)
623 type = EXCLUSION_EXCEPTION;
624 else if (strcmp(p, "[CompressionExclusionList]") == 0)
625 type = COMPRESSION_EXCLUSION_LIST;
626 else if (strcmp(p, "[AlignmentList]") == 0)
627 type = ALIGNMENT_LIST;
630 DEBUG("Adding pattern \"%s\" to exclusion list", p);
631 ret = pattern_list_add_pattern(&config->exclusion_list, p);
633 case EXCLUSION_EXCEPTION:
634 DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
635 ret = pattern_list_add_pattern(&config->exclusion_exception, p);
637 case COMPRESSION_EXCLUSION_LIST:
638 DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
639 ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
642 DEBUG("Adding pattern \"%s\" to alignment list", p);
643 ret = pattern_list_add_pattern(&config->alignment_list, p);
646 ERROR("Line %lu of capture configuration is not "
647 "in a block (such as [ExclusionList])",
649 ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
657 destroy_capture_config(config);
661 static bool match_pattern(const char *path, const char *path_basename,
662 const struct pattern_list *list)
664 for (size_t i = 0; i < list->num_pats; i++) {
665 const char *pat = list->pats[i];
670 string = path_basename;
671 if (fnmatch(pat, string, FNM_PATHNAME) == 0) {
672 DEBUG("`%s' matches the pattern \"%s\"",
680 static void print_pattern_list(const struct pattern_list *list)
682 for (size_t i = 0; i < list->num_pats; i++)
683 printf(" %s\n", list->pats[i]);
686 static void print_capture_config(const struct capture_config *config)
688 if (config->exclusion_list.num_pats) {
689 puts("Files or folders excluded from image capture:");
690 print_pattern_list(&config->exclusion_list);
695 bool exclude_path(const char *path, const struct capture_config *config,
698 const char *basename = path_basename(path);
699 if (exclude_prefix) {
700 wimlib_assert(strlen(path) >= config->prefix_len);
701 if (memcmp(config->prefix, path, config->prefix_len) == 0
702 && path[config->prefix_len] == '/')
703 path += config->prefix_len;
705 return match_pattern(path, basename, &config->exclusion_list) &&
706 !match_pattern(path, basename, &config->exclusion_exception);
712 int do_add_image(WIMStruct *w, const char *dir, const char *name,
713 const char *description, const char *flags_element,
714 const char *config_str, size_t config_len,
716 int (*capture_tree)(struct dentry **, const char *,
717 struct lookup_table *,
718 struct wim_security_data *,
719 const struct capture_config *,
723 struct dentry *root_dentry = NULL;
724 struct image_metadata *imd;
725 struct wim_security_data *sd;
726 struct capture_config config;
729 DEBUG("Adding dentry tree from dir `%s'.", dir);
731 if (!name || !*name) {
732 ERROR("Must specify a non-empty string for the image name");
733 return WIMLIB_ERR_INVALID_PARAM;
736 ERROR("Must specify the name of a directory");
737 return WIMLIB_ERR_INVALID_PARAM;
740 if (wimlib_image_name_in_use(w, name)) {
741 ERROR("There is already an image named \"%s\" in `%s'",
743 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
746 DEBUG("Initializing capture configuration");
748 DEBUG("Using default capture configuration");
749 config_str = default_config;
750 config_len = strlen(default_config);
752 ret = init_capture_config(config_str, config_len, dir, &config);
755 print_capture_config(&config);
757 DEBUG("Allocating security data");
759 sd = CALLOC(1, sizeof(struct wim_security_data));
761 goto out_destroy_config;
762 sd->total_length = 8;
765 DEBUG("Building dentry tree.");
766 ret = (*capture_tree)(&root_dentry, dir, w->lookup_table, sd,
767 &config, flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
769 destroy_capture_config(&config);
772 ERROR("Failed to build dentry tree for `%s'", dir);
773 goto out_free_dentry_tree;
776 DEBUG("Calculating full paths of dentries.");
777 ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
779 goto out_free_dentry_tree;
781 ret = add_new_dentry_tree(w, root_dentry, sd);
783 goto out_free_dentry_tree;
785 DEBUG("Inserting dentries into hard link group table");
786 ret = for_dentry_in_tree(root_dentry, link_group_table_insert,
787 w->image_metadata[w->hdr.image_count - 1].lgt);
789 goto out_destroy_imd;
790 DEBUG("Assigning hard link groups");
791 assign_link_groups(w->image_metadata[w->hdr.image_count - 1].lgt);
793 if (flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
794 wimlib_set_boot_idx(w, w->hdr.image_count);
796 ret = xml_add_image(w, root_dentry, name, description, flags_element);
798 goto out_destroy_imd;
802 destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
804 w->hdr.image_count--;
806 out_free_dentry_tree:
807 free_dentry_tree(root_dentry, w->lookup_table);
809 free_security_data(sd);
811 destroy_capture_config(&config);
816 * Adds an image to a WIM file from a directory tree on disk.
818 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *dir,
819 const char *name, const char *description,
820 const char *flags_element,
821 const char *config_str,
822 size_t config_len, int flags)
824 return do_add_image(w, dir, name, description, flags_element,
825 config_str, config_len, flags,
826 build_dentry_tree, NULL);