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