]> wimlib.net Git - wimlib/blob - src/add_image.c
Source list mode
[wimlib] / src / add_image.c
1 /*
2  * add_image.c
3  */
4
5 /*
6  * Copyright (C) 2012, 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #include "wimlib_internal.h"
25 #include "dentry.h"
26 #include "timestamp.h"
27 #include "lookup_table.h"
28 #include "xml.h"
29 #include <string.h>
30 #include <fnmatch.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #include <sys/stat.h>
34 #include <dirent.h>
35 #include <errno.h>
36 #include <unistd.h>
37
38 #define WIMLIB_ADD_IMAGE_FLAG_ROOT      0x80000000
39 #define WIMLIB_ADD_IMAGE_FLAG_SOURCE    0x40000000
40
41 /*
42  * Adds the dentry tree and security data for a new image to the image metadata
43  * array of the WIMStruct.
44  */
45 int add_new_dentry_tree(WIMStruct *w, struct wim_dentry *root_dentry,
46                         struct wim_security_data *sd)
47 {
48         struct wim_lookup_table_entry *metadata_lte;
49         struct wim_image_metadata *imd;
50         struct wim_image_metadata *new_imd;
51
52         wimlib_assert(root_dentry != NULL);
53
54         DEBUG("Reallocating image metadata array for image_count = %u",
55               w->hdr.image_count + 1);
56         imd = CALLOC((w->hdr.image_count + 1), sizeof(struct wim_image_metadata));
57
58         if (!imd) {
59                 ERROR("Failed to allocate memory for new image metadata array");
60                 goto err;
61         }
62
63         memcpy(imd, w->image_metadata,
64                w->hdr.image_count * sizeof(struct wim_image_metadata));
65
66         metadata_lte = new_lookup_table_entry();
67         if (!metadata_lte)
68                 goto err_free_imd;
69
70         metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
71         random_hash(metadata_lte->hash);
72         lookup_table_insert(w->lookup_table, metadata_lte);
73
74         new_imd = &imd[w->hdr.image_count];
75
76         new_imd->root_dentry    = root_dentry;
77         new_imd->metadata_lte   = metadata_lte;
78         new_imd->security_data  = sd;
79         new_imd->modified       = 1;
80
81         FREE(w->image_metadata);
82         w->image_metadata = imd;
83         w->hdr.image_count++;
84         return 0;
85 err_free_imd:
86         FREE(imd);
87 err:
88         return WIMLIB_ERR_NOMEM;
89
90 }
91
92
93 /*
94  * build_dentry_tree():
95  *      Recursively builds a tree of WIM dentries from an on-disk directory
96  *      tree.
97  *
98  * @root_ret:   Place to return a pointer to the root of the dentry tree.  Only
99  *              modified if successful.  Set to NULL if the file or directory was
100  *              excluded from capture.
101  *
102  * @root_disk_path:  The path to the root of the directory tree on disk.
103  *
104  * @lookup_table: The lookup table for the WIM file.  For each file added to the
105  *              dentry tree being built, an entry is added to the lookup table,
106  *              unless an identical stream is already in the lookup table.
107  *              These lookup table entries that are added point to the path of
108  *              the file on disk.
109  *
110  * @sd:         Ignored.  (Security data only captured in NTFS mode.)
111  *
112  * @capture_config:
113  *              Configuration for files to be excluded from capture.
114  *
115  * @add_flags:  Bitwise or of WIMLIB_ADD_IMAGE_FLAG_*
116  *
117  * @extra_arg:  Ignored. (Only used in NTFS mode.)
118  *
119  * @return:     0 on success, nonzero on failure.  It is a failure if any of
120  *              the files cannot be `stat'ed, or if any of the needed
121  *              directories cannot be opened or read.  Failure to add the files
122  *              to the WIM may still occur later when trying to actually read
123  *              the on-disk files during a call to wimlib_write() or
124  *              wimlib_overwrite().
125  */
126 static int build_dentry_tree(struct wim_dentry **root_ret,
127                              const char *root_disk_path,
128                              struct wim_lookup_table *lookup_table,
129                              struct wim_security_data *sd,
130                              const struct capture_config *config,
131                              int add_image_flags,
132                              wimlib_progress_func_t progress_func,
133                              void *extra_arg)
134 {
135         struct stat root_stbuf;
136         int ret = 0;
137         int (*stat_fn)(const char *restrict, struct stat *restrict);
138         struct wim_dentry *root;
139         struct wim_inode *inode;
140
141         if (exclude_path(root_disk_path, config, true)) {
142                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
143                         ERROR("Cannot exclude the root directory from capture");
144                         return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
145                 }
146                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
147                     && progress_func)
148                 {
149                         union wimlib_progress_info info;
150                         info.scan.cur_path = root_disk_path;
151                         info.scan.excluded = true;
152                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
153                 }
154                 *root_ret = NULL;
155                 return 0;
156         }
157
158         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
159             && progress_func)
160         {
161                 union wimlib_progress_info info;
162                 info.scan.cur_path = root_disk_path;
163                 info.scan.excluded = false;
164                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
165         }
166
167         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
168                 stat_fn = stat;
169         else
170                 stat_fn = lstat;
171
172         ret = (*stat_fn)(root_disk_path, &root_stbuf);
173         if (ret != 0) {
174                 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
175                 return WIMLIB_ERR_STAT;
176         }
177
178         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
179               !S_ISDIR(root_stbuf.st_mode))
180         {
181                 /* Do a dereference-stat in case the root is a symbolic link.
182                  * This case is allowed, provided that the symbolic link points
183                  * to a directory. */
184                 ret = stat(root_disk_path, &root_stbuf);
185                 if (ret != 0) {
186                         ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
187                         return WIMLIB_ERR_STAT;
188                 }
189                 if (!S_ISDIR(root_stbuf.st_mode)) {
190                         ERROR("`%s' is not a directory", root_disk_path);
191                         return WIMLIB_ERR_NOTDIR;
192                 }
193         }
194         if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
195             && !S_ISLNK(root_stbuf.st_mode)) {
196                 ERROR("`%s' is not a regular file, directory, or symbolic link.",
197                       root_disk_path);
198                 return WIMLIB_ERR_SPECIAL_FILE;
199         }
200
201         root = new_dentry_with_timeless_inode(path_basename(root_disk_path));
202         if (!root) {
203                 if (errno == EILSEQ)
204                         return WIMLIB_ERR_INVALID_UTF8_STRING;
205                 else if (errno == ENOMEM)
206                         return WIMLIB_ERR_NOMEM;
207                 else
208                         return WIMLIB_ERR_ICONV_NOT_AVAILABLE;
209         }
210
211         inode = root->d_inode;
212
213 #ifdef HAVE_STAT_NANOSECOND_PRECISION
214         inode->i_creation_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
215         inode->i_last_write_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
216         inode->i_last_access_time = timespec_to_wim_timestamp(&root_stbuf.st_atim);
217 #else
218         inode->i_creation_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
219         inode->i_last_write_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
220         inode->i_last_access_time = unix_timestamp_to_wim(root_stbuf.st_atime);
221 #endif
222         if (sizeof(ino_t) >= 8)
223                 inode->i_ino = (u64)root_stbuf.st_ino;
224         else
225                 inode->i_ino = (u64)root_stbuf.st_ino |
226                                    ((u64)root_stbuf.st_dev << ((sizeof(ino_t) * 8) & 63));
227         inode->i_resolved = 1;
228         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
229                 ret = inode_set_unix_data(inode, root_stbuf.st_uid,
230                                           root_stbuf.st_gid,
231                                           root_stbuf.st_mode,
232                                           lookup_table,
233                                           UNIX_DATA_ALL | UNIX_DATA_CREATE);
234                 if (ret)
235                         goto out;
236         }
237         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
238         if (S_ISREG(root_stbuf.st_mode)) { /* Archiving a regular file */
239
240                 struct wim_lookup_table_entry *lte;
241                 u8 hash[SHA1_HASH_SIZE];
242
243                 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
244
245                 /* Empty files do not have to have a lookup table entry. */
246                 if (root_stbuf.st_size == 0)
247                         goto out;
248
249                 /* For each regular file, we must check to see if the file is in
250                  * the lookup table already; if it is, we increment its refcnt;
251                  * otherwise, we create a new lookup table entry and insert it.
252                  * */
253
254                 ret = sha1sum(root_disk_path, hash);
255                 if (ret != 0)
256                         goto out;
257
258                 lte = __lookup_resource(lookup_table, hash);
259                 if (lte) {
260                         lte->refcnt++;
261                         DEBUG("Add lte reference %u for `%s'", lte->refcnt,
262                               root_disk_path);
263                 } else {
264                         char *file_on_disk = STRDUP(root_disk_path);
265                         if (!file_on_disk) {
266                                 ERROR("Failed to allocate memory for file path");
267                                 ret = WIMLIB_ERR_NOMEM;
268                                 goto out;
269                         }
270                         lte = new_lookup_table_entry();
271                         if (!lte) {
272                                 FREE(file_on_disk);
273                                 ret = WIMLIB_ERR_NOMEM;
274                                 goto out;
275                         }
276                         lte->file_on_disk = file_on_disk;
277                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
278                         lte->resource_entry.original_size = root_stbuf.st_size;
279                         lte->resource_entry.size = root_stbuf.st_size;
280                         copy_hash(lte->hash, hash);
281                         lookup_table_insert(lookup_table, lte);
282                 }
283                 root->d_inode->i_lte = lte;
284         } else if (S_ISDIR(root_stbuf.st_mode)) { /* Archiving a directory */
285
286                 inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
287
288                 DIR *dir;
289                 struct dirent entry, *result;
290                 struct wim_dentry *child;
291
292                 dir = opendir(root_disk_path);
293                 if (!dir) {
294                         ERROR_WITH_ERRNO("Failed to open the directory `%s'",
295                                          root_disk_path);
296                         ret = WIMLIB_ERR_OPEN;
297                         goto out;
298                 }
299
300                 /* Buffer for names of files in directory. */
301                 size_t len = strlen(root_disk_path);
302                 char name[len + 1 + FILENAME_MAX + 1];
303                 memcpy(name, root_disk_path, len);
304                 name[len] = '/';
305
306                 /* Create a dentry for each entry in the directory on disk, and recurse
307                  * to any subdirectories. */
308                 while (1) {
309                         errno = 0;
310                         ret = readdir_r(dir, &entry, &result);
311                         if (ret != 0) {
312                                 ret = WIMLIB_ERR_READ;
313                                 ERROR_WITH_ERRNO("Error reading the "
314                                                  "directory `%s'",
315                                                  root_disk_path);
316                                 break;
317                         }
318                         if (result == NULL)
319                                 break;
320                         if (result->d_name[0] == '.' && (result->d_name[1] == '\0'
321                               || (result->d_name[1] == '.' && result->d_name[2] == '\0')))
322                                         continue;
323                         strcpy(name + len + 1, result->d_name);
324                         ret = build_dentry_tree(&child, name, lookup_table,
325                                                 NULL, config, add_image_flags,
326                                                 progress_func, NULL);
327                         if (ret != 0)
328                                 break;
329                         if (child)
330                                 dentry_add_child(root, child);
331                 }
332                 closedir(dir);
333         } else { /* Archiving a symbolic link */
334                 inode->i_attributes = FILE_ATTRIBUTE_REPARSE_POINT;
335                 inode->i_reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
336
337                 /* The idea here is to call readlink() to get the UNIX target of
338                  * the symbolic link, then turn the target into a reparse point
339                  * data buffer that contains a relative or absolute symbolic
340                  * link (NOT a junction point or *full* path symbolic link with
341                  * drive letter).
342                  */
343
344                 char deref_name_buf[4096];
345                 ssize_t deref_name_len;
346
347                 deref_name_len = readlink(root_disk_path, deref_name_buf,
348                                           sizeof(deref_name_buf) - 1);
349                 if (deref_name_len >= 0) {
350                         deref_name_buf[deref_name_len] = '\0';
351                         DEBUG("Read symlink `%s'", deref_name_buf);
352                         ret = inode_set_symlink(root->d_inode, deref_name_buf,
353                                                 lookup_table, NULL);
354                         if (ret == 0) {
355                                 /*
356                                  * Unfortunately, Windows seems to have the
357                                  * concept of "file" symbolic links as being
358                                  * different from "directory" symbolic links...
359                                  * so FILE_ATTRIBUTE_DIRECTORY needs to be set
360                                  * on the symbolic link if the *target* of the
361                                  * symbolic link is a directory.
362                                  */
363                                 struct stat stbuf;
364                                 if (stat(root_disk_path, &stbuf) == 0 &&
365                                     S_ISDIR(stbuf.st_mode))
366                                 {
367                                         inode->i_attributes |= FILE_ATTRIBUTE_DIRECTORY;
368                                 }
369                         }
370                 } else {
371                         ERROR_WITH_ERRNO("Failed to read target of "
372                                          "symbolic link `%s'", root_disk_path);
373                         ret = WIMLIB_ERR_READLINK;
374                 }
375         }
376 out:
377         if (ret == 0)
378                 *root_ret = root;
379         else
380                 free_dentry_tree(root, lookup_table);
381         return ret;
382 }
383
384
385 enum pattern_type {
386         NONE = 0,
387         EXCLUSION_LIST,
388         EXCLUSION_EXCEPTION,
389         COMPRESSION_EXCLUSION_LIST,
390         ALIGNMENT_LIST,
391 };
392
393 #define COMPAT_DEFAULT_CONFIG
394
395 /* Default capture configuration file when none is specified. */
396 static const char *default_config =
397 #ifdef COMPAT_DEFAULT_CONFIG /* XXX: This policy is being moved to library
398                                 users.  The next ABI-incompatible library
399                                 version will default to the empty string here. */
400 "[ExclusionList]\n"
401 "\\$ntfs.log\n"
402 "\\hiberfil.sys\n"
403 "\\pagefile.sys\n"
404 "\\System Volume Information\n"
405 "\\RECYCLER\n"
406 "\\Windows\\CSC\n"
407 "\n"
408 "[CompressionExclusionList]\n"
409 "*.mp3\n"
410 "*.zip\n"
411 "*.cab\n"
412 "\\WINDOWS\\inf\\*.pnf\n";
413 #else
414 "";
415 #endif
416
417 static void destroy_pattern_list(struct pattern_list *list)
418 {
419         FREE(list->pats);
420 }
421
422 static void destroy_capture_config(struct capture_config *config)
423 {
424         destroy_pattern_list(&config->exclusion_list);
425         destroy_pattern_list(&config->exclusion_exception);
426         destroy_pattern_list(&config->compression_exclusion_list);
427         destroy_pattern_list(&config->alignment_list);
428         FREE(config->config_str);
429         FREE(config->prefix);
430         memset(config, 0, sizeof(*config));
431 }
432
433 static int pattern_list_add_pattern(struct pattern_list *list,
434                                     const char *pattern)
435 {
436         const char **pats;
437         if (list->num_pats >= list->num_allocated_pats) {
438                 pats = REALLOC(list->pats,
439                                sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
440                 if (!pats)
441                         return WIMLIB_ERR_NOMEM;
442                 list->num_allocated_pats += 8;
443                 list->pats = pats;
444         }
445         list->pats[list->num_pats++] = pattern;
446         return 0;
447 }
448
449 /* Parses the contents of the image capture configuration file and fills in a
450  * `struct capture_config'. */
451 static int init_capture_config(const char *_config_str, size_t config_len,
452                                const char *_prefix, struct capture_config *config)
453 {
454         char *config_str;
455         char *prefix;
456         char *p;
457         char *eol;
458         char *next_p;
459         size_t bytes_remaining;
460         enum pattern_type type = NONE;
461         int ret;
462         unsigned long line_no = 0;
463
464         DEBUG("config_len = %zu", config_len);
465         bytes_remaining = config_len;
466         memset(config, 0, sizeof(*config));
467         config_str = MALLOC(config_len);
468         if (!config_str) {
469                 ERROR("Could not duplicate capture config string");
470                 return WIMLIB_ERR_NOMEM;
471         }
472         prefix = STRDUP(_prefix);
473         if (!prefix) {
474                 FREE(config_str);
475                 return WIMLIB_ERR_NOMEM;
476         }
477
478         memcpy(config_str, _config_str, config_len);
479         next_p = config_str;
480         config->config_str = config_str;
481         config->prefix = prefix;
482         config->prefix_len = strlen(prefix);
483         while (bytes_remaining) {
484                 line_no++;
485                 p = next_p;
486                 eol = memchr(p, '\n', bytes_remaining);
487                 if (!eol) {
488                         ERROR("Expected end-of-line in capture config file on "
489                               "line %lu", line_no);
490                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
491                         goto out_destroy;
492                 }
493
494                 next_p = eol + 1;
495                 bytes_remaining -= (next_p - p);
496                 if (eol == p)
497                         continue;
498
499                 if (*(eol - 1) == '\r')
500                         eol--;
501                 *eol = '\0';
502
503                 /* Translate backslash to forward slash */
504                 for (char *pp = p; pp != eol; pp++)
505                         if (*pp == '\\')
506                                 *pp = '/';
507
508                 /* Remove drive letter */
509                 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
510                         p += 2;
511
512                 ret = 0;
513                 if (strcmp(p, "[ExclusionList]") == 0)
514                         type = EXCLUSION_LIST;
515                 else if (strcmp(p, "[ExclusionException]") == 0)
516                         type = EXCLUSION_EXCEPTION;
517                 else if (strcmp(p, "[CompressionExclusionList]") == 0)
518                         type = COMPRESSION_EXCLUSION_LIST;
519                 else if (strcmp(p, "[AlignmentList]") == 0)
520                         type = ALIGNMENT_LIST;
521                 else if (p[0] == '[' && strrchr(p, ']')) {
522                         ERROR("Unknown capture configuration section `%s'", p);
523                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
524                 } else switch (type) {
525                 case EXCLUSION_LIST:
526                         DEBUG("Adding pattern \"%s\" to exclusion list", p);
527                         ret = pattern_list_add_pattern(&config->exclusion_list, p);
528                         break;
529                 case EXCLUSION_EXCEPTION:
530                         DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
531                         ret = pattern_list_add_pattern(&config->exclusion_exception, p);
532                         break;
533                 case COMPRESSION_EXCLUSION_LIST:
534                         DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
535                         ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
536                         break;
537                 case ALIGNMENT_LIST:
538                         DEBUG("Adding pattern \"%s\" to alignment list", p);
539                         ret = pattern_list_add_pattern(&config->alignment_list, p);
540                         break;
541                 default:
542                         ERROR("Line %lu of capture configuration is not "
543                               "in a block (such as [ExclusionList])",
544                               line_no);
545                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
546                         break;
547                 }
548                 if (ret != 0)
549                         goto out_destroy;
550         }
551         return 0;
552 out_destroy:
553         destroy_capture_config(config);
554         return ret;
555 }
556
557 static bool match_pattern(const char *path, const char *path_basename,
558                           const struct pattern_list *list)
559 {
560         for (size_t i = 0; i < list->num_pats; i++) {
561                 const char *pat = list->pats[i];
562                 const char *string;
563                 if (pat[0] == '/')
564                         /* Absolute path from root of capture */
565                         string = path;
566                 else {
567                         if (strchr(pat, '/'))
568                                 /* Relative path from root of capture */
569                                 string = path + 1;
570                         else
571                                 /* A file name pattern */
572                                 string = path_basename;
573                 }
574                 if (fnmatch(pat, string, FNM_PATHNAME
575                         #ifdef FNM_CASEFOLD
576                                         | FNM_CASEFOLD
577                         #endif
578                         ) == 0)
579                 {
580                         DEBUG("`%s' matches the pattern \"%s\"",
581                               string, pat);
582                         return true;
583                 }
584         }
585         return false;
586 }
587
588 /* Return true if the image capture configuration file indicates we should
589  * exclude the filename @path from capture.
590  *
591  * If @exclude_prefix is %true, the part of the path up and including the name
592  * of the directory being captured is not included in the path for matching
593  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
594  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
595  * directory.
596  */
597 bool exclude_path(const char *path, const struct capture_config *config,
598                   bool exclude_prefix)
599 {
600         const char *basename = path_basename(path);
601         if (exclude_prefix) {
602                 wimlib_assert(strlen(path) >= config->prefix_len);
603                 if (memcmp(config->prefix, path, config->prefix_len) == 0
604                      && path[config->prefix_len] == '/')
605                         path += config->prefix_len;
606         }
607         return match_pattern(path, basename, &config->exclusion_list) &&
608                 !match_pattern(path, basename, &config->exclusion_exception);
609
610 }
611
612 /* Strip leading and trailing forward slashes from a string.  Modifies it in
613  * place and returns the stripped string. */
614 static const char *canonicalize_target_path(char *target_path)
615 {
616         char *p;
617         if (target_path == NULL)
618                 target_path = "";
619         for (;;) {
620                 if (*target_path == '\0')
621                         return target_path;
622                 else if (*target_path == '/')
623                         target_path++;
624                 else
625                         break;
626         }
627
628         p = target_path + strlen(target_path) - 1;
629         while (*p == '/')
630                 *p-- = '\0';
631         return target_path;
632 }
633
634 /* Strip leading and trailing slashes from the target paths */
635 static void canonicalize_targets(struct wimlib_capture_source *sources,
636                                  size_t num_sources)
637 {
638         while (num_sources--) {
639                 DEBUG("Canonicalizing { source: \"%s\", target=\"%s\"}",
640                       sources->fs_source_path,
641                       sources->wim_target_path);
642                 sources->wim_target_path =
643                         (char*)canonicalize_target_path(sources->wim_target_path);
644                 DEBUG("\"%s\"", sources->wim_target_path);
645                 sources++;
646         }
647 }
648
649 static int capture_source_cmp(const void *p1, const void *p2)
650 {
651         const struct wimlib_capture_source *s1, *s2;
652
653         s1 = p1;
654         s2 = p2;
655         return strcmp(s1->wim_target_path, s2->wim_target_path);
656 }
657
658 /* Sorts the capture sources lexicographically by target path.  This occurs
659  * after leading and trailing forward slashes are stripped.
660  *
661  * One purpose of this is to make sure that target paths that are inside other
662  * target paths are extracted after the containing target paths. */
663 static void sort_sources(struct wimlib_capture_source *sources,
664                          size_t num_sources)
665 {
666         qsort(sources, num_sources, sizeof(sources[0]), capture_source_cmp);
667 }
668
669 static int check_sorted_sources(struct wimlib_capture_source *sources,
670                                 size_t num_sources, int add_image_flags)
671 {
672         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
673                 if (num_sources != 1) {
674                         ERROR("Must specify exactly 1 capture source "
675                               "(the NTFS volume) in NTFS mode!");
676                         return WIMLIB_ERR_INVALID_PARAM;
677                 }
678                 if (sources[0].wim_target_path[0] != '\0') {
679                         ERROR("In NTFS capture mode the target path inside "
680                               "the image must be the root directory!");
681                         return WIMLIB_ERR_INVALID_PARAM;
682                 }
683         } else if (num_sources != 0) {
684                 /* This code is disabled because the current code
685                  * unconditionally attempts to do overlays.  So, duplicate
686                  * target paths are OK. */
687         #if 0
688                 if (num_sources > 1 && sources[0].wim_target_path[0] == '\0') {
689                         ERROR("Cannot specify root target when using multiple "
690                               "capture sources!");
691                         return WIMLIB_ERR_INVALID_PARAM;
692                 }
693                 for (size_t i = 0; i < num_sources - 1; i++) {
694                         size_t len = strlen(sources[i].wim_target_path);
695                         size_t j = i + 1;
696                         const char *target1 = sources[i].wim_target_path;
697                         do {
698                                 const char *target2 = sources[j].wim_target_path;
699                                 DEBUG("target1=%s, target2=%s",
700                                       target1,target2);
701                                 if (strncmp(target1, target2, len) ||
702                                     target2[len] > '/')
703                                         break;
704                                 if (target2[len] == '/') {
705                                         ERROR("Invalid target `%s': is a prefix of `%s'",
706                                               target1, target2);
707                                         return WIMLIB_ERR_INVALID_PARAM;
708                                 }
709                                 if (target2[len] == '\0') {
710                                         ERROR("Invalid target `%s': is a duplicate of `%s'",
711                                               target1, target2);
712                                         return WIMLIB_ERR_INVALID_PARAM;
713                                 }
714                         } while (++j != num_sources);
715                 }
716         #endif
717         }
718         return 0;
719
720 }
721
722 /* Creates a new directory to place in the WIM image.  This is to create parent
723  * directories that are not part of any target as needed.  */
724 static struct wim_dentry *
725 new_filler_directory(const char *name)
726 {
727         struct wim_dentry *dentry;
728         DEBUG("Creating filler directory \"%s\"", name);
729         dentry = new_dentry_with_inode(name);
730         if (dentry) {
731                 dentry->d_inode->i_ino = 0;
732                 dentry->d_inode->i_resolved = 1;
733                 dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
734         }
735         return dentry;
736 }
737
738 /* Transfers the children of @branch to @target.  It is an error if @target is
739  * not a directory or if both @branch and @target contain a child dentry with
740  * the same name. */
741 static int do_overlay(struct wim_dentry *target,
742                       struct wim_dentry *branch)
743 {
744         struct rb_root *rb_root;
745
746         if (!dentry_is_directory(target)) {
747                 ERROR("Cannot overlay directory `%s' over non-directory",
748                       branch->file_name_utf8);
749                 /* XXX Use a different error code */
750                 return WIMLIB_ERR_INVALID_DENTRY;
751         }
752
753         rb_root = &branch->d_inode->i_children;
754         while (rb_root->rb_node) { /* While @branch has children... */
755                 struct wim_dentry *child;
756
757                 child = container_of(rb_root->rb_node, struct wim_dentry, rb_node);
758                 unlink_dentry(child);
759                 if (!dentry_add_child(target, child)) {
760                         dentry_add_child(branch, child);
761                         ERROR("Overlay error: file `%s' already exists as child of `%s'",
762                               child->file_name_utf8, target->file_name_utf8);
763                         return WIMLIB_ERR_INVALID_DENTRY;
764                 }
765         }
766         return 0;
767
768 }
769
770 /* Attach or overlay a branch onto the WIM image.
771  *
772  * @root_p:
773  *      Pointer to the root of the WIM image, or pointer to NULL if it has not
774  *      been created yet.
775  * @branch
776  *      Branch to add.
777  * @target_path:
778  *      Path in the WIM image to add the branch.
779  */
780 static int attach_branch(struct wim_dentry **root_p,
781                          struct wim_dentry *branch,
782                          char *target_path)
783 {
784         char *slash;
785         struct wim_dentry *dentry, *parent, *target;
786
787         if (*target_path == '\0') {
788                 /* Target: root directory */
789                 if (*root_p) {
790                         /* Overlay on existing root */
791                         return do_overlay(*root_p, branch);
792                 } else  {
793                         /* Set as root */
794                         *root_p = branch;
795                         return 0;
796                 }
797         }
798
799         /* Adding a non-root branch.  Create root if it hasn't been created
800          * already. */
801         if (!*root_p) {
802                 *root_p = new_filler_directory("");
803                 if (!*root_p)
804                         return WIMLIB_ERR_NOMEM;
805         }
806
807         /* Walk the path to the branch, creating filler directories as needed.
808          * */
809         parent = *root_p;
810         while ((slash = strchr(target_path, '/'))) {
811                 *slash = '\0';
812                 dentry = get_dentry_child_with_name(parent, target_path);
813                 if (!dentry) {
814                         dentry = new_filler_directory(target_path);
815                         if (!dentry)
816                                 return WIMLIB_ERR_NOMEM;
817                         dentry_add_child(parent, dentry);
818                 }
819                 parent = dentry;
820                 target_path = slash;
821                 do {
822                         ++target_path;
823                         wimlib_assert(*target_path != '\0');
824                 } while (*target_path == '/');
825         }
826
827         /* If the target path already existed, overlay the branch onto it.
828          * Otherwise, set the branch as the target path. */
829         target = get_dentry_child_with_name(parent, branch->file_name_utf8);
830         if (target) {
831                 return do_overlay(target, branch);
832         } else {
833                 dentry_add_child(parent, branch);
834                 return 0;
835         }
836 }
837
838 WIMLIBAPI int wimlib_add_image_multisource(WIMStruct *w,
839                                            struct wimlib_capture_source *sources,
840                                            size_t num_sources,
841                                            const char *name,
842                                            const char *config_str,
843                                            size_t config_len,
844                                            int add_image_flags,
845                                            wimlib_progress_func_t progress_func)
846 {
847         int (*capture_tree)(struct wim_dentry **, const char *,
848                             struct wim_lookup_table *,
849                             struct wim_security_data *,
850                             const struct capture_config *,
851                             int, wimlib_progress_func_t, void *);
852         void *extra_arg;
853         struct wim_dentry *root_dentry = NULL;
854         struct wim_security_data *sd;
855         struct capture_config config;
856         struct wim_image_metadata *imd;
857         int ret;
858
859         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
860 #ifdef WITH_NTFS_3G
861                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
862                         ERROR("Cannot dereference files when capturing directly from NTFS");
863                         return WIMLIB_ERR_INVALID_PARAM;
864                 }
865                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
866                         ERROR("Capturing UNIX owner and mode not supported "
867                               "when capturing directly from NTFS");
868                         return WIMLIB_ERR_INVALID_PARAM;
869                 }
870                 capture_tree = build_dentry_tree_ntfs;
871                 extra_arg = &w->ntfs_vol;
872 #else
873                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
874                       "        cannot capture a WIM image directly from a NTFS volume!");
875                 return WIMLIB_ERR_UNSUPPORTED;
876 #endif
877         } else {
878                 capture_tree = build_dentry_tree;
879                 extra_arg = NULL;
880         }
881
882         if (!name || !*name) {
883                 ERROR("Must specify a non-empty string for the image name");
884                 return WIMLIB_ERR_INVALID_PARAM;
885         }
886
887         if (w->hdr.total_parts != 1) {
888                 ERROR("Cannot add an image to a split WIM");
889                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
890         }
891
892         if (wimlib_image_name_in_use(w, name)) {
893                 ERROR("There is already an image named \"%s\" in `%s'",
894                       name, w->filename);
895                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
896         }
897
898         if (!config_str) {
899                 DEBUG("Using default capture configuration");
900                 config_str = default_config;
901                 config_len = strlen(default_config);
902         }
903         memset(&config, 0, sizeof(struct capture_config));
904
905         DEBUG("Allocating security data");
906
907         sd = CALLOC(1, sizeof(struct wim_security_data));
908         if (!sd) {
909                 ret = WIMLIB_ERR_NOMEM;
910                 goto out_destroy_config;
911         }
912         sd->total_length = 8;
913         sd->refcnt = 1;
914
915         DEBUG("Using %zu capture sources", num_sources);
916         canonicalize_targets(sources, num_sources);
917         sort_sources(sources, num_sources);
918         ret = check_sorted_sources(sources, num_sources, add_image_flags);
919         if (ret) {
920                 ret = WIMLIB_ERR_INVALID_PARAM;
921                 goto out_free_security_data;
922         }
923
924         DEBUG("Building dentry tree.");
925         if (num_sources == 0) {
926                 root_dentry = new_filler_directory("");
927                 if (!root_dentry)
928                         goto out_free_security_data;
929         } else {
930                 size_t i = 0;
931                 struct wim_dentry *branch;
932                 int flags;
933                 do {
934                         DEBUG("Building dentry tree for source %zu of %zu "
935                               "(\"%s\" => \"%s\")", i + 1, num_sources,
936                               sources[i].fs_source_path,
937                               sources[i].wim_target_path);
938                         union wimlib_progress_info progress;
939                         if (progress_func) {
940                                 memset(&progress, 0, sizeof(progress));
941                                 progress.scan.source = sources[i].fs_source_path;
942                                 progress.scan.wim_target_path = sources[i].wim_target_path;
943                                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
944                         }
945                         ret = init_capture_config(config_str, config_len,
946                                                   sources[i].fs_source_path,
947                                                   &config);
948                         if (ret)
949                                 goto out_free_dentry_tree;
950                         flags = add_image_flags | WIMLIB_ADD_IMAGE_FLAG_SOURCE;
951                         if (!*sources[i].wim_target_path)
952                                 flags |= WIMLIB_ADD_IMAGE_FLAG_ROOT;
953                         ret = (*capture_tree)(&branch, sources[i].fs_source_path,
954                                               w->lookup_table, sd,
955                                               &config,
956                                               flags,
957                                               progress_func, extra_arg);
958                         if (ret) {
959                                 ERROR("Failed to build dentry tree for `%s'",
960                                       sources[i].fs_source_path);
961                                 goto out_free_dentry_tree;
962                         }
963                         if (branch) {
964                                 ret = set_dentry_name(branch,
965                                                       path_basename(sources[i].wim_target_path));
966                                 if (ret) {
967                                         free_dentry_tree(branch, w->lookup_table);
968                                         goto out_free_dentry_tree;
969                                 }
970
971                                 ret = attach_branch(&root_dentry, branch,
972                                                     sources[i].wim_target_path);
973                                 if (ret) {
974                                         free_dentry_tree(branch, w->lookup_table);
975                                         goto out_free_dentry_tree;
976                                 }
977                         }
978                         destroy_capture_config(&config);
979                         if (progress_func)
980                                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
981                 } while (++i != num_sources);
982         }
983
984         DEBUG("Calculating full paths of dentries.");
985         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
986         if (ret != 0)
987                 goto out_free_dentry_tree;
988
989         ret = add_new_dentry_tree(w, root_dentry, sd);
990         if (ret != 0)
991                 goto out_free_dentry_tree;
992
993         imd = &w->image_metadata[w->hdr.image_count - 1];
994
995         ret = dentry_tree_fix_inodes(root_dentry, &imd->inode_list);
996         if (ret != 0)
997                 goto out_destroy_imd;
998
999         DEBUG("Assigning hard link group IDs");
1000         assign_inode_numbers(&imd->inode_list);
1001
1002         ret = xml_add_image(w, name);
1003         if (ret != 0)
1004                 goto out_destroy_imd;
1005
1006         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
1007                 wimlib_set_boot_idx(w, w->hdr.image_count);
1008         ret = 0;
1009         goto out;
1010 out_destroy_imd:
1011         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
1012                                w->lookup_table);
1013         w->hdr.image_count--;
1014         return ret;
1015 out_free_dentry_tree:
1016         free_dentry_tree(root_dentry, w->lookup_table);
1017 out_free_security_data:
1018         free_security_data(sd);
1019 out_destroy_config:
1020         destroy_capture_config(&config);
1021 out:
1022         return ret;
1023 }
1024
1025 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *source,
1026                                const char *name, const char *config_str,
1027                                size_t config_len, int add_image_flags,
1028                                wimlib_progress_func_t progress_func)
1029 {
1030         if (!source || !*source)
1031                 return WIMLIB_ERR_INVALID_PARAM;
1032
1033         char *fs_source_path = STRDUP(source);
1034         int ret;
1035         struct wimlib_capture_source capture_src = {
1036                 .fs_source_path = fs_source_path,
1037                 .wim_target_path = NULL,
1038                 .reserved = 0,
1039         };
1040         ret = wimlib_add_image_multisource(w, &capture_src, 1, name,
1041                                            config_str, config_len,
1042                                            add_image_flags, progress_func);
1043         FREE(fs_source_path);
1044         return ret;
1045 }