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