Fix various issues
[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 Lesser General Public License as published by the Free
17  * Software Foundation; either version 2.1 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 Lesser General Public License for more
23  * details.
24  *
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/.
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. */
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_image == WIM_ALL_IMAGES) {
368                 if (src_wim->hdr.image_count > 1) {
369
370                         /* multi-image export. */
371
372                         if ((flags & WIMLIB_EXPORT_FLAG_BOOT) && 
373                               (src_wim->hdr.boot_idx == 0))
374                         {
375                                 /* Specifying the boot flag on a multi-image
376                                  * source WIM makes the boot index default to
377                                  * the bootable image in the source WIM.  It is
378                                  * an error if there is no such bootable image.
379                                  * */
380                                 ERROR("Cannot specify `boot' flag when "
381                                       "exporting multiple images from a WIM "
382                                       "with no bootable images");
383                                 return WIMLIB_ERR_INVALID_PARAM;
384                         }
385                         if (dest_name || dest_description) {
386                                 ERROR("Image name or image description was "
387                                       "specified, but we are exporting "
388                                       "multiple images");
389                                 return WIMLIB_ERR_INVALID_PARAM;
390                         }
391                         for (i = 1; i <= src_wim->hdr.image_count; i++) {
392                                 int export_flags = flags;
393
394                                 if (i != src_wim->hdr.boot_idx)
395                                         export_flags &= ~WIMLIB_EXPORT_FLAG_BOOT;
396
397                                 ret = wimlib_export_image(src_wim, i, dest_wim, 
398                                                           NULL,
399                                                           dest_description,
400                                                           export_flags);
401                                 if (ret != 0)
402                                         return ret;
403                         }
404                         return 0;
405                 } else {
406                         src_image = 1; 
407                 }
408         }
409
410         ret = wimlib_select_image(src_wim, src_image);
411         if (ret != 0) {
412                 ERROR("Could not select image %d from the WIM `%s' "
413                       "to export it", src_image, src_wim->filename);
414                 return ret;
415         }
416
417         if (!dest_name) {
418                 dest_name = wimlib_get_image_name(src_wim, src_image);
419                 DEBUG("Using name `%s' for source image %d",
420                       dest_name, src_image);
421         }
422
423         DEBUG("Exporting image %d from `%s'", src_image, src_wim->filename);
424
425         if (wimlib_image_name_in_use(dest_wim, dest_name)) {
426                 ERROR("There is already an image named `%s' in the "
427                       "destination WIM", dest_name);
428                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
429         }
430
431
432         /* Cleaning up here on failure would be hard.  For example, we could
433          * fail to allocate memory in add_lte_to_dest_wim(),
434          * leaving the lookup table entries in the destination WIM in an
435          * inconsistent state.  Until these issues can be resolved,
436          * wimlib_export_image() is documented as leaving dest_wim is an
437          * indeterminate state.  */
438         root = wim_root_dentry(src_wim);
439         sd = wim_security_data(src_wim);
440         for_dentry_in_tree(root, increment_dentry_refcnt, NULL);
441         wims.src_wim = src_wim;
442         wims.dest_wim = dest_wim;
443         ret = for_dentry_in_tree(root, add_lte_to_dest_wim, &wims);
444         if (ret != 0)
445                 return ret;
446         ret = add_new_dentry_tree(dest_wim, root, sd);
447         if (ret != 0)
448                 return ret;
449         sd->refcnt++;
450
451         if (flags & WIMLIB_EXPORT_FLAG_BOOT) {
452                 DEBUG("Setting boot_idx to %d", dest_wim->hdr.image_count);
453                 dest_wim->hdr.boot_idx = dest_wim->hdr.image_count;
454         }
455
456         return xml_export_image(src_wim->wim_info, src_image, &dest_wim->wim_info,
457                                 dest_name, dest_description);
458 }
459
460 /* 
461  * Deletes an image from the WIM. 
462  */
463 WIMLIBAPI int wimlib_delete_image(WIMStruct *w, int image)
464 {
465         int num_images;
466         int i;
467         int ret;
468
469         if (image == WIM_ALL_IMAGES) {
470                 num_images = w->hdr.image_count;
471                 for (i = 1; i <= num_images; i++) {
472                         /* Always delete the first image, since by the end
473                          * there won't be any more than that!  */
474                         ret = wimlib_delete_image(w, 1);
475                         if (ret != 0)
476                                 return ret;
477                 }
478                 return 0;
479         }
480
481         DEBUG("Deleting image %d", image);
482
483         /* Even if the dentry tree is not allocated, we must select it (and
484          * therefore allocate it) so that we can decrement the reference counts
485          * in the lookup table.  */
486         ret = wimlib_select_image(w, image);
487         if (ret != 0)
488                 return ret;
489
490         /* Free the dentry tree, any lookup table entries that have their
491          * refcnt decremented to 0, and the security data. */
492         destroy_image_metadata(wim_get_current_image_metadata(w),
493                                w->lookup_table);
494
495         /* Get rid of the empty slot in the image metadata array. */
496         memmove(&w->image_metadata[image - 1], &w->image_metadata[image],
497                 (w->hdr.image_count - image) * sizeof(struct image_metadata));
498
499         /* Decrement the image count. */
500         if (--w->hdr.image_count == 0) {
501                 FREE(w->image_metadata);
502                 w->image_metadata = NULL;
503         }
504
505         /* Fix the boot index. */
506         if (w->hdr.boot_idx == image)
507                 w->hdr.boot_idx = 0;
508         else if (w->hdr.boot_idx > image)
509                 w->hdr.boot_idx--;
510
511         w->current_image = WIM_NO_IMAGE;
512
513         /* Remove the image from the XML information. */
514         xml_delete_image(&w->wim_info, image);
515         return 0;
516 }
517
518 enum pattern_type {
519         NONE = 0,
520         EXCLUSION_LIST,
521         EXCLUSION_EXCEPTION,
522         COMPRESSION_EXCLUSION_LIST,
523         ALIGNMENT_LIST,
524 };
525
526 static const char *default_config =
527 "[ExclusionList]\n"
528 "\\$ntfs.log\n"
529 "\\hiberfil.sys\n"
530 "\\pagefile.sys\n"
531 "\\System Volume Information\n"
532 "\\RECYCLER\n"
533 "\\Windows\\CSC\n"
534 "\n"
535 "[CompressionExclusionList]\n"
536 "*.mp3\n"
537 "*.zip\n"
538 "*.cab\n"
539 "\\WINDOWS\\inf\\*.pnf\n";
540
541 static void destroy_pattern_list(struct pattern_list *list)
542 {
543         FREE(list->pats);
544 }
545
546 static void destroy_capture_config(struct capture_config *config)
547 {
548         destroy_pattern_list(&config->exclusion_list);
549         destroy_pattern_list(&config->exclusion_exception);
550         destroy_pattern_list(&config->compression_exclusion_list);
551         destroy_pattern_list(&config->alignment_list);
552         FREE(config->config_str);
553         FREE(config->prefix);
554         memset(config, 0, sizeof(*config));
555 }
556
557 static int pattern_list_add_pattern(struct pattern_list *list,
558                                     const char *pattern)
559 {
560         const char **pats;
561         if (list->num_pats >= list->num_allocated_pats) {
562                 pats = REALLOC(list->pats,
563                                sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
564                 if (!pats)
565                         return WIMLIB_ERR_NOMEM;
566                 list->num_allocated_pats += 8;
567                 list->pats = pats;
568         }
569         list->pats[list->num_pats++] = pattern;
570         return 0;
571 }
572
573 static int init_capture_config(const char *_config_str, size_t config_len,
574                                const char *_prefix, struct capture_config *config)
575 {
576         char *config_str;
577         char *prefix;
578         char *p;
579         char *eol;
580         char *next_p;
581         size_t bytes_remaining;
582         enum pattern_type type = NONE;
583         int ret;
584         unsigned long line_no = 0;
585
586         DEBUG("config_len = %zu", config_len);
587         bytes_remaining = config_len;
588         memset(config, 0, sizeof(*config));
589         config_str = MALLOC(config_len);
590         if (!config_str) {
591                 ERROR("Could not duplicate capture config string");
592                 return WIMLIB_ERR_NOMEM;
593         }
594         prefix = STRDUP(_prefix);
595         if (!prefix) {
596                 FREE(config_str);
597                 return WIMLIB_ERR_NOMEM;
598         }
599         
600         memcpy(config_str, _config_str, config_len);
601         next_p = config_str;
602         config->config_str = config_str;
603         config->prefix = prefix;
604         config->prefix_len = strlen(prefix);
605         while (bytes_remaining) {
606                 line_no++;
607                 p = next_p;
608                 eol = memchr(p, '\n', bytes_remaining);
609                 if (!eol) {
610                         ERROR("Expected end-of-line in capture config file on "
611                               "line %lu", line_no);
612                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
613                         goto out_destroy;
614                 }
615                 
616                 next_p = eol + 1;
617                 bytes_remaining -= (eol - p) + 1;
618                 if (eol == p)
619                         continue;
620
621                 if (*(eol - 1) == '\r')
622                         eol--;
623                 *eol = '\0';
624
625                 /* Translate backslash to forward slash */
626                 for (char *pp = p; pp != eol; pp++)
627                         if (*pp == '\\')
628                                 *pp = '/';
629
630                 /* Remove drive letter */
631                 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
632                         p += 2;
633
634                 ret = 0;
635                 if (strcmp(p, "[ExclusionList]") == 0)
636                         type = EXCLUSION_LIST;
637                 else if (strcmp(p, "[ExclusionException]") == 0)
638                         type = EXCLUSION_EXCEPTION;
639                 else if (strcmp(p, "[CompressionExclusionList]") == 0)
640                         type = COMPRESSION_EXCLUSION_LIST;
641                 else if (strcmp(p, "[AlignmentList]") == 0)
642                         type = ALIGNMENT_LIST;
643                 else if (p[0] == '[' && strrchr(p, ']')) {
644                         ERROR("Unknown capture configuration section `%s'", p);
645                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
646                         goto out_destroy;
647                 } else switch (type) {
648                 case EXCLUSION_LIST:
649                         DEBUG("Adding pattern \"%s\" to exclusion list", p);
650                         ret = pattern_list_add_pattern(&config->exclusion_list, p);
651                         break;
652                 case EXCLUSION_EXCEPTION:
653                         DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
654                         ret = pattern_list_add_pattern(&config->exclusion_exception, p);
655                         break;
656                 case COMPRESSION_EXCLUSION_LIST:
657                         DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
658                         ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
659                         break;
660                 case ALIGNMENT_LIST:
661                         DEBUG("Adding pattern \"%s\" to alignment list", p);
662                         ret = pattern_list_add_pattern(&config->alignment_list, p);
663                         break;
664                 default:
665                         ERROR("Line %lu of capture configuration is not "
666                               "in a block (such as [ExclusionList])",
667                               line_no);
668                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
669                         goto out_destroy;
670                 }
671                 if (ret != 0)
672                         goto out_destroy;
673         }
674         return 0;
675 out_destroy:
676         destroy_capture_config(config);
677         return ret;
678 }
679
680 static bool match_pattern(const char *path, const char *path_basename,
681                           const struct pattern_list *list)
682 {
683         for (size_t i = 0; i < list->num_pats; i++) {
684                 const char *pat = list->pats[i];
685                 const char *string;
686                 if (pat[0] == '/')
687                         /* Absolute path from root of capture */
688                         string = path;
689                 else {
690                         if (strchr(pat, '/'))
691                                 /* Relative path from root of capture */
692                                 string = path + 1;
693                         else
694                                 /* A file name pattern */
695                                 string = path_basename;
696                 }
697                 if (fnmatch(pat, string, FNM_PATHNAME
698                         #ifdef FNM_CASEFOLD
699                                         | FNM_CASEFOLD
700                         #endif
701                         ) == 0)
702                 {
703                         DEBUG("`%s' matches the pattern \"%s\"",
704                               string, pat);
705                         return true;
706                 }
707         }
708         return false;
709 }
710
711 static void print_pattern_list(const struct pattern_list *list)
712 {
713         for (size_t i = 0; i < list->num_pats; i++)
714                 printf("    %s\n", list->pats[i]);
715 }
716
717 static void print_capture_config(const struct capture_config *config)
718 {
719         if (config->exclusion_list.num_pats) {
720                 puts("Files or folders excluded from image capture:");
721                 print_pattern_list(&config->exclusion_list);
722                 putchar('\n');
723         }
724 }
725
726 bool exclude_path(const char *path, const struct capture_config *config,
727                   bool exclude_prefix)
728 {
729         const char *basename = path_basename(path);
730         if (exclude_prefix) {
731                 wimlib_assert(strlen(path) >= config->prefix_len);
732                 if (memcmp(config->prefix, path, config->prefix_len) == 0
733                      && path[config->prefix_len] == '/')
734                         path += config->prefix_len;
735         }
736         return match_pattern(path, basename, &config->exclusion_list) && 
737                 !match_pattern(path, basename, &config->exclusion_exception);
738
739 }
740
741
742
743 int do_add_image(WIMStruct *w, const char *dir, const char *name,
744                  const char *config_str, size_t config_len,
745                  int flags,
746                  int (*capture_tree)(struct dentry **, const char *,
747                                      struct lookup_table *, 
748                                      struct wim_security_data *,
749                                      const struct capture_config *,
750                                      int, void *),
751                  void *extra_arg)
752 {
753         struct dentry *root_dentry = NULL;
754         struct wim_security_data *sd;
755         struct capture_config config;
756         struct link_group_table *lgt;
757         int ret;
758
759         DEBUG("Adding dentry tree from dir `%s'.", dir);
760
761         if (!name || !*name) {
762                 ERROR("Must specify a non-empty string for the image name");
763                 return WIMLIB_ERR_INVALID_PARAM;
764         }
765         if (!dir) {
766                 ERROR("Must specify the name of a directory");
767                 return WIMLIB_ERR_INVALID_PARAM;
768         }
769
770         if (wimlib_image_name_in_use(w, name)) {
771                 ERROR("There is already an image named \"%s\" in `%s'",
772                       name, w->filename);
773                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
774         }
775
776         DEBUG("Initializing capture configuration");
777         if (!config_str) {
778                 DEBUG("Using default capture configuration");
779                 config_str = default_config;
780                 config_len = strlen(default_config);
781         }
782         ret = init_capture_config(config_str, config_len, dir, &config);
783         if (ret != 0)
784                 return ret;
785         print_capture_config(&config);
786
787         DEBUG("Allocating security data");
788
789         sd = CALLOC(1, sizeof(struct wim_security_data));
790         if (!sd)
791                 goto out_destroy_config;
792         sd->total_length = 8;
793         sd->refcnt = 1;
794
795         DEBUG("Building dentry tree.");
796         ret = (*capture_tree)(&root_dentry, dir, w->lookup_table, sd,
797                               &config, flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
798                               extra_arg);
799         destroy_capture_config(&config);
800
801         if (ret != 0) {
802                 ERROR("Failed to build dentry tree for `%s'", dir);
803                 goto out_free_dentry_tree;
804         }
805
806         DEBUG("Calculating full paths of dentries.");
807         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
808         if (ret != 0)
809                 goto out_free_dentry_tree;
810
811         ret = add_new_dentry_tree(w, root_dentry, sd);
812         if (ret != 0)
813                 goto out_free_dentry_tree;
814
815         lgt = w->image_metadata[w->hdr.image_count - 1].lgt;
816         DEBUG("Inserting dentries into hard link group table");
817         ret = for_dentry_in_tree(root_dentry, link_group_table_insert, lgt);
818                                  
819         if (ret != 0)
820                 goto out_destroy_imd;
821
822         DEBUG("Cleanup up the hard link groups");
823         ret = fix_link_groups(lgt);
824         if (ret != 0)
825                 goto out_destroy_imd;
826
827         DEBUG("Assigning hard link group IDs");
828         assign_link_group_ids(w->image_metadata[w->hdr.image_count - 1].lgt);
829
830         if (flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
831                 wimlib_set_boot_idx(w, w->hdr.image_count);
832
833         ret = xml_add_image(w, root_dentry, name);
834         if (ret != 0)
835                 goto out_destroy_imd;
836
837         return 0;
838 out_destroy_imd:
839         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
840                                w->lookup_table);
841         w->hdr.image_count--;
842         return ret;
843 out_free_dentry_tree:
844         free_dentry_tree(root_dentry, w->lookup_table);
845         free_security_data(sd);
846 out_destroy_config:
847         destroy_capture_config(&config);
848         return ret;
849 }
850
851 /*
852  * Adds an image to a WIM file from a directory tree on disk.
853  */
854 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *dir, 
855                                const char *name, const char *config_str,
856                                size_t config_len, int flags)
857 {
858         return do_add_image(w, dir, name, config_str, config_len, flags,
859                             build_dentry_tree, NULL);
860 }