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