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