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