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