42de5e92849613da8debf887dc45cacee4fb369a
[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 entry, *result;
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                         ret = readdir_r(dir, &entry, &result);
261                         if (ret != 0) {
262                                 ret = WIMLIB_ERR_READ;
263                                 ERROR_WITH_ERRNO("Error reading the "
264                                                  "directory `%s'",
265                                                  root_disk_path);
266                                 break;
267                         }
268                         if (result == NULL)
269                                 break;
270                         if (result->d_name[0] == '.' && (result->d_name[1] == '\0'
271                               || (result->d_name[1] == '.' && result->d_name[2] == '\0')))
272                                         continue;
273                         strcpy(name + len + 1, result->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 (dest_wim->hdr.total_parts != 1) {
515                 ERROR("Exporting an image to a split WIM is "
516                       "unsupported");
517                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
518         }
519
520         if (src_image == WIMLIB_ALL_IMAGES) {
521                 if (src_wim->hdr.image_count > 1) {
522
523                         /* multi-image export. */
524
525                         if ((export_flags & WIMLIB_EXPORT_FLAG_BOOT) &&
526                               (src_wim->hdr.boot_idx == 0))
527                         {
528                                 /* Specifying the boot flag on a multi-image
529                                  * source WIM makes the boot index default to
530                                  * the bootable image in the source WIM.  It is
531                                  * an error if there is no such bootable image.
532                                  * */
533                                 ERROR("Cannot specify `boot' flag when "
534                                       "exporting multiple images from a WIM "
535                                       "with no bootable images");
536                                 return WIMLIB_ERR_INVALID_PARAM;
537                         }
538                         if (dest_name || dest_description) {
539                                 ERROR("Image name or image description was "
540                                       "specified, but we are exporting "
541                                       "multiple images");
542                                 return WIMLIB_ERR_INVALID_PARAM;
543                         }
544                         for (i = 1; i <= src_wim->hdr.image_count; i++) {
545                                 int new_flags = export_flags;
546
547                                 if (i != src_wim->hdr.boot_idx)
548                                         new_flags &= ~WIMLIB_EXPORT_FLAG_BOOT;
549
550                                 ret = wimlib_export_image(src_wim, i, dest_wim,
551                                                           NULL, NULL,
552                                                           new_flags,
553                                                           additional_swms,
554                                                           num_additional_swms,
555                                                           progress_func);
556                                 if (ret != 0)
557                                         return ret;
558                         }
559                         return 0;
560                 } else if (src_wim->hdr.image_count == 1) {
561                         src_image = 1;
562                 } else {
563                         return 0;
564                 }
565         }
566
567         if (!dest_name) {
568                 dest_name = wimlib_get_image_name(src_wim, src_image);
569                 DEBUG("Using name `%s' for source image %d",
570                       dest_name, src_image);
571         }
572
573         if (!dest_description) {
574                 dest_description = wimlib_get_image_description(src_wim,
575                                                                 src_image);
576                 DEBUG("Using description `%s' for source image %d",
577                       dest_description, src_image);
578         }
579
580         DEBUG("Exporting image %d from `%s'", src_image, src_wim->filename);
581
582         if (wimlib_image_name_in_use(dest_wim, dest_name)) {
583                 ERROR("There is already an image named `%s' in the "
584                       "destination WIM", dest_name);
585                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
586         }
587
588         ret = verify_swm_set(src_wim, additional_swms, num_additional_swms);
589         if (ret != 0)
590                 return ret;
591
592         if (num_additional_swms) {
593                 ret = new_joined_lookup_table(src_wim, additional_swms,
594                                               num_additional_swms,
595                                               &joined_tab);
596                 if (ret != 0)
597                         return ret;
598                 src_wim_tab_save = src_wim->lookup_table;
599                 src_wim->lookup_table = joined_tab;
600         }
601
602         ret = select_wim_image(src_wim, src_image);
603         if (ret != 0) {
604                 ERROR("Could not select image %d from the WIM `%s' "
605                       "to export it", src_image, src_wim->filename);
606                 goto out;
607         }
608
609         /* Pre-allocate the new lookup table entries that will be needed.  This
610          * way, it's not possible to run out of memory part-way through
611          * modifying the lookup table of the destination WIM. */
612         wims.src_wim = src_wim;
613         wims.dest_wim = dest_wim;
614         INIT_LIST_HEAD(&wims.lte_list_head);
615         for_lookup_table_entry(src_wim->lookup_table, lte_zero_out_refcnt, NULL);
616         root = wim_root_dentry(src_wim);
617         for_dentry_in_tree(root, dentry_unresolve_ltes, NULL);
618         ret = for_dentry_in_tree(root, allocate_lte_if_needed, &wims);
619         if (ret != 0)
620                 goto out_free_ltes;
621
622         ret = xml_export_image(src_wim->wim_info, src_image,
623                                &dest_wim->wim_info, dest_name, dest_description);
624         if (ret != 0)
625                 goto out_free_ltes;
626
627         sd = wim_security_data(src_wim);
628         ret = add_new_dentry_tree(dest_wim, root, sd);
629         if (ret != 0)
630                 goto out_xml_delete_image;
631
632
633         /* All memory allocations have been taken care of, so it's no longer
634          * possible for this function to fail.  Go ahead and increment the
635          * reference counts of the dentry tree and security data, then update
636          * the lookup table of the destination WIM and the boot index, if
637          * needed. */
638         for_dentry_in_tree(root, increment_dentry_refcnt, NULL);
639         sd->refcnt++;
640         for_dentry_in_tree(root, add_lte_to_dest_wim, &wims);
641         wimlib_assert(list_empty(&wims.lte_list_head));
642
643         if (export_flags & WIMLIB_EXPORT_FLAG_BOOT) {
644                 DEBUG("Setting boot_idx to %d", dest_wim->hdr.image_count);
645                 wimlib_set_boot_idx(dest_wim, dest_wim->hdr.image_count);
646         }
647         ret = 0;
648         goto out;
649
650 out_xml_delete_image:
651         xml_delete_image(&dest_wim->wim_info, dest_wim->hdr.image_count);
652 out_free_ltes:
653         {
654                 struct lookup_table_entry *lte, *tmp;
655                 list_for_each_entry_safe(lte, tmp, &wims.lte_list_head, staging_list)
656                         free_lookup_table_entry(lte);
657         }
658
659 out:
660         if (num_additional_swms) {
661                 free_lookup_table(src_wim->lookup_table);
662                 src_wim->lookup_table = src_wim_tab_save;
663         }
664         return ret;
665 }
666
667 static int image_run_full_verifications(WIMStruct *w)
668 {
669         return for_dentry_in_tree(wim_root_dentry(w), verify_dentry, w);
670 }
671
672 static int lte_fix_refcnt(struct lookup_table_entry *lte, void *ctr)
673 {
674         if (lte->refcnt != lte->real_refcnt) {
675                 WARNING("The following lookup table entry has a reference "
676                         "count of %u, but", lte->refcnt);
677                 WARNING("We found %u references to it",
678                         lte->real_refcnt);
679                 print_lookup_table_entry(lte);
680                 lte->refcnt = lte->real_refcnt;
681                 ++*(unsigned long *)ctr;
682         }
683         return 0;
684 }
685
686 /* Ideally this would be unnecessary... however, the WIMs for Windows 8 are
687  * screwed up because some lookup table entries are referenced more times than
688  * their stated reference counts.  So theoretically, if we do the delete all the
689  * references to a stream and then remove it, it might still be referenced
690  * somewhere else... So, work around this problem by looking at ALL the images
691  * to re-calculate the reference count of EVERY lookup table entry. */
692 int wim_run_full_verifications(WIMStruct *w)
693 {
694         int ret;
695
696         for_lookup_table_entry(w->lookup_table, lte_zero_real_refcnt, NULL);
697         w->all_images_verified = true;
698         w->full_verification_in_progress = true;
699         ret = for_image(w, WIMLIB_ALL_IMAGES, image_run_full_verifications);
700         w->full_verification_in_progress = false;
701         if (ret == 0) {
702                 unsigned long num_ltes_with_bogus_refcnt = 0;
703                 for_lookup_table_entry(w->lookup_table, lte_fix_refcnt,
704                                        &num_ltes_with_bogus_refcnt);
705                 if (num_ltes_with_bogus_refcnt != 0) {
706                         WARNING("A total of %lu entries in the WIM's stream "
707                                 "lookup table had to have\n"
708                                 "          their reference counts fixed.",
709                                 num_ltes_with_bogus_refcnt);
710                 }
711         } else {
712                 w->all_images_verified = false;
713         }
714         return ret;
715 }
716
717 /*
718  * Deletes an image from the WIM.
719  */
720 WIMLIBAPI int wimlib_delete_image(WIMStruct *w, int image)
721 {
722         int i;
723         int ret;
724
725         if (w->hdr.total_parts != 1) {
726                 ERROR("Deleting an image from a split WIM is not supported.");
727                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
728         }
729
730         if (image == WIMLIB_ALL_IMAGES) {
731                 for (i = w->hdr.image_count; i >= 1; i--) {
732                         ret = wimlib_delete_image(w, i);
733                         if (ret != 0)
734                                 return ret;
735                 }
736                 return 0;
737         }
738
739         if (!w->all_images_verified) {
740                 ret = wim_run_full_verifications(w);
741                 if (ret != 0)
742                         return ret;
743         }
744
745         DEBUG("Deleting image %d", image);
746
747         /* Even if the dentry tree is not allocated, we must select it (and
748          * therefore allocate it) so that we can decrement the reference counts
749          * in the lookup table.  */
750         ret = select_wim_image(w, image);
751         if (ret != 0)
752                 return ret;
753
754         /* Free the dentry tree, any lookup table entries that have their
755          * refcnt decremented to 0, and the security data. */
756         destroy_image_metadata(&w->image_metadata[image - 1], w->lookup_table);
757
758         /* Get rid of the empty slot in the image metadata array. */
759         memmove(&w->image_metadata[image - 1], &w->image_metadata[image],
760                 (w->hdr.image_count - image) * sizeof(struct image_metadata));
761
762         /* Decrement the image count. */
763         if (--w->hdr.image_count == 0) {
764                 FREE(w->image_metadata);
765                 w->image_metadata = NULL;
766         }
767
768         /* Fix the boot index. */
769         if (w->hdr.boot_idx == image)
770                 w->hdr.boot_idx = 0;
771         else if (w->hdr.boot_idx > image)
772                 w->hdr.boot_idx--;
773
774         w->current_image = WIMLIB_NO_IMAGE;
775
776         /* Remove the image from the XML information. */
777         xml_delete_image(&w->wim_info, image);
778
779         w->deletion_occurred = true;
780         return 0;
781 }
782
783 enum pattern_type {
784         NONE = 0,
785         EXCLUSION_LIST,
786         EXCLUSION_EXCEPTION,
787         COMPRESSION_EXCLUSION_LIST,
788         ALIGNMENT_LIST,
789 };
790
791 /* Default capture configuration file when none is specified. */
792 static const char *default_config =
793 "[ExclusionList]\n"
794 "\\$ntfs.log\n"
795 "\\hiberfil.sys\n"
796 "\\pagefile.sys\n"
797 "\\System Volume Information\n"
798 "\\RECYCLER\n"
799 "\\Windows\\CSC\n"
800 "\n"
801 "[CompressionExclusionList]\n"
802 "*.mp3\n"
803 "*.zip\n"
804 "*.cab\n"
805 "\\WINDOWS\\inf\\*.pnf\n";
806
807 static void destroy_pattern_list(struct pattern_list *list)
808 {
809         FREE(list->pats);
810 }
811
812 static void destroy_capture_config(struct capture_config *config)
813 {
814         destroy_pattern_list(&config->exclusion_list);
815         destroy_pattern_list(&config->exclusion_exception);
816         destroy_pattern_list(&config->compression_exclusion_list);
817         destroy_pattern_list(&config->alignment_list);
818         FREE(config->config_str);
819         FREE(config->prefix);
820         memset(config, 0, sizeof(*config));
821 }
822
823 static int pattern_list_add_pattern(struct pattern_list *list,
824                                     const char *pattern)
825 {
826         const char **pats;
827         if (list->num_pats >= list->num_allocated_pats) {
828                 pats = REALLOC(list->pats,
829                                sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
830                 if (!pats)
831                         return WIMLIB_ERR_NOMEM;
832                 list->num_allocated_pats += 8;
833                 list->pats = pats;
834         }
835         list->pats[list->num_pats++] = pattern;
836         return 0;
837 }
838
839 /* Parses the contents of the image capture configuration file and fills in a
840  * `struct capture_config'. */
841 static int init_capture_config(const char *_config_str, size_t config_len,
842                                const char *_prefix, struct capture_config *config)
843 {
844         char *config_str;
845         char *prefix;
846         char *p;
847         char *eol;
848         char *next_p;
849         size_t bytes_remaining;
850         enum pattern_type type = NONE;
851         int ret;
852         unsigned long line_no = 0;
853
854         DEBUG("config_len = %zu", config_len);
855         bytes_remaining = config_len;
856         memset(config, 0, sizeof(*config));
857         config_str = MALLOC(config_len);
858         if (!config_str) {
859                 ERROR("Could not duplicate capture config string");
860                 return WIMLIB_ERR_NOMEM;
861         }
862         prefix = STRDUP(_prefix);
863         if (!prefix) {
864                 FREE(config_str);
865                 return WIMLIB_ERR_NOMEM;
866         }
867
868         memcpy(config_str, _config_str, config_len);
869         next_p = config_str;
870         config->config_str = config_str;
871         config->prefix = prefix;
872         config->prefix_len = strlen(prefix);
873         while (bytes_remaining) {
874                 line_no++;
875                 p = next_p;
876                 eol = memchr(p, '\n', bytes_remaining);
877                 if (!eol) {
878                         ERROR("Expected end-of-line in capture config file on "
879                               "line %lu", line_no);
880                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
881                         goto out_destroy;
882                 }
883
884                 next_p = eol + 1;
885                 bytes_remaining -= (next_p - p);
886                 if (eol == p)
887                         continue;
888
889                 if (*(eol - 1) == '\r')
890                         eol--;
891                 *eol = '\0';
892
893                 /* Translate backslash to forward slash */
894                 for (char *pp = p; pp != eol; pp++)
895                         if (*pp == '\\')
896                                 *pp = '/';
897
898                 /* Remove drive letter */
899                 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
900                         p += 2;
901
902                 ret = 0;
903                 if (strcmp(p, "[ExclusionList]") == 0)
904                         type = EXCLUSION_LIST;
905                 else if (strcmp(p, "[ExclusionException]") == 0)
906                         type = EXCLUSION_EXCEPTION;
907                 else if (strcmp(p, "[CompressionExclusionList]") == 0)
908                         type = COMPRESSION_EXCLUSION_LIST;
909                 else if (strcmp(p, "[AlignmentList]") == 0)
910                         type = ALIGNMENT_LIST;
911                 else if (p[0] == '[' && strrchr(p, ']')) {
912                         ERROR("Unknown capture configuration section `%s'", p);
913                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
914                 } else switch (type) {
915                 case EXCLUSION_LIST:
916                         DEBUG("Adding pattern \"%s\" to exclusion list", p);
917                         ret = pattern_list_add_pattern(&config->exclusion_list, p);
918                         break;
919                 case EXCLUSION_EXCEPTION:
920                         DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
921                         ret = pattern_list_add_pattern(&config->exclusion_exception, p);
922                         break;
923                 case COMPRESSION_EXCLUSION_LIST:
924                         DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
925                         ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
926                         break;
927                 case ALIGNMENT_LIST:
928                         DEBUG("Adding pattern \"%s\" to alignment list", p);
929                         ret = pattern_list_add_pattern(&config->alignment_list, p);
930                         break;
931                 default:
932                         ERROR("Line %lu of capture configuration is not "
933                               "in a block (such as [ExclusionList])",
934                               line_no);
935                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
936                         break;
937                 }
938                 if (ret != 0)
939                         goto out_destroy;
940         }
941         return 0;
942 out_destroy:
943         destroy_capture_config(config);
944         return ret;
945 }
946
947 static bool match_pattern(const char *path, const char *path_basename,
948                           const struct pattern_list *list)
949 {
950         for (size_t i = 0; i < list->num_pats; i++) {
951                 const char *pat = list->pats[i];
952                 const char *string;
953                 if (pat[0] == '/')
954                         /* Absolute path from root of capture */
955                         string = path;
956                 else {
957                         if (strchr(pat, '/'))
958                                 /* Relative path from root of capture */
959                                 string = path + 1;
960                         else
961                                 /* A file name pattern */
962                                 string = path_basename;
963                 }
964                 if (fnmatch(pat, string, FNM_PATHNAME
965                         #ifdef FNM_CASEFOLD
966                                         | FNM_CASEFOLD
967                         #endif
968                         ) == 0)
969                 {
970                         DEBUG("`%s' matches the pattern \"%s\"",
971                               string, pat);
972                         return true;
973                 }
974         }
975         return false;
976 }
977
978 static void print_pattern_list(const struct pattern_list *list)
979 {
980         for (size_t i = 0; i < list->num_pats; i++)
981                 printf("    %s\n", list->pats[i]);
982 }
983
984 static void print_capture_config(const struct capture_config *config)
985 {
986         if (config->exclusion_list.num_pats) {
987                 puts("Files or folders excluded from image capture:");
988                 print_pattern_list(&config->exclusion_list);
989                 putchar('\n');
990         }
991 }
992
993 /* Return true if the image capture configuration file indicates we should
994  * exclude the filename @path from capture.
995  *
996  * If @exclude_prefix is %true, the part of the path up and including the name
997  * of the directory being captured is not included in the path for matching
998  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
999  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
1000  * directory.
1001  */
1002 bool exclude_path(const char *path, const struct capture_config *config,
1003                   bool exclude_prefix)
1004 {
1005         const char *basename = path_basename(path);
1006         if (exclude_prefix) {
1007                 wimlib_assert(strlen(path) >= config->prefix_len);
1008                 if (memcmp(config->prefix, path, config->prefix_len) == 0
1009                      && path[config->prefix_len] == '/')
1010                         path += config->prefix_len;
1011         }
1012         return match_pattern(path, basename, &config->exclusion_list) &&
1013                 !match_pattern(path, basename, &config->exclusion_exception);
1014
1015 }
1016
1017 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *source,
1018                                const char *name, const char *config_str,
1019                                size_t config_len, int add_image_flags,
1020                                wimlib_progress_func_t progress_func)
1021 {
1022         int (*capture_tree)(struct dentry **, const char *,
1023                             struct lookup_table *,
1024                             struct wim_security_data *,
1025                             const struct capture_config *,
1026                             int, wimlib_progress_func_t, void *);
1027         void *extra_arg;
1028
1029         struct dentry *root_dentry = NULL;
1030         struct wim_security_data *sd;
1031         struct capture_config config;
1032         struct inode_table inode_tab;
1033         struct hlist_head inode_list;
1034         int ret;
1035
1036         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
1037 #ifdef WITH_NTFS_3G
1038                 if (add_image_flags & (WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)) {
1039                         ERROR("Cannot dereference files when capturing directly from NTFS");
1040                         return WIMLIB_ERR_INVALID_PARAM;
1041                 }
1042                 capture_tree = build_dentry_tree_ntfs;
1043                 extra_arg = &w->ntfs_vol;
1044 #else
1045                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
1046                       "        cannot capture a WIM image directly from a NTFS volume!");
1047                 return WIMLIB_ERR_UNSUPPORTED;
1048 #endif
1049         } else {
1050                 capture_tree = build_dentry_tree;
1051                 extra_arg = NULL;
1052         }
1053
1054         DEBUG("Adding dentry tree from directory or NTFS volume `%s'.", source);
1055
1056         if (!name || !*name) {
1057                 ERROR("Must specify a non-empty string for the image name");
1058                 return WIMLIB_ERR_INVALID_PARAM;
1059         }
1060         if (!source) {
1061                 ERROR("Must specify the name of a directory or NTFS volume");
1062                 return WIMLIB_ERR_INVALID_PARAM;
1063         }
1064
1065         if (w->hdr.total_parts != 1) {
1066                 ERROR("Cannot add an image to a split WIM");
1067                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1068         }
1069
1070         if (wimlib_image_name_in_use(w, name)) {
1071                 ERROR("There is already an image named \"%s\" in `%s'",
1072                       name, w->filename);
1073                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1074         }
1075
1076         DEBUG("Initializing capture configuration");
1077         if (!config_str) {
1078                 DEBUG("Using default capture configuration");
1079                 config_str = default_config;
1080                 config_len = strlen(default_config);
1081         }
1082         ret = init_capture_config(config_str, config_len, source, &config);
1083         if (ret != 0)
1084                 return ret;
1085         print_capture_config(&config);
1086
1087         DEBUG("Allocating security data");
1088
1089         sd = CALLOC(1, sizeof(struct wim_security_data));
1090         if (!sd) {
1091                 ret = WIMLIB_ERR_NOMEM;
1092                 goto out_destroy_config;
1093         }
1094         sd->total_length = 8;
1095         sd->refcnt = 1;
1096
1097         if (progress_func) {
1098                 union wimlib_progress_info progress;
1099                 progress.scan.source = source;
1100                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
1101         }
1102
1103         DEBUG("Building dentry tree.");
1104         ret = (*capture_tree)(&root_dentry, source, w->lookup_table, sd,
1105                               &config, add_image_flags | WIMLIB_ADD_IMAGE_FLAG_ROOT,
1106                               progress_func, extra_arg);
1107         destroy_capture_config(&config);
1108
1109         if (ret != 0) {
1110                 ERROR("Failed to build dentry tree for `%s'", source);
1111                 goto out_free_security_data;
1112         }
1113
1114         if (progress_func) {
1115                 union wimlib_progress_info progress;
1116                 progress.scan.source = source;
1117                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
1118         }
1119
1120         DEBUG("Calculating full paths of dentries.");
1121         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
1122         if (ret != 0)
1123                 goto out_free_dentry_tree;
1124
1125         ret = add_new_dentry_tree(w, root_dentry, sd);
1126         if (ret != 0)
1127                 goto out_free_dentry_tree;
1128
1129         DEBUG("Inserting dentries into inode table");
1130         ret = init_inode_table(&inode_tab, 9001);
1131         if (ret != 0)
1132                 goto out_destroy_imd;
1133
1134         for_dentry_in_tree(root_dentry, inode_table_insert, &inode_tab);
1135
1136         DEBUG("Cleaning up the hard link groups");
1137         ret = fix_inodes(&inode_tab, &inode_list);
1138         destroy_inode_table(&inode_tab);
1139         if (ret != 0)
1140                 goto out_destroy_imd;
1141
1142         DEBUG("Assigning hard link group IDs");
1143         assign_inode_numbers(&inode_list);
1144
1145         ret = xml_add_image(w, name);
1146         if (ret != 0)
1147                 goto out_destroy_imd;
1148
1149         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
1150                 wimlib_set_boot_idx(w, w->hdr.image_count);
1151         return 0;
1152 out_destroy_imd:
1153         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
1154                                w->lookup_table);
1155         w->hdr.image_count--;
1156         return ret;
1157 out_free_dentry_tree:
1158         free_dentry_tree(root_dentry, w->lookup_table);
1159 out_free_security_data:
1160         free_security_data(sd);
1161 out_destroy_config:
1162         destroy_capture_config(&config);
1163         return ret;
1164 }