]> wimlib.net Git - wimlib/blob - src/modify.c
a8ce13caabb08b8b31737f26387eacd7a46287db
[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 "timestamp.h"
36 #include <sys/stat.h>
37 #include <dirent.h>
38 #include <string.h>
39 #include <errno.h>
40 #include <fnmatch.h>
41 #include <ctype.h>
42 #include <unistd.h>
43
44 /** Private flag: Used to mark that we currently adding the root directory of
45  * the WIM image. */
46 #define WIMLIB_ADD_IMAGE_FLAG_ROOT 0x80000000
47
48 void destroy_image_metadata(struct image_metadata *imd,
49                             struct lookup_table *table)
50 {
51         free_dentry_tree(imd->root_dentry, table);
52         free_security_data(imd->security_data);
53
54         /* Get rid of the lookup table entry for this image's metadata resource
55          * */
56         if (table) {
57                 lookup_table_unlink(table, imd->metadata_lte);
58                 free_lookup_table_entry(imd->metadata_lte);
59         }
60 }
61
62 /*
63  * Recursively builds a dentry tree from a directory tree on disk, outside the
64  * WIM file.
65  *
66  * @root_ret:   Place to return a pointer to the root of the dentry tree.  Only
67  *              modified if successful.  NULL if the file or directory was
68  *              excluded from capture.
69  *
70  * @root_disk_path:  The path to the root of the directory tree on disk.
71  *
72  * @lookup_table: The lookup table for the WIM file.  For each file added to the
73  *              dentry tree being built, an entry is added to the lookup table,
74  *              unless an identical stream is already in the lookup table.
75  *              These lookup table entries that are added point to the path of
76  *              the file on disk.
77  *
78  * @sd:         Ignored.  (Security data only captured in NTFS mode.)
79  *
80  * @capture_config:
81  *              Configuration for files to be excluded from capture.
82  *
83  * @add_flags:  Bitwise or of WIMLIB_ADD_IMAGE_FLAG_*
84  *
85  * @extra_arg:  Ignored. (Only used in NTFS mode.)
86  *
87  * @return:     0 on success, nonzero on failure.  It is a failure if any of
88  *              the files cannot be `stat'ed, or if any of the needed
89  *              directories cannot be opened or read.  Failure to add the files
90  *              to the WIM may still occur later when trying to actually read
91  *              the on-disk files during a call to wimlib_write() or
92  *              wimlib_overwrite().
93  */
94 static int build_dentry_tree(struct dentry **root_ret,
95                              const char *root_disk_path,
96                              struct lookup_table *lookup_table,
97                              struct wim_security_data *sd,
98                              const struct capture_config *config,
99                              int add_flags,
100                              void *extra_arg)
101 {
102         struct stat root_stbuf;
103         int ret = 0;
104         int (*stat_fn)(const char *restrict, struct stat *restrict);
105         struct dentry *root;
106         const char *filename;
107         struct inode *inode;
108
109         if (exclude_path(root_disk_path, config, true)) {
110                 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
111                         ERROR("Cannot exclude the root directory from capture");
112                         return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
113                 }
114                 if (add_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
115                         printf("Excluding file `%s' from capture\n",
116                                root_disk_path);
117                 *root_ret = NULL;
118                 return 0;
119         }
120
121
122         if (add_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
123                 stat_fn = stat;
124         else
125                 stat_fn = lstat;
126
127         if (add_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
128                 printf("Scanning `%s'\n", root_disk_path);
129
130         ret = (*stat_fn)(root_disk_path, &root_stbuf);
131         if (ret != 0) {
132                 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
133                 return WIMLIB_ERR_STAT;
134         }
135
136         if ((add_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
137               !S_ISDIR(root_stbuf.st_mode)) {
138                 ERROR("`%s' is not a directory", root_disk_path);
139                 return WIMLIB_ERR_NOTDIR;
140         }
141         if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
142             && !S_ISLNK(root_stbuf.st_mode)) {
143                 ERROR("`%s' is not a regular file, directory, or symbolic link.",
144                       root_disk_path);
145                 return WIMLIB_ERR_SPECIAL_FILE;
146         }
147
148         if (add_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT)
149                 filename = "";
150         else
151                 filename = path_basename(root_disk_path);
152
153         root = new_dentry_with_timeless_inode(filename);
154         if (!root)
155                 return WIMLIB_ERR_NOMEM;
156
157         inode = root->d_inode;
158
159         inode->creation_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
160         inode->last_write_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
161         inode->last_access_time = timespec_to_wim_timestamp(&root_stbuf.st_atim);
162         if (sizeof(ino_t) >= 8)
163                 inode->ino = (u64)root_stbuf.st_ino;
164         else
165                 inode->ino = (u64)root_stbuf.st_ino |
166                                    ((u64)root_stbuf.st_dev << ((sizeof(ino_t) * 8) & 63));
167
168         add_flags &= ~WIMLIB_ADD_IMAGE_FLAG_ROOT;
169         inode->resolved = true;
170
171         if (S_ISREG(root_stbuf.st_mode)) { /* Archiving a regular file */
172
173                 struct lookup_table_entry *lte;
174                 u8 hash[SHA1_HASH_SIZE];
175
176                 inode->attributes = FILE_ATTRIBUTE_NORMAL;
177
178                 /* Empty files do not have to have a lookup table entry. */
179                 if (root_stbuf.st_size == 0)
180                         goto out;
181
182                 /* For each regular file, we must check to see if the file is in
183                  * the lookup table already; if it is, we increment its refcnt;
184                  * otherwise, we create a new lookup table entry and insert it.
185                  * */
186
187                 ret = sha1sum(root_disk_path, hash);
188                 if (ret != 0)
189                         goto out;
190
191                 lte = __lookup_resource(lookup_table, hash);
192                 if (lte) {
193                         lte->refcnt++;
194                         DEBUG("Add lte reference %u for `%s'", lte->refcnt,
195                               root_disk_path);
196                 } else {
197                         char *file_on_disk = STRDUP(root_disk_path);
198                         if (!file_on_disk) {
199                                 ERROR("Failed to allocate memory for file path");
200                                 ret = WIMLIB_ERR_NOMEM;
201                                 goto out;
202                         }
203                         lte = new_lookup_table_entry();
204                         if (!lte) {
205                                 FREE(file_on_disk);
206                                 ret = WIMLIB_ERR_NOMEM;
207                                 goto out;
208                         }
209                         lte->file_on_disk = file_on_disk;
210                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
211                         lte->resource_entry.original_size = root_stbuf.st_size;
212                         lte->resource_entry.size = root_stbuf.st_size;
213                         copy_hash(lte->hash, hash);
214                         lookup_table_insert(lookup_table, lte);
215                 }
216                 root->d_inode->lte = lte;
217         } else if (S_ISDIR(root_stbuf.st_mode)) { /* Archiving a directory */
218
219                 inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
220
221                 DIR *dir;
222                 struct dirent *p;
223                 struct dentry *child;
224
225                 dir = opendir(root_disk_path);
226                 if (!dir) {
227                         ERROR_WITH_ERRNO("Failed to open the directory `%s'",
228                                          root_disk_path);
229                         ret = WIMLIB_ERR_OPEN;
230                         goto out;
231                 }
232
233                 /* Buffer for names of files in directory. */
234                 size_t len = strlen(root_disk_path);
235                 char name[len + 1 + FILENAME_MAX + 1];
236                 memcpy(name, root_disk_path, len);
237                 name[len] = '/';
238
239                 /* Create a dentry for each entry in the directory on disk, and recurse
240                  * to any subdirectories. */
241                 while (1) {
242                         errno = 0;
243                         p = readdir(dir);
244                         if (p == NULL) {
245                                 if (errno) {
246                                         ret = WIMLIB_ERR_READ;
247                                         ERROR_WITH_ERRNO("Error reading the "
248                                                          "directory `%s'",
249                                                          root_disk_path);
250                                 }
251                                 break;
252                         }
253                         if (p->d_name[0] == '.' && (p->d_name[1] == '\0'
254                               || (p->d_name[1] == '.' && p->d_name[2] == '\0')))
255                                         continue;
256                         strcpy(name + len + 1, p->d_name);
257                         ret = build_dentry_tree(&child, name, lookup_table,
258                                                 NULL, config,
259                                                 add_flags, NULL);
260                         if (ret != 0)
261                                 break;
262                         if (child)
263                                 dentry_add_child(root, child);
264                 }
265                 closedir(dir);
266         } else { /* Archiving a symbolic link */
267                 inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
268                 inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
269
270                 /* The idea here is to call readlink() to get the UNIX target of
271                  * the symbolic link, then turn the target into a reparse point
272                  * data buffer that contains a relative or absolute symbolic
273                  * link (NOT a junction point or *full* path symbolic link with
274                  * drive letter).
275                  */
276
277                 char deref_name_buf[4096];
278                 ssize_t deref_name_len;
279
280                 deref_name_len = readlink(root_disk_path, deref_name_buf,
281                                           sizeof(deref_name_buf) - 1);
282                 if (deref_name_len >= 0) {
283                         deref_name_buf[deref_name_len] = '\0';
284                         DEBUG("Read symlink `%s'", deref_name_buf);
285                         ret = inode_set_symlink(root->d_inode, deref_name_buf,
286                                                 lookup_table, NULL);
287                         if (ret == 0) {
288                                 /*
289                                  * Unfortunately, Windows seems to have the
290                                  * concept of "file" symbolic links as being
291                                  * different from "directory" symbolic links...
292                                  * so FILE_ATTRIBUTE_DIRECTORY needs to be set
293                                  * on the symbolic link if the *target* of the
294                                  * symbolic link is a directory.
295                                  */
296                                 struct stat stbuf;
297                                 if (stat(root_disk_path, &stbuf) == 0 &&
298                                     S_ISDIR(stbuf.st_mode))
299                                 {
300                                         inode->attributes |= FILE_ATTRIBUTE_DIRECTORY;
301                                 }
302                         }
303                 } else {
304                         ERROR_WITH_ERRNO("Failed to read target of "
305                                          "symbolic link `%s'", root_disk_path);
306                         ret = WIMLIB_ERR_READLINK;
307                 }
308         }
309 out:
310         if (ret == 0)
311                 *root_ret = root;
312         else
313                 free_dentry_tree(root, lookup_table);
314         return ret;
315 }
316
317 struct wim_pair {
318         WIMStruct *src_wim;
319         WIMStruct *dest_wim;
320         struct list_head lte_list_head;
321 };
322
323 static int allocate_lte_if_needed(struct dentry *dentry, void *arg)
324 {
325         const WIMStruct *src_wim, *dest_wim;
326         struct list_head *lte_list_head;
327         struct inode *inode;
328
329         src_wim = ((struct wim_pair*)arg)->src_wim;
330         dest_wim = ((struct wim_pair*)arg)->dest_wim;
331         lte_list_head = &((struct wim_pair*)arg)->lte_list_head;
332         inode = dentry->d_inode;
333
334         wimlib_assert(!inode->resolved);
335
336         for (unsigned i = 0; i <= inode->num_ads; i++) {
337                 struct lookup_table_entry *src_lte, *dest_lte;
338                 src_lte = inode_stream_lte_unresolved(inode, i,
339                                                       src_wim->lookup_table);
340
341                 if (src_lte && ++src_lte->out_refcnt == 1) {
342                         dest_lte = inode_stream_lte_unresolved(inode, i,
343                                                                dest_wim->lookup_table);
344
345                         if (!dest_lte) {
346                                 dest_lte = clone_lookup_table_entry(src_lte);
347                                 if (!dest_lte)
348                                         return WIMLIB_ERR_NOMEM;
349                                 list_add_tail(&dest_lte->staging_list, lte_list_head);
350                         }
351                 }
352         }
353         return 0;
354 }
355
356 /*
357  * This function takes in a dentry that was previously located only in image(s)
358  * in @src_wim, but now is being added to @dest_wim.  For each stream associated
359  * with the dentry, if there is already a lookup table entry for that stream in
360  * the lookup table of the destination WIM file, its reference count is
361  * incrementej.  Otherwise, a new lookup table entry is created that points back
362  * to the stream in the source WIM file (through the @hash field combined with
363  * the @wim field of the lookup table entry.)
364  */
365 static int add_lte_to_dest_wim(struct dentry *dentry, void *arg)
366 {
367         WIMStruct *src_wim, *dest_wim;
368         struct inode *inode;
369
370         src_wim = ((struct wim_pair*)arg)->src_wim;
371         dest_wim = ((struct wim_pair*)arg)->dest_wim;
372         inode = dentry->d_inode;
373
374         wimlib_assert(!inode->resolved);
375
376         for (unsigned i = 0; i <= inode->num_ads; i++) {
377                 struct lookup_table_entry *src_lte, *dest_lte;
378                 src_lte = inode_stream_lte_unresolved(inode, i,
379                                                       src_wim->lookup_table);
380
381                 if (!src_lte) /* Empty or nonexistent stream. */
382                         continue;
383
384                 dest_lte = inode_stream_lte_unresolved(inode, i,
385                                                        dest_wim->lookup_table);
386                 if (dest_lte) {
387                         dest_lte->refcnt++;
388                 } else {
389                         struct list_head *lte_list_head;
390                         struct list_head *next;
391
392                         lte_list_head = &((struct wim_pair*)arg)->lte_list_head;
393                         wimlib_assert(!list_empty(lte_list_head));
394
395                         next = lte_list_head->next;
396                         list_del(next);
397                         dest_lte = container_of(next, struct lookup_table_entry,
398                                                 staging_list);
399                         dest_lte->part_number = 1;
400                         dest_lte->refcnt = 1;
401                         wimlib_assert(hashes_equal(dest_lte->hash, src_lte->hash));
402
403                         lookup_table_insert(dest_wim->lookup_table, dest_lte);
404                 }
405         }
406         return 0;
407 }
408
409 /*
410  * Adds an image (given by its dentry tree) to the image metadata array of a WIM
411  * file, adds an entry to the lookup table for the image metadata, updates the
412  * image count in the header, and selects the new image.
413  *
414  * Does not update the XML data.
415  *
416  * On failure, WIMLIB_ERR_NOMEM is returned and no changes are made.  Otherwise,
417  * 0 is returned and the image metadata array of @w is modified.
418  *
419  * @w:            The WIMStruct for the WIM file.
420  * @root_dentry:  The root of the directory tree for the image.
421  * @sd:           The security data for the image.
422  */
423 static int add_new_dentry_tree(WIMStruct *w, struct dentry *root_dentry,
424                                struct wim_security_data *sd)
425 {
426         struct lookup_table_entry *metadata_lte;
427         struct image_metadata *imd;
428         struct image_metadata *new_imd;
429         int ret;
430
431         wimlib_assert(root_dentry != NULL);
432
433         DEBUG("Reallocating image metadata array for image_count = %u",
434               w->hdr.image_count + 1);
435         imd = CALLOC((w->hdr.image_count + 1), sizeof(struct image_metadata));
436
437         if (!imd) {
438                 ERROR("Failed to allocate memory for new image metadata array");
439                 goto err;
440         }
441
442         memcpy(imd, w->image_metadata,
443                w->hdr.image_count * sizeof(struct image_metadata));
444
445         metadata_lte = new_lookup_table_entry();
446         if (!metadata_lte)
447                 goto err_free_imd;
448
449         metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
450         random_hash(metadata_lte->hash);
451         lookup_table_insert(w->lookup_table, metadata_lte);
452
453         new_imd = &imd[w->hdr.image_count];
454
455         new_imd->root_dentry    = root_dentry;
456         new_imd->metadata_lte   = metadata_lte;
457         new_imd->security_data  = sd;
458         new_imd->modified       = true;
459
460         FREE(w->image_metadata);
461         w->image_metadata       = imd;
462         w->hdr.image_count++;
463
464         /* Change the current image to the new one.  There should not be any
465          * ways for this to fail, since the image is valid and the dentry tree
466          * is already in memory. */
467         ret = select_wim_image(w, w->hdr.image_count);
468         wimlib_assert(ret == 0);
469         return ret;
470 err_free_imd:
471         FREE(imd);
472 err:
473         return WIMLIB_ERR_NOMEM;
474
475 }
476
477 /*
478  * Copies an image, or all the images, from a WIM file, into another WIM file.
479  */
480 WIMLIBAPI int wimlib_export_image(WIMStruct *src_wim,
481                                   int src_image,
482                                   WIMStruct *dest_wim,
483                                   const char *dest_name,
484                                   const char *dest_description,
485                                   int export_flags,
486                                   WIMStruct **additional_swms,
487                                   unsigned num_additional_swms,
488                                   wimlib_progress_func_t progress_func)
489 {
490         int i;
491         int ret;
492         struct dentry *root;
493         struct wim_pair wims;
494         struct wim_security_data *sd;
495         struct lookup_table *joined_tab, *src_wim_tab_save;
496
497         if (!src_wim || !dest_wim)
498                 return WIMLIB_ERR_INVALID_PARAM;
499
500         if (dest_wim->hdr.total_parts != 1) {
501                 ERROR("Exporting an image to a split WIM is "
502                       "unsupported");
503                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
504         }
505
506         if (src_image == WIMLIB_ALL_IMAGES) {
507                 if (src_wim->hdr.image_count > 1) {
508
509                         /* multi-image export. */
510
511                         if ((export_flags & WIMLIB_EXPORT_FLAG_BOOT) &&
512                               (src_wim->hdr.boot_idx == 0))
513                         {
514                                 /* Specifying the boot flag on a multi-image
515                                  * source WIM makes the boot index default to
516                                  * the bootable image in the source WIM.  It is
517                                  * an error if there is no such bootable image.
518                                  * */
519                                 ERROR("Cannot specify `boot' flag when "
520                                       "exporting multiple images from a WIM "
521                                       "with no bootable images");
522                                 return WIMLIB_ERR_INVALID_PARAM;
523                         }
524                         if (dest_name || dest_description) {
525                                 ERROR("Image name or image description was "
526                                       "specified, but we are exporting "
527                                       "multiple images");
528                                 return WIMLIB_ERR_INVALID_PARAM;
529                         }
530                         for (i = 1; i <= src_wim->hdr.image_count; i++) {
531                                 int new_flags = export_flags;
532
533                                 if (i != src_wim->hdr.boot_idx)
534                                         new_flags &= ~WIMLIB_EXPORT_FLAG_BOOT;
535
536                                 ret = wimlib_export_image(src_wim, i, dest_wim,
537                                                           NULL, NULL,
538                                                           new_flags,
539                                                           additional_swms,
540                                                           num_additional_swms,
541                                                           progress_func);
542                                 if (ret != 0)
543                                         return ret;
544                         }
545                         return 0;
546                 } else if (src_wim->hdr.image_count == 1) {
547                         src_image = 1;
548                 } else {
549                         return 0;
550                 }
551         }
552
553         if (!dest_name) {
554                 dest_name = wimlib_get_image_name(src_wim, src_image);
555                 DEBUG("Using name `%s' for source image %d",
556                       dest_name, src_image);
557         }
558
559         if (!dest_description) {
560                 dest_description = wimlib_get_image_description(src_wim,
561                                                                 src_image);
562                 DEBUG("Using description `%s' for source image %d",
563                       dest_description, src_image);
564         }
565
566         DEBUG("Exporting image %d from `%s'", src_image, src_wim->filename);
567
568         if (wimlib_image_name_in_use(dest_wim, dest_name)) {
569                 ERROR("There is already an image named `%s' in the "
570                       "destination WIM", dest_name);
571                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
572         }
573
574         ret = verify_swm_set(src_wim, additional_swms, num_additional_swms);
575         if (ret != 0)
576                 return ret;
577
578         if (num_additional_swms) {
579                 ret = new_joined_lookup_table(src_wim, additional_swms,
580                                               num_additional_swms,
581                                               &joined_tab);
582                 if (ret != 0)
583                         return ret;
584                 src_wim_tab_save = src_wim->lookup_table;
585                 src_wim->lookup_table = joined_tab;
586         }
587
588         ret = select_wim_image(src_wim, src_image);
589         if (ret != 0) {
590                 ERROR("Could not select image %d from the WIM `%s' "
591                       "to export it", src_image, src_wim->filename);
592                 goto out;
593         }
594
595         /* Pre-allocate the new lookup table entries that will be needed.  This
596          * way, it's not possible to run out of memory part-way through
597          * modifying the lookup table of the destination WIM. */
598         wims.src_wim = src_wim;
599         wims.dest_wim = dest_wim;
600         INIT_LIST_HEAD(&wims.lte_list_head);
601         for_lookup_table_entry(src_wim->lookup_table, lte_zero_out_refcnt, NULL);
602         root = wim_root_dentry(src_wim);
603         for_dentry_in_tree(root, dentry_unresolve_ltes, NULL);
604         ret = for_dentry_in_tree(root, allocate_lte_if_needed, &wims);
605         if (ret != 0)
606                 goto out_free_ltes;
607
608         ret = xml_export_image(src_wim->wim_info, src_image,
609                                &dest_wim->wim_info, dest_name, dest_description);
610         if (ret != 0)
611                 goto out_free_ltes;
612
613         sd = wim_security_data(src_wim);
614         ret = add_new_dentry_tree(dest_wim, root, sd);
615         if (ret != 0)
616                 goto out_xml_delete_image;
617
618
619         /* All memory allocations have been taken care of, so it's no longer
620          * possible for this function to fail.  Go ahead and increment the
621          * reference counts of the dentry tree and security data, then update
622          * the lookup table of the destination WIM and the boot index, if
623          * needed. */
624         for_dentry_in_tree(root, increment_dentry_refcnt, NULL);
625         sd->refcnt++;
626         for_dentry_in_tree(root, add_lte_to_dest_wim, &wims);
627         wimlib_assert(list_empty(&wims.lte_list_head));
628
629         if (export_flags & WIMLIB_EXPORT_FLAG_BOOT) {
630                 DEBUG("Setting boot_idx to %d", dest_wim->hdr.image_count);
631                 wimlib_set_boot_idx(dest_wim, dest_wim->hdr.image_count);
632         }
633         ret = 0;
634         goto out;
635
636 out_xml_delete_image:
637         xml_delete_image(&dest_wim->wim_info, dest_wim->hdr.image_count);
638 out_free_ltes:
639         {
640                 struct lookup_table_entry *lte, *tmp;
641                 list_for_each_entry_safe(lte, tmp, &wims.lte_list_head, staging_list)
642                         free_lookup_table_entry(lte);
643         }
644
645 out:
646         if (num_additional_swms) {
647                 free_lookup_table(src_wim->lookup_table);
648                 src_wim->lookup_table = src_wim_tab_save;
649         }
650         return ret;
651 }
652
653 /*
654  * Deletes an image from the WIM.
655  */
656 WIMLIBAPI int wimlib_delete_image(WIMStruct *w, int image)
657 {
658         int i;
659         int ret;
660
661         if (w->hdr.total_parts != 1) {
662                 ERROR("Deleting an image from a split WIM is not supported.");
663                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
664         }
665
666         if (image == WIMLIB_ALL_IMAGES) {
667                 for (i = w->hdr.image_count; i >= 1; i--) {
668                         ret = wimlib_delete_image(w, i);
669                         if (ret != 0)
670                                 return ret;
671                 }
672                 return 0;
673         }
674
675         DEBUG("Deleting image %d", image);
676
677         /* Even if the dentry tree is not allocated, we must select it (and
678          * therefore allocate it) so that we can decrement the reference counts
679          * in the lookup table.  */
680         ret = select_wim_image(w, image);
681         if (ret != 0)
682                 return ret;
683
684         /* Free the dentry tree, any lookup table entries that have their
685          * refcnt decremented to 0, and the security data. */
686         destroy_image_metadata(&w->image_metadata[image - 1], w->lookup_table);
687
688         /* Get rid of the empty slot in the image metadata array. */
689         memmove(&w->image_metadata[image - 1], &w->image_metadata[image],
690                 (w->hdr.image_count - image) * sizeof(struct image_metadata));
691
692         /* Decrement the image count. */
693         if (--w->hdr.image_count == 0) {
694                 FREE(w->image_metadata);
695                 w->image_metadata = NULL;
696         }
697
698         /* Fix the boot index. */
699         if (w->hdr.boot_idx == image)
700                 w->hdr.boot_idx = 0;
701         else if (w->hdr.boot_idx > image)
702                 w->hdr.boot_idx--;
703
704         w->current_image = WIMLIB_NO_IMAGE;
705
706         /* Remove the image from the XML information. */
707         xml_delete_image(&w->wim_info, image);
708
709         w->deletion_occurred = true;
710         return 0;
711 }
712
713 enum pattern_type {
714         NONE = 0,
715         EXCLUSION_LIST,
716         EXCLUSION_EXCEPTION,
717         COMPRESSION_EXCLUSION_LIST,
718         ALIGNMENT_LIST,
719 };
720
721 /* Default capture configuration file when none is specified. */
722 static const char *default_config =
723 "[ExclusionList]\n"
724 "\\$ntfs.log\n"
725 "\\hiberfil.sys\n"
726 "\\pagefile.sys\n"
727 "\\System Volume Information\n"
728 "\\RECYCLER\n"
729 "\\Windows\\CSC\n"
730 "\n"
731 "[CompressionExclusionList]\n"
732 "*.mp3\n"
733 "*.zip\n"
734 "*.cab\n"
735 "\\WINDOWS\\inf\\*.pnf\n";
736
737 static void destroy_pattern_list(struct pattern_list *list)
738 {
739         FREE(list->pats);
740 }
741
742 static void destroy_capture_config(struct capture_config *config)
743 {
744         destroy_pattern_list(&config->exclusion_list);
745         destroy_pattern_list(&config->exclusion_exception);
746         destroy_pattern_list(&config->compression_exclusion_list);
747         destroy_pattern_list(&config->alignment_list);
748         FREE(config->config_str);
749         FREE(config->prefix);
750         memset(config, 0, sizeof(*config));
751 }
752
753 static int pattern_list_add_pattern(struct pattern_list *list,
754                                     const char *pattern)
755 {
756         const char **pats;
757         if (list->num_pats >= list->num_allocated_pats) {
758                 pats = REALLOC(list->pats,
759                                sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
760                 if (!pats)
761                         return WIMLIB_ERR_NOMEM;
762                 list->num_allocated_pats += 8;
763                 list->pats = pats;
764         }
765         list->pats[list->num_pats++] = pattern;
766         return 0;
767 }
768
769 /* Parses the contents of the image capture configuration file and fills in a
770  * `struct capture_config'. */
771 static int init_capture_config(const char *_config_str, size_t config_len,
772                                const char *_prefix, struct capture_config *config)
773 {
774         char *config_str;
775         char *prefix;
776         char *p;
777         char *eol;
778         char *next_p;
779         size_t bytes_remaining;
780         enum pattern_type type = NONE;
781         int ret;
782         unsigned long line_no = 0;
783
784         DEBUG("config_len = %zu", config_len);
785         bytes_remaining = config_len;
786         memset(config, 0, sizeof(*config));
787         config_str = MALLOC(config_len);
788         if (!config_str) {
789                 ERROR("Could not duplicate capture config string");
790                 return WIMLIB_ERR_NOMEM;
791         }
792         prefix = STRDUP(_prefix);
793         if (!prefix) {
794                 FREE(config_str);
795                 return WIMLIB_ERR_NOMEM;
796         }
797
798         memcpy(config_str, _config_str, config_len);
799         next_p = config_str;
800         config->config_str = config_str;
801         config->prefix = prefix;
802         config->prefix_len = strlen(prefix);
803         while (bytes_remaining) {
804                 line_no++;
805                 p = next_p;
806                 eol = memchr(p, '\n', bytes_remaining);
807                 if (!eol) {
808                         ERROR("Expected end-of-line in capture config file on "
809                               "line %lu", line_no);
810                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
811                         goto out_destroy;
812                 }
813
814                 next_p = eol + 1;
815                 bytes_remaining -= (next_p - p);
816                 if (eol == p)
817                         continue;
818
819                 if (*(eol - 1) == '\r')
820                         eol--;
821                 *eol = '\0';
822
823                 /* Translate backslash to forward slash */
824                 for (char *pp = p; pp != eol; pp++)
825                         if (*pp == '\\')
826                                 *pp = '/';
827
828                 /* Remove drive letter */
829                 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
830                         p += 2;
831
832                 ret = 0;
833                 if (strcmp(p, "[ExclusionList]") == 0)
834                         type = EXCLUSION_LIST;
835                 else if (strcmp(p, "[ExclusionException]") == 0)
836                         type = EXCLUSION_EXCEPTION;
837                 else if (strcmp(p, "[CompressionExclusionList]") == 0)
838                         type = COMPRESSION_EXCLUSION_LIST;
839                 else if (strcmp(p, "[AlignmentList]") == 0)
840                         type = ALIGNMENT_LIST;
841                 else if (p[0] == '[' && strrchr(p, ']')) {
842                         ERROR("Unknown capture configuration section `%s'", p);
843                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
844                 } else switch (type) {
845                 case EXCLUSION_LIST:
846                         DEBUG("Adding pattern \"%s\" to exclusion list", p);
847                         ret = pattern_list_add_pattern(&config->exclusion_list, p);
848                         break;
849                 case EXCLUSION_EXCEPTION:
850                         DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
851                         ret = pattern_list_add_pattern(&config->exclusion_exception, p);
852                         break;
853                 case COMPRESSION_EXCLUSION_LIST:
854                         DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
855                         ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
856                         break;
857                 case ALIGNMENT_LIST:
858                         DEBUG("Adding pattern \"%s\" to alignment list", p);
859                         ret = pattern_list_add_pattern(&config->alignment_list, p);
860                         break;
861                 default:
862                         ERROR("Line %lu of capture configuration is not "
863                               "in a block (such as [ExclusionList])",
864                               line_no);
865                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
866                         break;
867                 }
868                 if (ret != 0)
869                         goto out_destroy;
870         }
871         return 0;
872 out_destroy:
873         destroy_capture_config(config);
874         return ret;
875 }
876
877 static bool match_pattern(const char *path, const char *path_basename,
878                           const struct pattern_list *list)
879 {
880         for (size_t i = 0; i < list->num_pats; i++) {
881                 const char *pat = list->pats[i];
882                 const char *string;
883                 if (pat[0] == '/')
884                         /* Absolute path from root of capture */
885                         string = path;
886                 else {
887                         if (strchr(pat, '/'))
888                                 /* Relative path from root of capture */
889                                 string = path + 1;
890                         else
891                                 /* A file name pattern */
892                                 string = path_basename;
893                 }
894                 if (fnmatch(pat, string, FNM_PATHNAME
895                         #ifdef FNM_CASEFOLD
896                                         | FNM_CASEFOLD
897                         #endif
898                         ) == 0)
899                 {
900                         DEBUG("`%s' matches the pattern \"%s\"",
901                               string, pat);
902                         return true;
903                 }
904         }
905         return false;
906 }
907
908 static void print_pattern_list(const struct pattern_list *list)
909 {
910         for (size_t i = 0; i < list->num_pats; i++)
911                 printf("    %s\n", list->pats[i]);
912 }
913
914 static void print_capture_config(const struct capture_config *config)
915 {
916         if (config->exclusion_list.num_pats) {
917                 puts("Files or folders excluded from image capture:");
918                 print_pattern_list(&config->exclusion_list);
919                 putchar('\n');
920         }
921 }
922
923 /* Return true if the image capture configuration file indicates we should
924  * exclude the filename @path from capture.
925  *
926  * If @exclude_prefix is %true, the part of the path up and including the name
927  * of the directory being captured is not included in the path for matching
928  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
929  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
930  * directory.
931  */
932 bool exclude_path(const char *path, const struct capture_config *config,
933                   bool exclude_prefix)
934 {
935         const char *basename = path_basename(path);
936         if (exclude_prefix) {
937                 wimlib_assert(strlen(path) >= config->prefix_len);
938                 if (memcmp(config->prefix, path, config->prefix_len) == 0
939                      && path[config->prefix_len] == '/')
940                         path += config->prefix_len;
941         }
942         return match_pattern(path, basename, &config->exclusion_list) &&
943                 !match_pattern(path, basename, &config->exclusion_exception);
944
945 }
946
947 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *source,
948                                const char *name, const char *config_str,
949                                size_t config_len, int add_image_flags,
950                                wimlib_progress_func_t progress_func)
951 {
952         int (*capture_tree)(struct dentry **, const char *,
953                             struct lookup_table *,
954                             struct wim_security_data *,
955                             const struct capture_config *,
956                             int, void *);
957         void *extra_arg;
958
959         struct dentry *root_dentry = NULL;
960         struct wim_security_data *sd;
961         struct capture_config config;
962         struct inode_table inode_tab;
963         struct hlist_head inode_list;
964         int ret;
965
966         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
967 #ifdef WITH_NTFS_3G
968                 if (add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)) {
969                         ERROR("Cannot dereference files when capturing directly from NTFS");
970                         return WIMLIB_ERR_INVALID_PARAM;
971                 }
972                 capture_tree = build_dentry_tree_ntfs;
973                 extra_arg = &w->ntfs_vol;
974 #else
975                 ERROR("wimlib was compiled without support for NTFS-3g, so");
976                 ERROR("we cannot capture a WIM image directly from a NTFS volume");
977                 return WIMLIB_ERR_UNSUPPORTED;
978 #endif
979         } else {
980                 capture_tree = build_dentry_tree;
981                 extra_arg = NULL;
982         }
983
984         DEBUG("Adding dentry tree from directory or NTFS volume `%s'.", dir);
985
986         if (!name || !*name) {
987                 ERROR("Must specify a non-empty string for the image name");
988                 return WIMLIB_ERR_INVALID_PARAM;
989         }
990         if (!source) {
991                 ERROR("Must specify the name of a directory or NTFS volume");
992                 return WIMLIB_ERR_INVALID_PARAM;
993         }
994
995         if (w->hdr.total_parts != 1) {
996                 ERROR("Cannot add an image to a split WIM");
997                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
998         }
999
1000         if (wimlib_image_name_in_use(w, name)) {
1001                 ERROR("There is already an image named \"%s\" in `%s'",
1002                       name, w->filename);
1003                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1004         }
1005
1006         DEBUG("Initializing capture configuration");
1007         if (!config_str) {
1008                 DEBUG("Using default capture configuration");
1009                 config_str = default_config;
1010                 config_len = strlen(default_config);
1011         }
1012         ret = init_capture_config(config_str, config_len, source, &config);
1013         if (ret != 0)
1014                 return ret;
1015         print_capture_config(&config);
1016
1017         DEBUG("Allocating security data");
1018
1019         sd = CALLOC(1, sizeof(struct wim_security_data));
1020         if (!sd) {
1021                 ret = WIMLIB_ERR_NOMEM;
1022                 goto out_destroy_config;
1023         }
1024         sd->total_length = 8;
1025         sd->refcnt = 1;
1026
1027         if (progress_func) {
1028                 union wimlib_progress_info progress;
1029                 progress.scan.source = source;
1030                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
1031         }
1032
1033         DEBUG("Building dentry tree.");
1034         ret = (*capture_tree)(&root_dentry, source, w->lookup_table, sd,
1035                               &config, add_image_flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
1036                               extra_arg);
1037         destroy_capture_config(&config);
1038
1039         if (ret != 0) {
1040                 ERROR("Failed to build dentry tree for `%s'", source);
1041                 goto out_free_security_data;
1042         }
1043
1044         if (progress_func) {
1045                 union wimlib_progress_info progress;
1046                 progress.scan.source = source;
1047                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
1048         }
1049
1050         DEBUG("Calculating full paths of dentries.");
1051         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
1052         if (ret != 0)
1053                 goto out_free_dentry_tree;
1054
1055         ret = add_new_dentry_tree(w, root_dentry, sd);
1056         if (ret != 0)
1057                 goto out_free_dentry_tree;
1058
1059         DEBUG("Inserting dentries into inode table");
1060         ret = init_inode_table(&inode_tab, 9001);
1061         if (ret != 0)
1062                 goto out_destroy_imd;
1063
1064         for_dentry_in_tree(root_dentry, inode_table_insert, &inode_tab);
1065
1066         DEBUG("Cleaning up the hard link groups");
1067         ret = fix_inodes(&inode_tab, &inode_list);
1068         destroy_inode_table(&inode_tab);
1069         if (ret != 0)
1070                 goto out_destroy_imd;
1071
1072         DEBUG("Assigning hard link group IDs");
1073         assign_inode_numbers(&inode_list);
1074
1075         ret = xml_add_image(w, name);
1076         if (ret != 0)
1077                 goto out_destroy_imd;
1078
1079         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
1080                 wimlib_set_boot_idx(w, w->hdr.image_count);
1081         return 0;
1082 out_destroy_imd:
1083         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
1084                                w->lookup_table);
1085         w->hdr.image_count--;
1086         return ret;
1087 out_free_dentry_tree:
1088         free_dentry_tree(root_dentry, w->lookup_table);
1089 out_free_security_data:
1090         free_security_data(sd);
1091 out_destroy_config:
1092         destroy_capture_config(&config);
1093         return ret;
1094 }