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