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