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