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