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