]> wimlib.net Git - wimlib/blob - src/modify.c
split WIM apply, doc updates
[wimlib] / src / modify.c
1 /*
2  * modify.c
3  *
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.
8  */
9
10 /*
11  * Copyright (C) 2012 Eric Biggers
12  *
13  * This file is part of wimlib, a library for working with WIM files.
14  *
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)
18  * any later version.
19  *
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
23  * details.
24  *
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/.
27  */
28
29 #include "wimlib_internal.h"
30 #include "util.h"
31 #include "sha1.h"
32 #include "dentry.h"
33 #include "xml.h"
34 #include "lookup_table.h"
35 #include <sys/stat.h>
36 #include <dirent.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <fnmatch.h>
40 #include <ctype.h>
41 #include <unistd.h>
42
43 /** Private flag: Used to mark that we currently adding the root directory of
44  * the WIM image. */
45 #define WIMLIB_ADD_IMAGE_FLAG_ROOT 0x80000000
46
47 void destroy_image_metadata(struct image_metadata *imd,struct lookup_table *lt)
48 {
49         free_dentry_tree(imd->root_dentry, lt);
50         free_security_data(imd->security_data);
51         free_link_group_table(imd->lgt);
52
53         /* Get rid of the lookup table entry for this image's metadata resource
54          * */
55         if (lt)
56                 lookup_table_remove(lt, imd->metadata_lte);
57 }
58
59 /* 
60  * Recursively builds a dentry tree from a directory tree on disk, outside the
61  * WIM file.
62  *
63  * @root:  A dentry that has already been created for the root of the dentry
64  *         tree.
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.
70  *
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.
76  */
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,
81                              int add_flags,
82                              void *extra_arg)
83 {
84         struct stat root_stbuf;
85         int ret = 0;
86         int (*stat_fn)(const char *restrict, struct stat *restrict);
87         struct dentry *root;
88         const char *filename;
89
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",
93                                root_disk_path);
94                 *root_ret = NULL;
95                 return 0;
96         }
97
98
99         if (add_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
100                 stat_fn = stat;
101         else
102                 stat_fn = lstat;
103
104         if (add_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
105                 printf("Scanning `%s'\n", root_disk_path);
106
107
108         ret = (*stat_fn)(root_disk_path, &root_stbuf);
109         if (ret != 0) {
110                 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
111                 return WIMLIB_ERR_STAT;
112         }
113
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;
118         }
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.",
122                       root_disk_path);
123                 return WIMLIB_ERR_SPECIAL_FILE;
124         }
125
126         if (add_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT)
127                 filename = "";
128         else
129                 filename = path_basename(root_disk_path);
130
131         root = new_dentry(filename);
132         if (!root)
133                 return WIMLIB_ERR_NOMEM;
134
135         stbuf_to_dentry(&root_stbuf, root);
136         add_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
137         root->resolved = true;
138
139         if (dentry_is_directory(root)) {
140                 /* Open the directory on disk */
141                 DIR *dir;
142                 struct dirent *p;
143                 struct dentry *child;
144
145                 dir = opendir(root_disk_path);
146                 if (!dir) {
147                         ERROR_WITH_ERRNO("Failed to open the directory `%s'",
148                                          root_disk_path);
149                         return WIMLIB_ERR_OPEN;
150                 }
151
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);
156                 name[len] = '/';
157
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')))
163                                         continue;
164                         strcpy(name + len + 1, p->d_name);
165                         ret = build_dentry_tree(&child, name, lookup_table,
166                                                 sd, config,
167                                                 add_flags, extra_arg);
168                         if (ret != 0)
169                                 break;
170                         if (child)
171                                 link_dentry(child, root);
172                 }
173                 closedir(dir);
174         } else if (dentry_is_symlink(root)) {
175                 /* Archiving a symbolic link */
176                 char deref_name_buf[4096];
177                 ssize_t deref_name_len;
178                 
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;
185                 }
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,
189                                          lookup_table, NULL);
190         } else {
191                 /* Regular file */
192                 struct lookup_table_entry *lte;
193                 u8 hash[SHA1_HASH_SIZE];
194
195                 /* Empty files do not have to have a lookup table entry. */
196                 if (root_stbuf.st_size == 0)
197                         goto out;
198
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.
202                  * */
203                 ret = sha1sum(root_disk_path, hash);
204                 if (ret != 0)
205                         return ret;
206
207                 lte = __lookup_resource(lookup_table, hash);
208                 if (lte) {
209                         lte->refcnt++;
210                         DEBUG("Add lte reference %u for `%s'", lte->refcnt,
211                               root_disk_path);
212                 } else {
213                         char *file_on_disk = STRDUP(root_disk_path);
214                         if (!file_on_disk) {
215                                 ERROR("Failed to allocate memory for file path");
216                                 return WIMLIB_ERR_NOMEM;
217                         }
218                         lte = new_lookup_table_entry();
219                         if (!lte) {
220                                 FREE(file_on_disk);
221                                 return WIMLIB_ERR_NOMEM;
222                         }
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);
229                 }
230                 root->lte = lte;
231         }
232 out:
233         *root_ret = root;
234         return ret;
235 }
236
237 struct wim_pair {
238         WIMStruct *src_wim;
239         WIMStruct *dest_wim;
240 };
241
242 /* 
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.
249  */
250 static int add_lte_to_dest_wim(struct dentry *dentry, void *arg)
251 {
252         WIMStruct *src_wim, *dest_wim;
253
254         src_wim = ((struct wim_pair*)arg)->src_wim;
255         dest_wim = ((struct wim_pair*)arg)->dest_wim;
256
257         wimlib_assert(!dentry->resolved);
258
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);
263                 if (!src_lte)
264                         continue;
265                 dest_lte = dentry_stream_lte_unresolved(dentry, i,
266                                                         dest_wim->lookup_table);
267                 if (dest_lte) {
268                         dest_lte->refcnt++;
269                 } else {
270                         dest_lte = new_lookup_table_entry();
271                         if (!dest_lte)
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);
281                 }
282         }
283         return 0;
284 }
285
286 /*
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. 
290  *
291  * Does not update the XML data.
292  *
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.
296  */
297 static int add_new_dentry_tree(WIMStruct *w, struct dentry *root_dentry,
298                                struct wim_security_data *sd)
299 {
300         struct lookup_table_entry *metadata_lte;
301         struct image_metadata *imd;
302         struct image_metadata *new_imd;
303         struct link_group_table *lgt;
304
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));
308
309         if (!imd) {
310                 ERROR("Failed to allocate memory for new image metadata array");
311                 return WIMLIB_ERR_NOMEM;
312         }
313
314         memcpy(imd, w->image_metadata, 
315                w->hdr.image_count * sizeof(struct image_metadata));
316         
317         metadata_lte = new_lookup_table_entry();
318         if (!metadata_lte)
319                 goto out_free_imd;
320
321         lgt = new_link_group_table(9001);
322         if (!lgt)
323                 goto out_free_metadata_lte;
324
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);
328
329         new_imd = &imd[w->hdr.image_count];
330
331         new_imd->root_dentry    = root_dentry;
332         new_imd->metadata_lte   = metadata_lte;
333         new_imd->security_data  = sd;
334         new_imd->lgt            = lgt;
335         new_imd->modified       = true;
336
337         FREE(w->image_metadata);
338         w->image_metadata       = imd;
339         w->hdr.image_count++;
340
341         /* Change the current image to the new one. */
342         return wimlib_select_image(w, w->hdr.image_count);
343 out_free_metadata_lte:
344         FREE(metadata_lte);
345 out_free_imd:
346         FREE(imd);
347         return WIMLIB_ERR_NOMEM;
348
349 }
350
351 /*
352  * Copies an image, or all the images, from a WIM file, into another WIM file.
353  */
354 WIMLIBAPI int wimlib_export_image(WIMStruct *src_wim, 
355                                   int src_image, 
356                                   WIMStruct *dest_wim, 
357                                   const char *dest_name, 
358                                   const char *dest_description, 
359                                   int flags)
360 {
361         int i;
362         int ret;
363         struct dentry *root;
364         struct wim_pair wims;
365         struct wim_security_data *sd;
366
367         if (!src_wim || !dest_wim)
368                 return WIMLIB_ERR_INVALID_PARAM;
369
370         if (src_wim->hdr.total_parts != 1 || src_wim->hdr.total_parts != 1) {
371                 ERROR("Exporting an image to or from a split WIM is "
372                       "unsupported");
373                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
374         }
375
376         if (src_image == WIM_ALL_IMAGES) {
377                 if (src_wim->hdr.image_count > 1) {
378
379                         /* multi-image export. */
380
381                         if ((flags & WIMLIB_EXPORT_FLAG_BOOT) && 
382                               (src_wim->hdr.boot_idx == 0))
383                         {
384                                 /* Specifying the boot flag on a multi-image
385                                  * source WIM makes the boot index default to
386                                  * the bootable image in the source WIM.  It is
387                                  * an error if there is no such bootable image.
388                                  * */
389                                 ERROR("Cannot specify `boot' flag when "
390                                       "exporting multiple images from a WIM "
391                                       "with no bootable images");
392                                 return WIMLIB_ERR_INVALID_PARAM;
393                         }
394                         if (dest_name || dest_description) {
395                                 ERROR("Image name or image description was "
396                                       "specified, but we are exporting "
397                                       "multiple images");
398                                 return WIMLIB_ERR_INVALID_PARAM;
399                         }
400                         for (i = 1; i <= src_wim->hdr.image_count; i++) {
401                                 int export_flags = flags;
402
403                                 if (i != src_wim->hdr.boot_idx)
404                                         export_flags &= ~WIMLIB_EXPORT_FLAG_BOOT;
405
406                                 ret = wimlib_export_image(src_wim, i, dest_wim, 
407                                                           NULL,
408                                                           dest_description,
409                                                           export_flags);
410                                 if (ret != 0)
411                                         return ret;
412                         }
413                         return 0;
414                 } else {
415                         src_image = 1; 
416                 }
417         }
418
419         ret = wimlib_select_image(src_wim, src_image);
420         if (ret != 0) {
421                 ERROR("Could not select image %d from the WIM `%s' "
422                       "to export it", src_image, src_wim->filename);
423                 return ret;
424         }
425
426         if (!dest_name) {
427                 dest_name = wimlib_get_image_name(src_wim, src_image);
428                 DEBUG("Using name `%s' for source image %d",
429                       dest_name, src_image);
430         }
431
432         DEBUG("Exporting image %d from `%s'", src_image, src_wim->filename);
433
434         if (wimlib_image_name_in_use(dest_wim, dest_name)) {
435                 ERROR("There is already an image named `%s' in the "
436                       "destination WIM", dest_name);
437                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
438         }
439
440
441         /* Cleaning up here on failure would be hard.  For example, we could
442          * fail to allocate memory in add_lte_to_dest_wim(),
443          * leaving the lookup table entries in the destination WIM in an
444          * inconsistent state.  Until these issues can be resolved,
445          * wimlib_export_image() is documented as leaving dest_wim is an
446          * indeterminate state.  */
447         root = wim_root_dentry(src_wim);
448         sd = wim_security_data(src_wim);
449         for_dentry_in_tree(root, increment_dentry_refcnt, NULL);
450         wims.src_wim = src_wim;
451         wims.dest_wim = dest_wim;
452         ret = for_dentry_in_tree(root, add_lte_to_dest_wim, &wims);
453         if (ret != 0)
454                 return ret;
455         ret = add_new_dentry_tree(dest_wim, root, sd);
456         if (ret != 0)
457                 return ret;
458         sd->refcnt++;
459
460         if (flags & WIMLIB_EXPORT_FLAG_BOOT) {
461                 DEBUG("Setting boot_idx to %d", dest_wim->hdr.image_count);
462                 dest_wim->hdr.boot_idx = dest_wim->hdr.image_count;
463         }
464
465         return xml_export_image(src_wim->wim_info, src_image, &dest_wim->wim_info,
466                                 dest_name, dest_description);
467 }
468
469 /* 
470  * Deletes an image from the WIM. 
471  */
472 WIMLIBAPI int wimlib_delete_image(WIMStruct *w, int image)
473 {
474         int num_images;
475         int i;
476         int ret;
477
478         if (w->hdr.total_parts != 1) {
479                 ERROR("Deleting an image from a split WIM is not supported.");
480                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
481         }
482
483         if (image == WIM_ALL_IMAGES) {
484                 num_images = w->hdr.image_count;
485                 for (i = 1; i <= num_images; i++) {
486                         /* Always delete the first image, since by the end
487                          * there won't be any more than that!  */
488                         ret = wimlib_delete_image(w, 1);
489                         if (ret != 0)
490                                 return ret;
491                 }
492                 return 0;
493         }
494
495         DEBUG("Deleting image %d", image);
496
497         /* Even if the dentry tree is not allocated, we must select it (and
498          * therefore allocate it) so that we can decrement the reference counts
499          * in the lookup table.  */
500         ret = wimlib_select_image(w, image);
501         if (ret != 0)
502                 return ret;
503
504         /* Free the dentry tree, any lookup table entries that have their
505          * refcnt decremented to 0, and the security data. */
506         destroy_image_metadata(wim_get_current_image_metadata(w),
507                                w->lookup_table);
508
509         /* Get rid of the empty slot in the image metadata array. */
510         memmove(&w->image_metadata[image - 1], &w->image_metadata[image],
511                 (w->hdr.image_count - image) * sizeof(struct image_metadata));
512
513         /* Decrement the image count. */
514         if (--w->hdr.image_count == 0) {
515                 FREE(w->image_metadata);
516                 w->image_metadata = NULL;
517         }
518
519         /* Fix the boot index. */
520         if (w->hdr.boot_idx == image)
521                 w->hdr.boot_idx = 0;
522         else if (w->hdr.boot_idx > image)
523                 w->hdr.boot_idx--;
524
525         w->current_image = WIM_NO_IMAGE;
526
527         /* Remove the image from the XML information. */
528         xml_delete_image(&w->wim_info, image);
529         return 0;
530 }
531
532 enum pattern_type {
533         NONE = 0,
534         EXCLUSION_LIST,
535         EXCLUSION_EXCEPTION,
536         COMPRESSION_EXCLUSION_LIST,
537         ALIGNMENT_LIST,
538 };
539
540 /* Default capture configuration file when none is specified. */
541 static const char *default_config =
542 "[ExclusionList]\n"
543 "\\$ntfs.log\n"
544 "\\hiberfil.sys\n"
545 "\\pagefile.sys\n"
546 "\\System Volume Information\n"
547 "\\RECYCLER\n"
548 "\\Windows\\CSC\n"
549 "\n"
550 "[CompressionExclusionList]\n"
551 "*.mp3\n"
552 "*.zip\n"
553 "*.cab\n"
554 "\\WINDOWS\\inf\\*.pnf\n";
555
556 static void destroy_pattern_list(struct pattern_list *list)
557 {
558         FREE(list->pats);
559 }
560
561 static void destroy_capture_config(struct capture_config *config)
562 {
563         destroy_pattern_list(&config->exclusion_list);
564         destroy_pattern_list(&config->exclusion_exception);
565         destroy_pattern_list(&config->compression_exclusion_list);
566         destroy_pattern_list(&config->alignment_list);
567         FREE(config->config_str);
568         FREE(config->prefix);
569         memset(config, 0, sizeof(*config));
570 }
571
572 static int pattern_list_add_pattern(struct pattern_list *list,
573                                     const char *pattern)
574 {
575         const char **pats;
576         if (list->num_pats >= list->num_allocated_pats) {
577                 pats = REALLOC(list->pats,
578                                sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
579                 if (!pats)
580                         return WIMLIB_ERR_NOMEM;
581                 list->num_allocated_pats += 8;
582                 list->pats = pats;
583         }
584         list->pats[list->num_pats++] = pattern;
585         return 0;
586 }
587
588 /* Parses the contents of the image capture configuration file and fills in a
589  * `struct capture_config'. */
590 static int init_capture_config(const char *_config_str, size_t config_len,
591                                const char *_prefix, struct capture_config *config)
592 {
593         char *config_str;
594         char *prefix;
595         char *p;
596         char *eol;
597         char *next_p;
598         size_t bytes_remaining;
599         enum pattern_type type = NONE;
600         int ret;
601         unsigned long line_no = 0;
602
603         DEBUG("config_len = %zu", config_len);
604         bytes_remaining = config_len;
605         memset(config, 0, sizeof(*config));
606         config_str = MALLOC(config_len);
607         if (!config_str) {
608                 ERROR("Could not duplicate capture config string");
609                 return WIMLIB_ERR_NOMEM;
610         }
611         prefix = STRDUP(_prefix);
612         if (!prefix) {
613                 FREE(config_str);
614                 return WIMLIB_ERR_NOMEM;
615         }
616         
617         memcpy(config_str, _config_str, config_len);
618         next_p = config_str;
619         config->config_str = config_str;
620         config->prefix = prefix;
621         config->prefix_len = strlen(prefix);
622         while (bytes_remaining) {
623                 line_no++;
624                 p = next_p;
625                 eol = memchr(p, '\n', bytes_remaining);
626                 if (!eol) {
627                         ERROR("Expected end-of-line in capture config file on "
628                               "line %lu", line_no);
629                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
630                         goto out_destroy;
631                 }
632                 
633                 next_p = eol + 1;
634                 bytes_remaining -= (eol - p) + 1;
635                 if (eol == p)
636                         continue;
637
638                 if (*(eol - 1) == '\r')
639                         eol--;
640                 *eol = '\0';
641
642                 /* Translate backslash to forward slash */
643                 for (char *pp = p; pp != eol; pp++)
644                         if (*pp == '\\')
645                                 *pp = '/';
646
647                 /* Remove drive letter */
648                 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
649                         p += 2;
650
651                 ret = 0;
652                 if (strcmp(p, "[ExclusionList]") == 0)
653                         type = EXCLUSION_LIST;
654                 else if (strcmp(p, "[ExclusionException]") == 0)
655                         type = EXCLUSION_EXCEPTION;
656                 else if (strcmp(p, "[CompressionExclusionList]") == 0)
657                         type = COMPRESSION_EXCLUSION_LIST;
658                 else if (strcmp(p, "[AlignmentList]") == 0)
659                         type = ALIGNMENT_LIST;
660                 else if (p[0] == '[' && strrchr(p, ']')) {
661                         ERROR("Unknown capture configuration section `%s'", p);
662                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
663                         goto out_destroy;
664                 } else switch (type) {
665                 case EXCLUSION_LIST:
666                         DEBUG("Adding pattern \"%s\" to exclusion list", p);
667                         ret = pattern_list_add_pattern(&config->exclusion_list, p);
668                         break;
669                 case EXCLUSION_EXCEPTION:
670                         DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
671                         ret = pattern_list_add_pattern(&config->exclusion_exception, p);
672                         break;
673                 case COMPRESSION_EXCLUSION_LIST:
674                         DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
675                         ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
676                         break;
677                 case ALIGNMENT_LIST:
678                         DEBUG("Adding pattern \"%s\" to alignment list", p);
679                         ret = pattern_list_add_pattern(&config->alignment_list, p);
680                         break;
681                 default:
682                         ERROR("Line %lu of capture configuration is not "
683                               "in a block (such as [ExclusionList])",
684                               line_no);
685                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
686                         goto out_destroy;
687                 }
688                 if (ret != 0)
689                         goto out_destroy;
690         }
691         return 0;
692 out_destroy:
693         destroy_capture_config(config);
694         return ret;
695 }
696
697 static bool match_pattern(const char *path, const char *path_basename,
698                           const struct pattern_list *list)
699 {
700         for (size_t i = 0; i < list->num_pats; i++) {
701                 const char *pat = list->pats[i];
702                 const char *string;
703                 if (pat[0] == '/')
704                         /* Absolute path from root of capture */
705                         string = path;
706                 else {
707                         if (strchr(pat, '/'))
708                                 /* Relative path from root of capture */
709                                 string = path + 1;
710                         else
711                                 /* A file name pattern */
712                                 string = path_basename;
713                 }
714                 if (fnmatch(pat, string, FNM_PATHNAME
715                         #ifdef FNM_CASEFOLD
716                                         | FNM_CASEFOLD
717                         #endif
718                         ) == 0)
719                 {
720                         DEBUG("`%s' matches the pattern \"%s\"",
721                               string, pat);
722                         return true;
723                 }
724         }
725         return false;
726 }
727
728 static void print_pattern_list(const struct pattern_list *list)
729 {
730         for (size_t i = 0; i < list->num_pats; i++)
731                 printf("    %s\n", list->pats[i]);
732 }
733
734 static void print_capture_config(const struct capture_config *config)
735 {
736         if (config->exclusion_list.num_pats) {
737                 puts("Files or folders excluded from image capture:");
738                 print_pattern_list(&config->exclusion_list);
739                 putchar('\n');
740         }
741 }
742
743 /* Return true if the image capture configuration file indicates we should
744  * exclude the filename @path from capture.
745  *
746  * If @exclude_prefix is %true, the part of the path up and including the name
747  * of the directory being captured is not included in the path for matching
748  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
749  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
750  * directory.
751  */
752 bool exclude_path(const char *path, const struct capture_config *config,
753                   bool exclude_prefix)
754 {
755         const char *basename = path_basename(path);
756         if (exclude_prefix) {
757                 wimlib_assert(strlen(path) >= config->prefix_len);
758                 if (memcmp(config->prefix, path, config->prefix_len) == 0
759                      && path[config->prefix_len] == '/')
760                         path += config->prefix_len;
761         }
762         return match_pattern(path, basename, &config->exclusion_list) && 
763                 !match_pattern(path, basename, &config->exclusion_exception);
764
765 }
766
767
768
769 /*
770  * Adds an image to the WIM, delegating the capture of the dentry tree and
771  * security data to the function @capture_tree passed as a parameter.
772  * Currently, @capture_tree may be build_dentry_tree() for capturing a "regular"
773  * directory tree on disk, or build_dentry_tree_ntfs() for capturing a WIM image
774  * directory from a NTFS volume using libntfs-3g.
775  *
776  * The @capture_tree function is also expected to create lookup table entries
777  * for all the file streams it captures and insert them into @lookup_table,
778  * being careful to look for identical entries that already exist and simply
779  * increment the reference count for them rather than duplicating the entry.
780  */
781 int do_add_image(WIMStruct *w, const char *dir, const char *name,
782                  const char *config_str, size_t config_len,
783                  int flags,
784                  int (*capture_tree)(struct dentry **, const char *,
785                                      struct lookup_table *, 
786                                      struct wim_security_data *,
787                                      const struct capture_config *,
788                                      int, void *),
789                  void *extra_arg)
790 {
791         struct dentry *root_dentry = NULL;
792         struct wim_security_data *sd;
793         struct capture_config config;
794         struct link_group_table *lgt;
795         int ret;
796
797         DEBUG("Adding dentry tree from directory or NTFS volume `%s'.", dir);
798
799         if (!name || !*name) {
800                 ERROR("Must specify a non-empty string for the image name");
801                 return WIMLIB_ERR_INVALID_PARAM;
802         }
803         if (!dir) {
804                 ERROR("Must specify the name of a directory or NTFS volume");
805                 return WIMLIB_ERR_INVALID_PARAM;
806         }
807
808         if (w->hdr.total_parts != 1) {
809                 ERROR("Cannot add an image to a split WIM");
810                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
811         }
812
813         if (wimlib_image_name_in_use(w, name)) {
814                 ERROR("There is already an image named \"%s\" in `%s'",
815                       name, w->filename);
816                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
817         }
818
819         DEBUG("Initializing capture configuration");
820         if (!config_str) {
821                 DEBUG("Using default capture configuration");
822                 config_str = default_config;
823                 config_len = strlen(default_config);
824         }
825         ret = init_capture_config(config_str, config_len, dir, &config);
826         if (ret != 0)
827                 return ret;
828         print_capture_config(&config);
829
830         DEBUG("Allocating security data");
831
832         sd = CALLOC(1, sizeof(struct wim_security_data));
833         if (!sd)
834                 goto out_destroy_config;
835         sd->total_length = 8;
836         sd->refcnt = 1;
837
838         DEBUG("Building dentry tree.");
839         ret = (*capture_tree)(&root_dentry, dir, w->lookup_table, sd,
840                               &config, flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
841                               extra_arg);
842         destroy_capture_config(&config);
843
844         if (ret != 0) {
845                 ERROR("Failed to build dentry tree for `%s'", dir);
846                 goto out_free_dentry_tree;
847         }
848
849         DEBUG("Calculating full paths of dentries.");
850         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
851         if (ret != 0)
852                 goto out_free_dentry_tree;
853
854         ret = add_new_dentry_tree(w, root_dentry, sd);
855         if (ret != 0)
856                 goto out_free_dentry_tree;
857
858         lgt = w->image_metadata[w->hdr.image_count - 1].lgt;
859         DEBUG("Inserting dentries into hard link group table");
860         ret = for_dentry_in_tree(root_dentry, link_group_table_insert, lgt);
861                                  
862         if (ret != 0)
863                 goto out_destroy_imd;
864
865         DEBUG("Cleanup up the hard link groups");
866         ret = fix_link_groups(lgt);
867         if (ret != 0)
868                 goto out_destroy_imd;
869
870         DEBUG("Assigning hard link group IDs");
871         assign_link_group_ids(w->image_metadata[w->hdr.image_count - 1].lgt);
872
873         if (flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
874                 wimlib_set_boot_idx(w, w->hdr.image_count);
875
876         ret = xml_add_image(w, root_dentry, name);
877         if (ret != 0)
878                 goto out_destroy_imd;
879
880         return 0;
881 out_destroy_imd:
882         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
883                                w->lookup_table);
884         w->hdr.image_count--;
885         return ret;
886 out_free_dentry_tree:
887         free_dentry_tree(root_dentry, w->lookup_table);
888         free_security_data(sd);
889 out_destroy_config:
890         destroy_capture_config(&config);
891         return ret;
892 }
893
894 /*
895  * Adds an image to a WIM file from a directory tree on disk.
896  */
897 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *dir, 
898                                const char *name, const char *config_str,
899                                size_t config_len, int flags)
900 {
901         return do_add_image(w, dir, name, config_str, config_len, flags,
902                             build_dentry_tree, NULL);
903 }