Win32 fixes
[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 "config.h"
25
26 #if defined(__CYGWIN__) || defined(__WIN32__)
27 #       include <windows.h>
28 #       include <ntdef.h>
29 #       include <wchar.h>
30 #       ifdef ERROR
31 #               undef ERROR
32 #       endif
33 #       include "security.h"
34 #else
35 #       include <dirent.h>
36 #       include <sys/stat.h>
37 #       include "timestamp.h"
38 #endif
39
40 #include "wimlib_internal.h"
41 #include "dentry.h"
42 #include "lookup_table.h"
43 #include "xml.h"
44 #include <ctype.h>
45 #include <errno.h>
46 #include <fnmatch.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50
51 #ifdef HAVE_ALLOCA_H
52 #include <alloca.h>
53 #endif
54
55 #define WIMLIB_ADD_IMAGE_FLAG_ROOT      0x80000000
56 #define WIMLIB_ADD_IMAGE_FLAG_SOURCE    0x40000000
57
58 /*
59  * Adds the dentry tree and security data for a new image to the image metadata
60  * array of the WIMStruct.
61  */
62 int add_new_dentry_tree(WIMStruct *w, struct wim_dentry *root_dentry,
63                         struct wim_security_data *sd)
64 {
65         struct wim_lookup_table_entry *metadata_lte;
66         struct wim_image_metadata *imd;
67         struct wim_image_metadata *new_imd;
68
69         wimlib_assert(root_dentry != NULL);
70
71         DEBUG("Reallocating image metadata array for image_count = %u",
72               w->hdr.image_count + 1);
73         imd = CALLOC((w->hdr.image_count + 1), sizeof(struct wim_image_metadata));
74
75         if (!imd) {
76                 ERROR("Failed to allocate memory for new image metadata array");
77                 goto err;
78         }
79
80         memcpy(imd, w->image_metadata,
81                w->hdr.image_count * sizeof(struct wim_image_metadata));
82
83         metadata_lte = new_lookup_table_entry();
84         if (!metadata_lte)
85                 goto err_free_imd;
86
87         metadata_lte->resource_entry.flags = WIM_RESHDR_FLAG_METADATA;
88         random_hash(metadata_lte->hash);
89         lookup_table_insert(w->lookup_table, metadata_lte);
90
91         new_imd = &imd[w->hdr.image_count];
92
93         new_imd->root_dentry    = root_dentry;
94         new_imd->metadata_lte   = metadata_lte;
95         new_imd->security_data  = sd;
96         new_imd->modified       = 1;
97
98         FREE(w->image_metadata);
99         w->image_metadata = imd;
100         w->hdr.image_count++;
101         return 0;
102 err_free_imd:
103         FREE(imd);
104 err:
105         return WIMLIB_ERR_NOMEM;
106
107 }
108
109 #if defined(__CYGWIN__) || defined(__WIN32__)
110
111 static u64 FILETIME_to_u64(const FILETIME *ft)
112 {
113         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
114 }
115
116
117 static int build_dentry_tree(struct wim_dentry **root_ret,
118                              const char *root_disk_path,
119                              struct wim_lookup_table *lookup_table,
120                              struct wim_security_data *sd,
121                              const struct capture_config *config,
122                              int add_image_flags,
123                              wimlib_progress_func_t progress_func,
124                              void *extra_arg);
125
126 static int win32_get_short_name(struct wim_dentry *dentry,
127                                 const wchar_t *path_utf16)
128 {
129         WIN32_FIND_DATAW dat;
130         if (FindFirstFileW(path_utf16, &dat) &&
131             dat.cAlternateFileName[0] != L'\0')
132         {
133                 size_t short_name_len = wcslen(dat.cAlternateFileName) * 2;
134                 size_t n = short_name_len + sizeof(wchar_t);
135                 dentry->short_name = MALLOC(n);
136                 if (!dentry->short_name)
137                         return WIMLIB_ERR_NOMEM;
138                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
139                 dentry->short_name_len = short_name_len;
140         }
141         return 0;
142 }
143
144 static int win32_get_security_descriptor(struct wim_dentry *dentry,
145                                          struct sd_set *sd_set,
146                                          const wchar_t *path_utf16)
147 {
148         SECURITY_INFORMATION requestedInformation;
149         DWORD lenNeeded = 0;
150         BOOL status;
151         DWORD err;
152
153         requestedInformation = DACL_SECURITY_INFORMATION |
154                                SACL_SECURITY_INFORMATION |
155                                OWNER_SECURITY_INFORMATION |
156                                GROUP_SECURITY_INFORMATION;
157         /* Request length of security descriptor */
158         status = GetFileSecurityW(path_utf16, requestedInformation,
159                                   NULL, 0, &lenNeeded);
160         err = GetLastError();
161         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
162                 DWORD len = lenNeeded;
163                 char buf[len];
164                 if (GetFileSecurityW(path_utf16, requestedInformation,
165                                      buf, len, &lenNeeded))
166                 {
167                         int security_id = sd_set_add_sd(sd_set, buf, len);
168                         if (security_id < 0)
169                                 return WIMLIB_ERR_NOMEM;
170                         else {
171                                 dentry->d_inode->i_security_id = security_id;
172                                 return 0;
173                         }
174                 } else {
175                         err = GetLastError();
176                 }
177         }
178         ERROR("Win32 API: Failed to read security descriptor of \"%ls\"",
179               path_utf16);
180         win32_error(err);
181         return WIMLIB_ERR_READ;
182 }
183
184 /* Reads the directory entries of directory using a Win32 API and recursively
185  * calls build_dentry_tree() on them. */
186 static int win32_recurse_directory(struct wim_dentry *root,
187                                    const char *root_disk_path,
188                                    struct wim_lookup_table *lookup_table,
189                                    struct wim_security_data *sd,
190                                    const struct capture_config *config,
191                                    int add_image_flags,
192                                    wimlib_progress_func_t progress_func,
193                                    struct sd_set *sd_set,
194                                    const wchar_t *path_utf16,
195                                    size_t path_utf16_nchars)
196 {
197         WIN32_FIND_DATAW dat;
198         HANDLE hFind;
199         DWORD err;
200         int ret;
201
202         {
203                 /* Begin reading the directory by calling FindFirstFileW.
204                  * Unlink UNIX opendir(), FindFirstFileW has file globbing built
205                  * into it.  But this isn't what we actually want, so just add a
206                  * dummy glob to get all entries. */
207                 wchar_t pattern_buf[path_utf16_nchars + 3];
208                 memcpy(pattern_buf, path_utf16,
209                        path_utf16_nchars * sizeof(wchar_t));
210                 pattern_buf[path_utf16_nchars] = L'/';
211                 pattern_buf[path_utf16_nchars + 1] = L'*';
212                 pattern_buf[path_utf16_nchars + 2] = L'\0';
213                 hFind = FindFirstFileW(pattern_buf, &dat);
214         }
215         if (hFind == INVALID_HANDLE_VALUE) {
216                 err = GetLastError();
217                 if (err == ERROR_FILE_NOT_FOUND) {
218                         return 0;
219                 } else {
220                         ERROR("Win32 API: Failed to read directory \"%s\"",
221                               root_disk_path);
222                         win32_error(err);
223                         return WIMLIB_ERR_READ;
224                 }
225         }
226         ret = 0;
227         do {
228                 /* Skip . and .. entries */
229                 if (!(dat.cFileName[0] == L'.' &&
230                       (dat.cFileName[1] == L'\0' ||
231                        (dat.cFileName[1] == L'.' && dat.cFileName[2] == L'\0'))))
232                 {
233                         struct wim_dentry *child;
234
235                         char *utf8_name;
236                         size_t utf8_name_nbytes;
237                         ret = utf16_to_utf8((const char*)dat.cFileName,
238                                             wcslen(dat.cFileName) * sizeof(wchar_t),
239                                             &utf8_name,
240                                             &utf8_name_nbytes);
241                         if (ret)
242                                 goto out_find_close;
243
244                         char name[strlen(root_disk_path) + 1 + utf8_name_nbytes + 1];
245                         sprintf(name, "%s/%s", root_disk_path, utf8_name);
246                         FREE(utf8_name);
247                         ret = build_dentry_tree(&child, name, lookup_table,
248                                                 sd, config, add_image_flags,
249                                                 progress_func, sd_set);
250                         if (ret)
251                                 goto out_find_close;
252                         if (child)
253                                 dentry_add_child(root, child);
254                 }
255         } while (FindNextFileW(hFind, &dat));
256         err = GetLastError();
257         if (err != ERROR_NO_MORE_FILES) {
258                 ERROR("Win32 API: Failed to read directory \"%s\"", root_disk_path);
259                 win32_error(err);
260                 if (ret == 0)
261                         ret = WIMLIB_ERR_READ;
262         }
263 out_find_close:
264         FindClose(hFind);
265         return ret;
266 }
267
268 /* Load a reparse point into a WIM inode.  It is just stored in memory.
269  *
270  * @hFile:  Open handle to a reparse point, with permission to read the reparse
271  *          data.
272  *
273  * @inode:  WIM inode for the reparse point.
274  *
275  * @lookup_table:  Stream lookup table for the WIM; an entry will be added to it
276  *                 for the reparse point unless an entry already exists for
277  *                 the exact same data stream.
278  *
279  * @path:  External path to the parse point (UTF-8).  Used for error messages
280  *         only.
281  *
282  * Returns 0 on success; nonzero on failure. */
283 static int win32_capture_reparse_point(HANDLE hFile,
284                                        struct wim_inode *inode,
285                                        struct wim_lookup_table *lookup_table,
286                                        const char *path)
287 {
288         /* "Reparse point data, including the tag and optional GUID,
289          * cannot exceed 16 kilobytes." - MSDN  */
290         char reparse_point_buf[16 * 1024];
291         DWORD bytesReturned;
292
293         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
294                              NULL, 0, reparse_point_buf,
295                              sizeof(reparse_point_buf), &bytesReturned, NULL))
296         {
297                 DWORD err = GetLastError();
298                 ERROR("Win32 API: Failed to get reparse data of \"%s\"", path);
299                 win32_error(err);
300                 return WIMLIB_ERR_READ;
301         }
302         if (bytesReturned < 8) {
303                 ERROR("Reparse data on \"%s\" is invalid", path);
304                 return WIMLIB_ERR_READ;
305         }
306         inode->i_reparse_tag = *(u32*)reparse_point_buf;
307         return inode_add_ads_with_data(inode, "",
308                                        (const u8*)reparse_point_buf + 8,
309                                        bytesReturned - 8, lookup_table);
310 }
311
312 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
313  * an unnamed or named data stream.
314  *
315  * @path:       Path to the file, with the stream noted at the end for named
316  *              streams.  UTF-16LE encoding.
317  *
318  * @hash:       On success, the SHA1 message digest of the stream is written to
319  *              this location.
320  *
321  * Returns 0 on success; nonzero on failure.
322  */
323 static int win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
324 {
325         HANDLE hFile;
326         SHA_CTX ctx;
327         u8 buf[32768];
328         DWORD bytesRead;
329         int ret;
330
331         hFile = win32_open_file_readonly(path);
332         if (hFile == INVALID_HANDLE_VALUE)
333                 return WIMLIB_ERR_OPEN;
334
335         sha1_init(&ctx);
336         for (;;) {
337                 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
338                         ret = WIMLIB_ERR_READ;
339                         goto out_close_handle;
340                 }
341                 if (bytesRead == 0)
342                         break;
343                 sha1_update(&ctx, buf, bytesRead);
344         }
345         ret = 0;
346         sha1_final(hash, &ctx);
347 out_close_handle:
348         CloseHandle(hFile);
349         return ret;
350 }
351
352 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
353  * stream); calculates its SHA1 message digest and either creates a `struct
354  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
355  * wim_lookup_table_entry' for an identical stream.
356  *
357  * @path_utf16:         Path to the file (UTF-16LE).
358  *
359  * @path_utf16_nchars:  Number of 2-byte characters in @path_utf16.
360  *
361  * @inode:              WIM inode to save the stream into.
362  *
363  * @lookup_table:       Stream lookup table for the WIM.
364  *
365  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
366  *                      stream name.
367  *
368  * Returns 0 on success; nonzero on failure.
369  */
370 static int win32_capture_stream(const wchar_t *path_utf16,
371                                 size_t path_utf16_nchars,
372                                 struct wim_inode *inode,
373                                 struct wim_lookup_table *lookup_table,
374                                 WIN32_FIND_STREAM_DATA *dat)
375 {
376         struct wim_ads_entry *ads_entry;
377         u8 hash[SHA1_HASH_SIZE];
378         struct wim_lookup_table_entry *lte;
379         int ret;
380         wchar_t *p, *colon;
381         bool is_named_stream;
382         wchar_t *spath;
383         size_t spath_nchars;
384         DWORD err;
385
386         /* The stream name should be returned as :NAME:TYPE */
387         p = dat->cStreamName;
388         if (*p != L':')
389                 goto out_invalid_stream_name;
390         p += 1;
391         colon = wcschr(p, L':');
392         if (colon == NULL)
393                 goto out_invalid_stream_name;
394
395         if (wcscmp(colon + 1, L"$DATA")) {
396                 /* Not a DATA stream */
397                 ret = 0;
398                 goto out;
399         }
400
401         is_named_stream = (p != colon);
402         if (is_named_stream) {
403                 /* Allocate an ADS entry for the named stream. */
404                 char *utf8_stream_name;
405                 size_t utf8_stream_name_len;
406                 ret = utf16_to_utf8((const char *)p,
407                                     (colon - p) * sizeof(wchar_t),
408                                     &utf8_stream_name,
409                                     &utf8_stream_name_len);
410                 if (ret)
411                         goto out;
412                 ads_entry = inode_add_ads(inode, utf8_stream_name);
413                 FREE(utf8_stream_name);
414                 if (!ads_entry) {
415                         ret = WIMLIB_ERR_NOMEM;
416                         goto out;
417                 }
418         }
419
420         /* Create a UTF-16 string @spath that gives the filename, then a colon,
421          * then the stream name.  Or, if it's an unnamed stream, just the
422          * filename.  It is MALLOC()'ed so that it can be saved in the
423          * wim_lookup_table_entry if needed. */
424         *colon = '\0';
425         spath_nchars = path_utf16_nchars;
426         if (is_named_stream)
427                 spath_nchars += colon - p + 1;
428
429         spath = MALLOC((spath_nchars + 1) * sizeof(wchar_t));
430         memcpy(spath, path_utf16, path_utf16_nchars * sizeof(wchar_t));
431         if (is_named_stream) {
432                 spath[path_utf16_nchars] = L':';
433                 memcpy(&spath[path_utf16_nchars + 1], p, (colon - p) * sizeof(wchar_t));
434         }
435         spath[spath_nchars] = L'\0';
436
437         ret = win32_sha1sum(spath, hash);
438         if (ret) {
439                 err = GetLastError();
440                 ERROR("Win32 API: Failed to read \"%ls\" to calculate SHA1sum",
441                       path_utf16);
442                 win32_error(err);
443                 goto out_free_spath;
444         }
445
446         lte = __lookup_resource(lookup_table, hash);
447         if (lte) {
448                 /* Use existing wim_lookup_table_entry that has the same SHA1
449                  * message digest */
450                 lte->refcnt++;
451         } else {
452                 /* Make a new new wim_lookup_table_entry */
453                 lte = new_lookup_table_entry();
454                 if (!lte) {
455                         ret = WIMLIB_ERR_NOMEM;
456                         goto out_free_spath;
457                 }
458                 lte->file_on_disk = (char*)spath;
459                 spath = NULL;
460                 lte->resource_location = RESOURCE_WIN32;
461                 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
462                 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
463                 copy_hash(lte->hash, hash);
464                 lookup_table_insert(lookup_table, lte);
465         }
466         if (is_named_stream)
467                 ads_entry->lte = lte;
468         else
469                 inode->i_lte = lte;
470 out_free_spath:
471         FREE(spath);
472 out:
473         return ret;
474 out_invalid_stream_name:
475         ERROR("Invalid stream name: \"%ls:%ls\"", path_utf16, dat->cStreamName);
476         ret = WIMLIB_ERR_READ;
477         goto out;
478 }
479
480 /* Scans a Win32 file for unnamed and named data streams (not reparse point
481  * streams).
482  *
483  * @path_utf16:         Path to the file (UTF-16LE).
484  *
485  * @path_utf16_nchars:  Number of 2-byte characters in @path_utf16.
486  *
487  * @inode:              WIM inode to save the stream into.
488  *
489  * @lookup_table:       Stream lookup table for the WIM.
490  *
491  * Returns 0 on success; nonzero on failure.
492  */
493 static int win32_capture_streams(const wchar_t *path_utf16,
494                                  size_t path_utf16_nchars,
495                                  struct wim_inode *inode,
496                                  struct wim_lookup_table *lookup_table)
497 {
498         WIN32_FIND_STREAM_DATA dat;
499         int ret;
500         HANDLE hFind;
501         DWORD err;
502
503         hFind = FindFirstStreamW(path_utf16, FindStreamInfoStandard, &dat, 0);
504         if (hFind == INVALID_HANDLE_VALUE) {
505                 err = GetLastError();
506
507                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
508                  * points and directories */
509                 if ((inode->i_attributes &
510                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
511                     && err == ERROR_HANDLE_EOF)
512                 {
513                         return 0;
514                 } else {
515                         ERROR("Win32 API: Failed to look up data streams of \"%ls\"",
516                               path_utf16);
517                         win32_error(err);
518                         return WIMLIB_ERR_READ;
519                 }
520         }
521         do {
522                 ret = win32_capture_stream(path_utf16,
523                                            path_utf16_nchars,
524                                            inode, lookup_table,
525                                            &dat);
526                 if (ret)
527                         goto out_find_close;
528         } while (FindNextStreamW(hFind, &dat));
529         err = GetLastError();
530         if (err != ERROR_HANDLE_EOF) {
531                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path_utf16);
532                 win32_error(err);
533                 ret = WIMLIB_ERR_READ;
534         }
535 out_find_close:
536         FindClose(hFind);
537         return ret;
538 }
539 #endif
540
541 /*
542  * build_dentry_tree():
543  *      Recursively builds a tree of WIM dentries from an on-disk directory
544  *      tree.
545  *
546  * @root_ret:   Place to return a pointer to the root of the dentry tree.  Only
547  *              modified if successful.  Set to NULL if the file or directory was
548  *              excluded from capture.
549  *
550  * @root_disk_path:  The path to the root of the directory tree on disk (UTF-8).
551  *
552  * @lookup_table: The lookup table for the WIM file.  For each file added to the
553  *              dentry tree being built, an entry is added to the lookup table,
554  *              unless an identical stream is already in the lookup table.
555  *              These lookup table entries that are added point to the path of
556  *              the file on disk.
557  *
558  * @sd:         Ignored.  (Security data only captured in NTFS mode.)
559  *
560  * @capture_config:
561  *              Configuration for files to be excluded from capture.
562  *
563  * @add_flags:  Bitwise or of WIMLIB_ADD_IMAGE_FLAG_*
564  *
565  * @extra_arg:  Ignored in UNIX builds; used to pass sd_set pointer in Windows
566  *              builds.
567  *
568  * @return:     0 on success, nonzero on failure.  It is a failure if any of
569  *              the files cannot be `stat'ed, or if any of the needed
570  *              directories cannot be opened or read.  Failure to add the files
571  *              to the WIM may still occur later when trying to actually read
572  *              the on-disk files during a call to wimlib_write() or
573  *              wimlib_overwrite().
574  */
575 static int build_dentry_tree(struct wim_dentry **root_ret,
576                              const char *root_disk_path,
577                              struct wim_lookup_table *lookup_table,
578                              struct wim_security_data *sd,
579                              const struct capture_config *config,
580                              int add_image_flags,
581                              wimlib_progress_func_t progress_func,
582                              void *extra_arg)
583 {
584         struct wim_dentry *root = NULL;
585         int ret = 0;
586         struct wim_inode *inode;
587
588         if (exclude_path(root_disk_path, config, true)) {
589                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
590                         ERROR("Cannot exclude the root directory from capture");
591                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
592                         goto out;
593                 }
594                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
595                     && progress_func)
596                 {
597                         union wimlib_progress_info info;
598                         info.scan.cur_path = root_disk_path;
599                         info.scan.excluded = true;
600                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
601                 }
602                 goto out;
603         }
604
605         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
606             && progress_func)
607         {
608                 union wimlib_progress_info info;
609                 info.scan.cur_path = root_disk_path;
610                 info.scan.excluded = false;
611                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
612         }
613
614 #if !defined(__CYGWIN__) && !defined(__WIN32__)
615         /* UNIX version of capturing a directory tree */
616         struct stat root_stbuf;
617         int (*stat_fn)(const char *restrict, struct stat *restrict);
618         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
619                 stat_fn = stat;
620         else
621                 stat_fn = lstat;
622
623         ret = (*stat_fn)(root_disk_path, &root_stbuf);
624         if (ret != 0) {
625                 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
626                 goto out;
627         }
628
629         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
630               !S_ISDIR(root_stbuf.st_mode))
631         {
632                 /* Do a dereference-stat in case the root is a symbolic link.
633                  * This case is allowed, provided that the symbolic link points
634                  * to a directory. */
635                 ret = stat(root_disk_path, &root_stbuf);
636                 if (ret != 0) {
637                         ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
638                         ret = WIMLIB_ERR_STAT;
639                         goto out;
640                 }
641                 if (!S_ISDIR(root_stbuf.st_mode)) {
642                         ERROR("`%s' is not a directory", root_disk_path);
643                         ret = WIMLIB_ERR_NOTDIR;
644                         goto out;
645                 }
646         }
647         if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
648             && !S_ISLNK(root_stbuf.st_mode)) {
649                 ERROR("`%s' is not a regular file, directory, or symbolic link.",
650                       root_disk_path);
651                 ret = WIMLIB_ERR_SPECIAL_FILE;
652                 goto out;
653         }
654
655         root = new_dentry_with_timeless_inode(path_basename(root_disk_path));
656         if (!root) {
657                 if (errno == EILSEQ)
658                         ret = WIMLIB_ERR_INVALID_UTF8_STRING;
659                 else if (errno == ENOMEM)
660                         ret = WIMLIB_ERR_NOMEM;
661                 else
662                         ret = WIMLIB_ERR_ICONV_NOT_AVAILABLE;
663                 goto out;
664         }
665
666         inode = root->d_inode;
667
668 #ifdef HAVE_STAT_NANOSECOND_PRECISION
669         inode->i_creation_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
670         inode->i_last_write_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
671         inode->i_last_access_time = timespec_to_wim_timestamp(&root_stbuf.st_atim);
672 #else
673         inode->i_creation_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
674         inode->i_last_write_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
675         inode->i_last_access_time = unix_timestamp_to_wim(root_stbuf.st_atime);
676 #endif
677         if (sizeof(ino_t) >= 8)
678                 inode->i_ino = (u64)root_stbuf.st_ino;
679         else
680                 inode->i_ino = (u64)root_stbuf.st_ino |
681                                    ((u64)root_stbuf.st_dev << ((sizeof(ino_t) * 8) & 63));
682         inode->i_resolved = 1;
683         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
684                 ret = inode_set_unix_data(inode, root_stbuf.st_uid,
685                                           root_stbuf.st_gid,
686                                           root_stbuf.st_mode,
687                                           lookup_table,
688                                           UNIX_DATA_ALL | UNIX_DATA_CREATE);
689                 if (ret)
690                         goto out;
691         }
692         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
693         if (S_ISREG(root_stbuf.st_mode)) { /* Archiving a regular file */
694
695                 struct wim_lookup_table_entry *lte;
696                 u8 hash[SHA1_HASH_SIZE];
697
698                 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
699
700                 /* Empty files do not have to have a lookup table entry. */
701                 if (root_stbuf.st_size == 0)
702                         goto out;
703
704                 /* For each regular file, we must check to see if the file is in
705                  * the lookup table already; if it is, we increment its refcnt;
706                  * otherwise, we create a new lookup table entry and insert it.
707                  * */
708
709                 ret = sha1sum(root_disk_path, hash);
710                 if (ret != 0)
711                         goto out;
712
713                 lte = __lookup_resource(lookup_table, hash);
714                 if (lte) {
715                         lte->refcnt++;
716                         DEBUG("Add lte reference %u for `%s'", lte->refcnt,
717                               root_disk_path);
718                 } else {
719                         char *file_on_disk = STRDUP(root_disk_path);
720                         if (!file_on_disk) {
721                                 ERROR("Failed to allocate memory for file path");
722                                 ret = WIMLIB_ERR_NOMEM;
723                                 goto out;
724                         }
725                         lte = new_lookup_table_entry();
726                         if (!lte) {
727                                 FREE(file_on_disk);
728                                 ret = WIMLIB_ERR_NOMEM;
729                                 goto out;
730                         }
731                         lte->file_on_disk = file_on_disk;
732                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
733                         lte->resource_entry.original_size = root_stbuf.st_size;
734                         lte->resource_entry.size = root_stbuf.st_size;
735                         copy_hash(lte->hash, hash);
736                         lookup_table_insert(lookup_table, lte);
737                 }
738                 root->d_inode->i_lte = lte;
739         } else if (S_ISDIR(root_stbuf.st_mode)) { /* Archiving a directory */
740
741                 inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
742
743                 DIR *dir;
744                 struct dirent entry, *result;
745                 struct wim_dentry *child;
746
747                 dir = opendir(root_disk_path);
748                 if (!dir) {
749                         ERROR_WITH_ERRNO("Failed to open the directory `%s'",
750                                          root_disk_path);
751                         ret = WIMLIB_ERR_OPEN;
752                         goto out;
753                 }
754
755                 /* Buffer for names of files in directory. */
756                 size_t len = strlen(root_disk_path);
757                 char name[len + 1 + FILENAME_MAX + 1];
758                 memcpy(name, root_disk_path, len);
759                 name[len] = '/';
760
761                 /* Create a dentry for each entry in the directory on disk, and recurse
762                  * to any subdirectories. */
763                 while (1) {
764                         errno = 0;
765                         ret = readdir_r(dir, &entry, &result);
766                         if (ret != 0) {
767                                 ret = WIMLIB_ERR_READ;
768                                 ERROR_WITH_ERRNO("Error reading the "
769                                                  "directory `%s'",
770                                                  root_disk_path);
771                                 break;
772                         }
773                         if (result == NULL)
774                                 break;
775                         if (result->d_name[0] == '.' && (result->d_name[1] == '\0'
776                               || (result->d_name[1] == '.' && result->d_name[2] == '\0')))
777                                         continue;
778                         strcpy(name + len + 1, result->d_name);
779                         ret = build_dentry_tree(&child, name, lookup_table,
780                                                 NULL, config, add_image_flags,
781                                                 progress_func, NULL);
782                         if (ret != 0)
783                                 break;
784                         if (child)
785                                 dentry_add_child(root, child);
786                 }
787                 closedir(dir);
788         } else { /* Archiving a symbolic link */
789                 inode->i_attributes = FILE_ATTRIBUTE_REPARSE_POINT;
790                 inode->i_reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
791
792                 /* The idea here is to call readlink() to get the UNIX target of
793                  * the symbolic link, then turn the target into a reparse point
794                  * data buffer that contains a relative or absolute symbolic
795                  * link (NOT a junction point or *full* path symbolic link with
796                  * drive letter).
797                  */
798
799                 char deref_name_buf[4096];
800                 ssize_t deref_name_len;
801
802                 deref_name_len = readlink(root_disk_path, deref_name_buf,
803                                           sizeof(deref_name_buf) - 1);
804                 if (deref_name_len >= 0) {
805                         deref_name_buf[deref_name_len] = '\0';
806                         DEBUG("Read symlink `%s'", deref_name_buf);
807                         ret = inode_set_symlink(root->d_inode, deref_name_buf,
808                                                 lookup_table, NULL);
809                         if (ret == 0) {
810                                 /*
811                                  * Unfortunately, Windows seems to have the
812                                  * concept of "file" symbolic links as being
813                                  * different from "directory" symbolic links...
814                                  * so FILE_ATTRIBUTE_DIRECTORY needs to be set
815                                  * on the symbolic link if the *target* of the
816                                  * symbolic link is a directory.
817                                  */
818                                 struct stat stbuf;
819                                 if (stat(root_disk_path, &stbuf) == 0 &&
820                                     S_ISDIR(stbuf.st_mode))
821                                 {
822                                         inode->i_attributes |= FILE_ATTRIBUTE_DIRECTORY;
823                                 }
824                         }
825                 } else {
826                         ERROR_WITH_ERRNO("Failed to read target of "
827                                          "symbolic link `%s'", root_disk_path);
828                         ret = WIMLIB_ERR_READLINK;
829                 }
830         }
831 #else
832         /* Win32 version of capturing a directory tree */
833
834         wchar_t *path_utf16;
835         size_t path_utf16_nchars;
836         struct sd_set *sd_set;
837         DWORD err;
838
839         if (extra_arg == NULL) {
840                 sd_set = alloca(sizeof(struct sd_set));
841                 sd_set->rb_root.rb_node = NULL,
842                 sd_set->sd = sd;
843         } else {
844                 sd_set = extra_arg;
845         }
846
847         ret = utf8_to_utf16(root_disk_path, strlen(root_disk_path),
848                             (char**)&path_utf16, &path_utf16_nchars);
849         if (ret)
850                 goto out;
851         path_utf16_nchars /= sizeof(wchar_t);
852
853         HANDLE hFile = win32_open_file_readonly(path_utf16);
854         if (hFile == INVALID_HANDLE_VALUE) {
855                 err = GetLastError();
856                 ERROR("Win32 API: Failed to open \"%s\"", root_disk_path);
857                 win32_error(err);
858                 ret = WIMLIB_ERR_OPEN;
859                 goto out_free_path_utf16;
860         }
861
862         BY_HANDLE_FILE_INFORMATION file_info;
863         if (!GetFileInformationByHandle(hFile, &file_info)) {
864                 err = GetLastError();
865                 ERROR("Win32 API: Failed to get file information for \"%s\"",
866                       root_disk_path);
867                 win32_error(err);
868                 ret = WIMLIB_ERR_STAT;
869                 goto out_close_handle;
870         }
871
872         /* Create a WIM dentry */
873         root = new_dentry_with_timeless_inode(path_basename(root_disk_path));
874         if (!root) {
875                 if (errno == EILSEQ)
876                         ret = WIMLIB_ERR_INVALID_UTF8_STRING;
877                 else if (errno == ENOMEM)
878                         ret = WIMLIB_ERR_NOMEM;
879                 else
880                         ret = WIMLIB_ERR_ICONV_NOT_AVAILABLE;
881                 goto out_close_handle;
882         }
883
884         /* Start preparing the associated WIM inode */
885         inode = root->d_inode;
886
887         inode->i_attributes = file_info.dwFileAttributes;
888         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
889         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
890         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
891         inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
892                         (u64)file_info.nFileIndexLow;
893
894         inode->i_resolved = 1;
895         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
896
897         /* Get DOS name and security descriptor (if any). */
898         ret = win32_get_short_name(root, path_utf16);
899         if (ret)
900                 goto out_close_handle;
901         ret = win32_get_security_descriptor(root, sd_set, path_utf16);
902         if (ret)
903                 goto out_close_handle;
904
905         if (inode_is_directory(inode)) {
906                 /* Directory (not a reparse point) --- recurse to children */
907
908                 /* But first... directories may have alternate data streams that
909                  * need to be captured. */
910                 ret = win32_capture_streams(path_utf16,
911                                             path_utf16_nchars,
912                                             inode,
913                                             lookup_table);
914                 if (ret)
915                         goto out_close_handle;
916                 ret = win32_recurse_directory(root,
917                                               root_disk_path,
918                                               lookup_table,
919                                               sd,
920                                               config,
921                                               add_image_flags,
922                                               progress_func,
923                                               sd_set,
924                                               path_utf16,
925                                               path_utf16_nchars);
926         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
927                 /* Reparse point: save the reparse tag and data */
928                 ret = win32_capture_reparse_point(hFile,
929                                                   inode,
930                                                   lookup_table,
931                                                   root_disk_path);
932         } else {
933                 /* Not a directory, not a reparse point; capture the default
934                  * file contents and any alternate data streams. */
935                 ret = win32_capture_streams(path_utf16,
936                                             path_utf16_nchars,
937                                             inode,
938                                             lookup_table);
939         }
940 out_close_handle:
941         CloseHandle(hFile);
942 out_destroy_sd_set:
943         if (extra_arg == NULL)
944                 destroy_sd_set(sd_set);
945 out_free_path_utf16:
946         FREE(path_utf16);
947 #endif
948         /* The below lines of code are common to both UNIX and Win32 builds.  It
949          * simply returns the captured directory tree if the capture was
950          * successful, or frees it if the capture was unsuccessful. */
951 out:
952         if (ret == 0)
953                 *root_ret = root;
954         else
955                 free_dentry_tree(root, lookup_table);
956         return ret;
957 }
958
959 enum pattern_type {
960         NONE = 0,
961         EXCLUSION_LIST,
962         EXCLUSION_EXCEPTION,
963         COMPRESSION_EXCLUSION_LIST,
964         ALIGNMENT_LIST,
965 };
966
967 #define COMPAT_DEFAULT_CONFIG
968
969 /* Default capture configuration file when none is specified. */
970 static const char *default_config =
971 #ifdef COMPAT_DEFAULT_CONFIG /* XXX: This policy is being moved to library
972                                 users.  The next ABI-incompatible library
973                                 version will default to the empty string here. */
974 "[ExclusionList]\n"
975 "\\$ntfs.log\n"
976 "\\hiberfil.sys\n"
977 "\\pagefile.sys\n"
978 "\\System Volume Information\n"
979 "\\RECYCLER\n"
980 "\\Windows\\CSC\n"
981 "\n"
982 "[CompressionExclusionList]\n"
983 "*.mp3\n"
984 "*.zip\n"
985 "*.cab\n"
986 "\\WINDOWS\\inf\\*.pnf\n";
987 #else
988 "";
989 #endif
990
991 static void destroy_pattern_list(struct pattern_list *list)
992 {
993         FREE(list->pats);
994 }
995
996 static void destroy_capture_config(struct capture_config *config)
997 {
998         destroy_pattern_list(&config->exclusion_list);
999         destroy_pattern_list(&config->exclusion_exception);
1000         destroy_pattern_list(&config->compression_exclusion_list);
1001         destroy_pattern_list(&config->alignment_list);
1002         FREE(config->config_str);
1003         FREE(config->prefix);
1004         memset(config, 0, sizeof(*config));
1005 }
1006
1007 static int pattern_list_add_pattern(struct pattern_list *list,
1008                                     const char *pattern)
1009 {
1010         const char **pats;
1011         if (list->num_pats >= list->num_allocated_pats) {
1012                 pats = REALLOC(list->pats,
1013                                sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
1014                 if (!pats)
1015                         return WIMLIB_ERR_NOMEM;
1016                 list->num_allocated_pats += 8;
1017                 list->pats = pats;
1018         }
1019         list->pats[list->num_pats++] = pattern;
1020         return 0;
1021 }
1022
1023 /* Parses the contents of the image capture configuration file and fills in a
1024  * `struct capture_config'. */
1025 static int init_capture_config(struct capture_config *config,
1026                                const char *_config_str, size_t config_len)
1027 {
1028         char *config_str;
1029         char *p;
1030         char *eol;
1031         char *next_p;
1032         size_t bytes_remaining;
1033         enum pattern_type type = NONE;
1034         int ret;
1035         unsigned long line_no = 0;
1036
1037         DEBUG("config_len = %zu", config_len);
1038         bytes_remaining = config_len;
1039         memset(config, 0, sizeof(*config));
1040         config_str = MALLOC(config_len);
1041         if (!config_str) {
1042                 ERROR("Could not duplicate capture config string");
1043                 return WIMLIB_ERR_NOMEM;
1044         }
1045
1046         memcpy(config_str, _config_str, config_len);
1047         next_p = config_str;
1048         config->config_str = config_str;
1049         while (bytes_remaining) {
1050                 line_no++;
1051                 p = next_p;
1052                 eol = memchr(p, '\n', bytes_remaining);
1053                 if (!eol) {
1054                         ERROR("Expected end-of-line in capture config file on "
1055                               "line %lu", line_no);
1056                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1057                         goto out_destroy;
1058                 }
1059
1060                 next_p = eol + 1;
1061                 bytes_remaining -= (next_p - p);
1062                 if (eol == p)
1063                         continue;
1064
1065                 if (*(eol - 1) == '\r')
1066                         eol--;
1067                 *eol = '\0';
1068
1069                 /* Translate backslash to forward slash */
1070                 for (char *pp = p; pp != eol; pp++)
1071                         if (*pp == '\\')
1072                                 *pp = '/';
1073
1074                 /* Remove drive letter */
1075                 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
1076                         p += 2;
1077
1078                 ret = 0;
1079                 if (strcmp(p, "[ExclusionList]") == 0)
1080                         type = EXCLUSION_LIST;
1081                 else if (strcmp(p, "[ExclusionException]") == 0)
1082                         type = EXCLUSION_EXCEPTION;
1083                 else if (strcmp(p, "[CompressionExclusionList]") == 0)
1084                         type = COMPRESSION_EXCLUSION_LIST;
1085                 else if (strcmp(p, "[AlignmentList]") == 0)
1086                         type = ALIGNMENT_LIST;
1087                 else if (p[0] == '[' && strrchr(p, ']')) {
1088                         ERROR("Unknown capture configuration section `%s'", p);
1089                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1090                 } else switch (type) {
1091                 case EXCLUSION_LIST:
1092                         DEBUG("Adding pattern \"%s\" to exclusion list", p);
1093                         ret = pattern_list_add_pattern(&config->exclusion_list, p);
1094                         break;
1095                 case EXCLUSION_EXCEPTION:
1096                         DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
1097                         ret = pattern_list_add_pattern(&config->exclusion_exception, p);
1098                         break;
1099                 case COMPRESSION_EXCLUSION_LIST:
1100                         DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
1101                         ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
1102                         break;
1103                 case ALIGNMENT_LIST:
1104                         DEBUG("Adding pattern \"%s\" to alignment list", p);
1105                         ret = pattern_list_add_pattern(&config->alignment_list, p);
1106                         break;
1107                 default:
1108                         ERROR("Line %lu of capture configuration is not "
1109                               "in a block (such as [ExclusionList])",
1110                               line_no);
1111                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1112                         break;
1113                 }
1114                 if (ret != 0)
1115                         goto out_destroy;
1116         }
1117         return 0;
1118 out_destroy:
1119         destroy_capture_config(config);
1120         return ret;
1121 }
1122
1123 static int capture_config_set_prefix(struct capture_config *config,
1124                                      const char *_prefix)
1125 {
1126         char *prefix = STRDUP(_prefix);
1127
1128         if (!prefix)
1129                 return WIMLIB_ERR_NOMEM;
1130         FREE(config->prefix);
1131         config->prefix = prefix;
1132         config->prefix_len = strlen(prefix);
1133         return 0;
1134 }
1135
1136 static bool match_pattern(const char *path, const char *path_basename,
1137                           const struct pattern_list *list)
1138 {
1139         for (size_t i = 0; i < list->num_pats; i++) {
1140                 const char *pat = list->pats[i];
1141                 const char *string;
1142                 if (pat[0] == '/')
1143                         /* Absolute path from root of capture */
1144                         string = path;
1145                 else {
1146                         if (strchr(pat, '/'))
1147                                 /* Relative path from root of capture */
1148                                 string = path + 1;
1149                         else
1150                                 /* A file name pattern */
1151                                 string = path_basename;
1152                 }
1153                 if (fnmatch(pat, string, FNM_PATHNAME
1154                         #ifdef FNM_CASEFOLD
1155                                         | FNM_CASEFOLD
1156                         #endif
1157                         ) == 0)
1158                 {
1159                         DEBUG("`%s' matches the pattern \"%s\"",
1160                               string, pat);
1161                         return true;
1162                 }
1163         }
1164         return false;
1165 }
1166
1167 /* Return true if the image capture configuration file indicates we should
1168  * exclude the filename @path from capture.
1169  *
1170  * If @exclude_prefix is %true, the part of the path up and including the name
1171  * of the directory being captured is not included in the path for matching
1172  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
1173  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
1174  * directory.
1175  */
1176 bool exclude_path(const char *path, const struct capture_config *config,
1177                   bool exclude_prefix)
1178 {
1179         const char *basename = path_basename(path);
1180         if (exclude_prefix) {
1181                 wimlib_assert(strlen(path) >= config->prefix_len);
1182                 if (memcmp(config->prefix, path, config->prefix_len) == 0
1183                      && path[config->prefix_len] == '/')
1184                         path += config->prefix_len;
1185         }
1186         return match_pattern(path, basename, &config->exclusion_list) &&
1187                 !match_pattern(path, basename, &config->exclusion_exception);
1188
1189 }
1190
1191 /* Strip leading and trailing forward slashes from a string.  Modifies it in
1192  * place and returns the stripped string. */
1193 static const char *canonicalize_target_path(char *target_path)
1194 {
1195         char *p;
1196         if (target_path == NULL)
1197                 target_path = "";
1198         for (;;) {
1199                 if (*target_path == '\0')
1200                         return target_path;
1201                 else if (*target_path == '/')
1202                         target_path++;
1203                 else
1204                         break;
1205         }
1206
1207         p = target_path + strlen(target_path) - 1;
1208         while (*p == '/')
1209                 *p-- = '\0';
1210         return target_path;
1211 }
1212
1213 #if defined(__CYGWIN__) || defined(__WIN32__)
1214 static void zap_backslashes(char *s)
1215 {
1216         while (*s) {
1217                 if (*s == '\\')
1218                         *s = '/';
1219                 s++;
1220         }
1221 }
1222 #endif
1223
1224 /* Strip leading and trailing slashes from the target paths */
1225 static void canonicalize_targets(struct wimlib_capture_source *sources,
1226                                  size_t num_sources)
1227 {
1228         while (num_sources--) {
1229                 DEBUG("Canonicalizing { source: \"%s\", target=\"%s\"}",
1230                       sources->fs_source_path,
1231                       sources->wim_target_path);
1232 #if defined(__CYGWIN__) || defined(__WIN32__)
1233                 /* The Windows API can handle forward slashes.  Just get rid of
1234                  * backslashes to avoid confusing other parts of the library
1235                  * code. */
1236                 zap_backslashes(sources->fs_source_path);
1237                 if (sources->wim_target_path)
1238                         zap_backslashes(sources->wim_target_path);
1239 #endif
1240                 sources->wim_target_path =
1241                         (char*)canonicalize_target_path(sources->wim_target_path);
1242                 DEBUG("Canonical target: \"%s\"", sources->wim_target_path);
1243                 sources++;
1244         }
1245 }
1246
1247 static int capture_source_cmp(const void *p1, const void *p2)
1248 {
1249         const struct wimlib_capture_source *s1 = p1, *s2 = p2;
1250         return strcmp(s1->wim_target_path, s2->wim_target_path);
1251 }
1252
1253 /* Sorts the capture sources lexicographically by target path.  This occurs
1254  * after leading and trailing forward slashes are stripped.
1255  *
1256  * One purpose of this is to make sure that target paths that are inside other
1257  * target paths are extracted after the containing target paths. */
1258 static void sort_sources(struct wimlib_capture_source *sources,
1259                          size_t num_sources)
1260 {
1261         qsort(sources, num_sources, sizeof(sources[0]), capture_source_cmp);
1262 }
1263
1264 static int check_sorted_sources(struct wimlib_capture_source *sources,
1265                                 size_t num_sources, int add_image_flags)
1266 {
1267         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
1268                 if (num_sources != 1) {
1269                         ERROR("Must specify exactly 1 capture source "
1270                               "(the NTFS volume) in NTFS mode!");
1271                         return WIMLIB_ERR_INVALID_PARAM;
1272                 }
1273                 if (sources[0].wim_target_path[0] != '\0') {
1274                         ERROR("In NTFS capture mode the target path inside "
1275                               "the image must be the root directory!");
1276                         return WIMLIB_ERR_INVALID_PARAM;
1277                 }
1278         } else if (num_sources != 0) {
1279                 /* This code is disabled because the current code
1280                  * unconditionally attempts to do overlays.  So, duplicate
1281                  * target paths are OK. */
1282         #if 0
1283                 if (num_sources > 1 && sources[0].wim_target_path[0] == '\0') {
1284                         ERROR("Cannot specify root target when using multiple "
1285                               "capture sources!");
1286                         return WIMLIB_ERR_INVALID_PARAM;
1287                 }
1288                 for (size_t i = 0; i < num_sources - 1; i++) {
1289                         size_t len = strlen(sources[i].wim_target_path);
1290                         size_t j = i + 1;
1291                         const char *target1 = sources[i].wim_target_path;
1292                         do {
1293                                 const char *target2 = sources[j].wim_target_path;
1294                                 DEBUG("target1=%s, target2=%s",
1295                                       target1,target2);
1296                                 if (strncmp(target1, target2, len) ||
1297                                     target2[len] > '/')
1298                                         break;
1299                                 if (target2[len] == '/') {
1300                                         ERROR("Invalid target `%s': is a prefix of `%s'",
1301                                               target1, target2);
1302                                         return WIMLIB_ERR_INVALID_PARAM;
1303                                 }
1304                                 if (target2[len] == '\0') {
1305                                         ERROR("Invalid target `%s': is a duplicate of `%s'",
1306                                               target1, target2);
1307                                         return WIMLIB_ERR_INVALID_PARAM;
1308                                 }
1309                         } while (++j != num_sources);
1310                 }
1311         #endif
1312         }
1313         return 0;
1314
1315 }
1316
1317 /* Creates a new directory to place in the WIM image.  This is to create parent
1318  * directories that are not part of any target as needed.  */
1319 static struct wim_dentry *
1320 new_filler_directory(const char *name)
1321 {
1322         struct wim_dentry *dentry;
1323         DEBUG("Creating filler directory \"%s\"", name);
1324         dentry = new_dentry_with_inode(name);
1325         if (dentry) {
1326                 /* Set the inode number to 0 for now.  The final inode number
1327                  * will be assigned later by assign_inode_numbers(). */
1328                 dentry->d_inode->i_ino = 0;
1329                 dentry->d_inode->i_resolved = 1;
1330                 dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
1331         }
1332         return dentry;
1333 }
1334
1335 /* Transfers the children of @branch to @target.  It is an error if @target is
1336  * not a directory or if both @branch and @target contain a child dentry with
1337  * the same name. */
1338 static int do_overlay(struct wim_dentry *target, struct wim_dentry *branch)
1339 {
1340         struct rb_root *rb_root;
1341
1342         if (!dentry_is_directory(target)) {
1343                 ERROR("Cannot overlay directory `%s' over non-directory",
1344                       branch->file_name_utf8);
1345                 return WIMLIB_ERR_INVALID_OVERLAY;
1346         }
1347
1348         rb_root = &branch->d_inode->i_children;
1349         while (rb_root->rb_node) { /* While @branch has children... */
1350                 struct wim_dentry *child = rbnode_dentry(rb_root->rb_node);
1351                 /* Move @child to the directory @target */
1352                 unlink_dentry(child);
1353                 if (!dentry_add_child(target, child)) {
1354                         /* Revert the change to avoid leaking the directory tree
1355                          * rooted at @child */
1356                         dentry_add_child(branch, child);
1357                         ERROR("Overlay error: file `%s' already exists "
1358                               "as a child of `%s'",
1359                               child->file_name_utf8, target->file_name_utf8);
1360                         return WIMLIB_ERR_INVALID_OVERLAY;
1361                 }
1362         }
1363         return 0;
1364
1365 }
1366
1367 /* Attach or overlay a branch onto the WIM image.
1368  *
1369  * @root_p:
1370  *      Pointer to the root of the WIM image, or pointer to NULL if it has not
1371  *      been created yet.
1372  * @branch
1373  *      Branch to add.
1374  * @target_path:
1375  *      Path in the WIM image to add the branch, with leading and trailing
1376  *      slashes stripped.
1377  */
1378 static int attach_branch(struct wim_dentry **root_p,
1379                          struct wim_dentry *branch,
1380                          char *target_path)
1381 {
1382         char *slash;
1383         struct wim_dentry *dentry, *parent, *target;
1384
1385         if (*target_path == '\0') {
1386                 /* Target: root directory */
1387                 if (*root_p) {
1388                         /* Overlay on existing root */
1389                         return do_overlay(*root_p, branch);
1390                 } else  {
1391                         /* Set as root */
1392                         *root_p = branch;
1393                         return 0;
1394                 }
1395         }
1396
1397         /* Adding a non-root branch.  Create root if it hasn't been created
1398          * already. */
1399         if (!*root_p) {
1400                 *root_p = new_filler_directory("");
1401                 if (!*root_p)
1402                         return WIMLIB_ERR_NOMEM;
1403         }
1404
1405         /* Walk the path to the branch, creating filler directories as needed.
1406          * */
1407         parent = *root_p;
1408         while ((slash = strchr(target_path, '/'))) {
1409                 *slash = '\0';
1410                 dentry = get_dentry_child_with_name(parent, target_path);
1411                 if (!dentry) {
1412                         dentry = new_filler_directory(target_path);
1413                         if (!dentry)
1414                                 return WIMLIB_ERR_NOMEM;
1415                         dentry_add_child(parent, dentry);
1416                 }
1417                 parent = dentry;
1418                 target_path = slash;
1419                 /* Skip over slashes.  Note: this cannot overrun the length of
1420                  * the string because the last character cannot be a slash, as
1421                  * trailing slashes were tripped.  */
1422                 do {
1423                         ++target_path;
1424                 } while (*target_path == '/');
1425         }
1426
1427         /* If the target path already existed, overlay the branch onto it.
1428          * Otherwise, set the branch as the target path. */
1429         target = get_dentry_child_with_name(parent, branch->file_name_utf8);
1430         if (target) {
1431                 return do_overlay(target, branch);
1432         } else {
1433                 dentry_add_child(parent, branch);
1434                 return 0;
1435         }
1436 }
1437
1438 WIMLIBAPI int wimlib_add_image_multisource(WIMStruct *w,
1439                                            struct wimlib_capture_source *sources,
1440                                            size_t num_sources,
1441                                            const char *name,
1442                                            const char *config_str,
1443                                            size_t config_len,
1444                                            int add_image_flags,
1445                                            wimlib_progress_func_t progress_func)
1446 {
1447         int (*capture_tree)(struct wim_dentry **, const char *,
1448                             struct wim_lookup_table *,
1449                             struct wim_security_data *,
1450                             const struct capture_config *,
1451                             int, wimlib_progress_func_t, void *);
1452         void *extra_arg;
1453         struct wim_dentry *root_dentry;
1454         struct wim_dentry *branch;
1455         struct wim_security_data *sd;
1456         struct capture_config config;
1457         struct wim_image_metadata *imd;
1458         int ret;
1459
1460         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
1461 #ifdef WITH_NTFS_3G
1462                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
1463                         ERROR("Cannot dereference files when capturing directly from NTFS");
1464                         return WIMLIB_ERR_INVALID_PARAM;
1465                 }
1466                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
1467                         ERROR("Capturing UNIX owner and mode not supported "
1468                               "when capturing directly from NTFS");
1469                         return WIMLIB_ERR_INVALID_PARAM;
1470                 }
1471                 capture_tree = build_dentry_tree_ntfs;
1472                 extra_arg = &w->ntfs_vol;
1473 #else
1474                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
1475                       "        cannot capture a WIM image directly from a NTFS volume!");
1476                 return WIMLIB_ERR_UNSUPPORTED;
1477 #endif
1478         } else {
1479                 capture_tree = build_dentry_tree;
1480                 extra_arg = NULL;
1481         }
1482
1483 #if defined(__CYGWIN__) || defined(__WIN32__)
1484         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
1485                 ERROR("Capturing UNIX-specific data is not supported on Windows");
1486                 return WIMLIB_ERR_INVALID_PARAM;
1487         }
1488         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
1489                 ERROR("Dereferencing symbolic links is not supported on Windows");
1490                 return WIMLIB_ERR_INVALID_PARAM;
1491         }
1492 #endif
1493
1494         if (!name || !*name) {
1495                 ERROR("Must specify a non-empty string for the image name");
1496                 return WIMLIB_ERR_INVALID_PARAM;
1497         }
1498
1499         if (w->hdr.total_parts != 1) {
1500                 ERROR("Cannot add an image to a split WIM");
1501                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1502         }
1503
1504         if (wimlib_image_name_in_use(w, name)) {
1505                 ERROR("There is already an image named \"%s\" in `%s'",
1506                       name, w->filename);
1507                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1508         }
1509
1510         if (!config_str) {
1511                 DEBUG("Using default capture configuration");
1512                 config_str = default_config;
1513                 config_len = strlen(default_config);
1514         }
1515         ret = init_capture_config(&config, config_str, config_len);
1516         if (ret)
1517                 goto out;
1518
1519         DEBUG("Allocating security data");
1520         sd = CALLOC(1, sizeof(struct wim_security_data));
1521         if (!sd) {
1522                 ret = WIMLIB_ERR_NOMEM;
1523                 goto out_destroy_capture_config;
1524         }
1525         sd->total_length = 8;
1526         sd->refcnt = 1;
1527
1528         DEBUG("Using %zu capture sources", num_sources);
1529         canonicalize_targets(sources, num_sources);
1530         sort_sources(sources, num_sources);
1531         ret = check_sorted_sources(sources, num_sources, add_image_flags);
1532         if (ret) {
1533                 ret = WIMLIB_ERR_INVALID_PARAM;
1534                 goto out_free_security_data;
1535         }
1536
1537         DEBUG("Building dentry tree.");
1538         if (num_sources == 0) {
1539                 root_dentry = new_filler_directory("");
1540                 if (!root_dentry)
1541                         goto out_free_security_data;
1542         } else {
1543                 size_t i;
1544
1545                 root_dentry = NULL;
1546                 i = 0;
1547                 do {
1548                         int flags;
1549                         union wimlib_progress_info progress;
1550
1551                         DEBUG("Building dentry tree for source %zu of %zu "
1552                               "(\"%s\" => \"%s\")", i + 1, num_sources,
1553                               sources[i].fs_source_path,
1554                               sources[i].wim_target_path);
1555                         if (progress_func) {
1556                                 memset(&progress, 0, sizeof(progress));
1557                                 progress.scan.source = sources[i].fs_source_path;
1558                                 progress.scan.wim_target_path = sources[i].wim_target_path;
1559                                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
1560                         }
1561                         ret = capture_config_set_prefix(&config,
1562                                                         sources[i].fs_source_path);
1563                         if (ret)
1564                                 goto out_free_dentry_tree;
1565                         flags = add_image_flags | WIMLIB_ADD_IMAGE_FLAG_SOURCE;
1566                         if (!*sources[i].wim_target_path)
1567                                 flags |= WIMLIB_ADD_IMAGE_FLAG_ROOT;
1568                         ret = (*capture_tree)(&branch, sources[i].fs_source_path,
1569                                               w->lookup_table, sd,
1570                                               &config,
1571                                               flags,
1572                                               progress_func, extra_arg);
1573                         if (ret) {
1574                                 ERROR("Failed to build dentry tree for `%s'",
1575                                       sources[i].fs_source_path);
1576                                 goto out_free_dentry_tree;
1577                         }
1578                         if (branch) {
1579                                 /* Use the target name, not the source name, for
1580                                  * the root of each branch from a capture
1581                                  * source.  (This will also set the root dentry
1582                                  * of the entire image to be unnamed.) */
1583                                 ret = set_dentry_name(branch,
1584                                                       path_basename(sources[i].wim_target_path));
1585                                 if (ret)
1586                                         goto out_free_branch;
1587
1588                                 ret = attach_branch(&root_dentry, branch,
1589                                                     sources[i].wim_target_path);
1590                                 if (ret)
1591                                         goto out_free_branch;
1592                         }
1593                         if (progress_func)
1594                                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
1595                 } while (++i != num_sources);
1596         }
1597
1598         DEBUG("Calculating full paths of dentries.");
1599         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
1600         if (ret != 0)
1601                 goto out_free_dentry_tree;
1602
1603         ret = add_new_dentry_tree(w, root_dentry, sd);
1604         if (ret != 0)
1605                 goto out_free_dentry_tree;
1606
1607         imd = &w->image_metadata[w->hdr.image_count - 1];
1608
1609         ret = dentry_tree_fix_inodes(root_dentry, &imd->inode_list);
1610         if (ret != 0)
1611                 goto out_destroy_imd;
1612
1613         DEBUG("Assigning hard link group IDs");
1614         assign_inode_numbers(&imd->inode_list);
1615
1616         ret = xml_add_image(w, name);
1617         if (ret != 0)
1618                 goto out_destroy_imd;
1619
1620         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
1621                 wimlib_set_boot_idx(w, w->hdr.image_count);
1622         ret = 0;
1623         goto out;
1624 out_destroy_imd:
1625         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
1626                                w->lookup_table);
1627         w->hdr.image_count--;
1628         goto out;
1629 out_free_branch:
1630         free_dentry_tree(branch, w->lookup_table);
1631 out_free_dentry_tree:
1632         free_dentry_tree(root_dentry, w->lookup_table);
1633 out_free_security_data:
1634         free_security_data(sd);
1635 out_destroy_capture_config:
1636         destroy_capture_config(&config);
1637 out:
1638         return ret;
1639 }
1640
1641 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *source,
1642                                const char *name, const char *config_str,
1643                                size_t config_len, int add_image_flags,
1644                                wimlib_progress_func_t progress_func)
1645 {
1646         if (!source || !*source)
1647                 return WIMLIB_ERR_INVALID_PARAM;
1648
1649         char *fs_source_path = STRDUP(source);
1650         int ret;
1651         struct wimlib_capture_source capture_src = {
1652                 .fs_source_path = fs_source_path,
1653                 .wim_target_path = NULL,
1654                 .reserved = 0,
1655         };
1656         ret = wimlib_add_image_multisource(w, &capture_src, 1, name,
1657                                            config_str, config_len,
1658                                            add_image_flags, progress_func);
1659         FREE(fs_source_path);
1660         return ret;
1661 }