0ae57361af3f5822137af62e4eca2d978e1a86b9
[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                  * Unlike 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 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
540 #endif
541
542 /*
543  * build_dentry_tree():
544  *      Recursively builds a tree of WIM dentries from an on-disk directory
545  *      tree.
546  *
547  * @root_ret:   Place to return a pointer to the root of the dentry tree.  Only
548  *              modified if successful.  Set to NULL if the file or directory was
549  *              excluded from capture.
550  *
551  * @root_disk_path:  The path to the root of the directory tree on disk (UTF-8).
552  *
553  * @lookup_table: The lookup table for the WIM file.  For each file added to the
554  *              dentry tree being built, an entry is added to the lookup table,
555  *              unless an identical stream is already in the lookup table.
556  *              These lookup table entries that are added point to the path of
557  *              the file on disk.
558  *
559  * @sd:         Ignored.  (Security data only captured in NTFS mode.)
560  *
561  * @capture_config:
562  *              Configuration for files to be excluded from capture.
563  *
564  * @add_flags:  Bitwise or of WIMLIB_ADD_IMAGE_FLAG_*
565  *
566  * @extra_arg:  Ignored in UNIX builds; used to pass sd_set pointer in Windows
567  *              builds.
568  *
569  * @return:     0 on success, nonzero on failure.  It is a failure if any of
570  *              the files cannot be `stat'ed, or if any of the needed
571  *              directories cannot be opened or read.  Failure to add the files
572  *              to the WIM may still occur later when trying to actually read
573  *              the on-disk files during a call to wimlib_write() or
574  *              wimlib_overwrite().
575  */
576 static int build_dentry_tree(struct wim_dentry **root_ret,
577                              const char *root_disk_path,
578                              struct wim_lookup_table *lookup_table,
579                              struct wim_security_data *sd,
580                              const struct capture_config *config,
581                              int add_image_flags,
582                              wimlib_progress_func_t progress_func,
583                              void *extra_arg)
584 {
585         struct wim_dentry *root = NULL;
586         int ret = 0;
587         struct wim_inode *inode;
588
589         if (exclude_path(root_disk_path, config, true)) {
590                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
591                         ERROR("Cannot exclude the root directory from capture");
592                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
593                         goto out;
594                 }
595                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
596                     && progress_func)
597                 {
598                         union wimlib_progress_info info;
599                         info.scan.cur_path = root_disk_path;
600                         info.scan.excluded = true;
601                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
602                 }
603                 goto out;
604         }
605
606         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
607             && progress_func)
608         {
609                 union wimlib_progress_info info;
610                 info.scan.cur_path = root_disk_path;
611                 info.scan.excluded = false;
612                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
613         }
614
615 #if !defined(__CYGWIN__) && !defined(__WIN32__)
616         /* UNIX version of capturing a directory tree */
617         struct stat root_stbuf;
618         int (*stat_fn)(const char *restrict, struct stat *restrict);
619         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE)
620                 stat_fn = stat;
621         else
622                 stat_fn = lstat;
623
624         ret = (*stat_fn)(root_disk_path, &root_stbuf);
625         if (ret != 0) {
626                 ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
627                 goto out;
628         }
629
630         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) &&
631               !S_ISDIR(root_stbuf.st_mode))
632         {
633                 /* Do a dereference-stat in case the root is a symbolic link.
634                  * This case is allowed, provided that the symbolic link points
635                  * to a directory. */
636                 ret = stat(root_disk_path, &root_stbuf);
637                 if (ret != 0) {
638                         ERROR_WITH_ERRNO("Failed to stat `%s'", root_disk_path);
639                         ret = WIMLIB_ERR_STAT;
640                         goto out;
641                 }
642                 if (!S_ISDIR(root_stbuf.st_mode)) {
643                         ERROR("`%s' is not a directory", root_disk_path);
644                         ret = WIMLIB_ERR_NOTDIR;
645                         goto out;
646                 }
647         }
648         if (!S_ISREG(root_stbuf.st_mode) && !S_ISDIR(root_stbuf.st_mode)
649             && !S_ISLNK(root_stbuf.st_mode)) {
650                 ERROR("`%s' is not a regular file, directory, or symbolic link.",
651                       root_disk_path);
652                 ret = WIMLIB_ERR_SPECIAL_FILE;
653                 goto out;
654         }
655
656         root = new_dentry_with_timeless_inode(path_basename(root_disk_path));
657         if (!root) {
658                 if (errno == EILSEQ)
659                         ret = WIMLIB_ERR_INVALID_UTF8_STRING;
660                 else if (errno == ENOMEM)
661                         ret = WIMLIB_ERR_NOMEM;
662                 else
663                         ret = WIMLIB_ERR_ICONV_NOT_AVAILABLE;
664                 goto out;
665         }
666
667         inode = root->d_inode;
668
669 #ifdef HAVE_STAT_NANOSECOND_PRECISION
670         inode->i_creation_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
671         inode->i_last_write_time = timespec_to_wim_timestamp(&root_stbuf.st_mtim);
672         inode->i_last_access_time = timespec_to_wim_timestamp(&root_stbuf.st_atim);
673 #else
674         inode->i_creation_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
675         inode->i_last_write_time = unix_timestamp_to_wim(root_stbuf.st_mtime);
676         inode->i_last_access_time = unix_timestamp_to_wim(root_stbuf.st_atime);
677 #endif
678         if (sizeof(ino_t) >= 8)
679                 inode->i_ino = (u64)root_stbuf.st_ino;
680         else
681                 inode->i_ino = (u64)root_stbuf.st_ino |
682                                    ((u64)root_stbuf.st_dev << ((sizeof(ino_t) * 8) & 63));
683         inode->i_resolved = 1;
684         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
685                 ret = inode_set_unix_data(inode, root_stbuf.st_uid,
686                                           root_stbuf.st_gid,
687                                           root_stbuf.st_mode,
688                                           lookup_table,
689                                           UNIX_DATA_ALL | UNIX_DATA_CREATE);
690                 if (ret)
691                         goto out;
692         }
693         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
694         if (S_ISREG(root_stbuf.st_mode)) { /* Archiving a regular file */
695
696                 struct wim_lookup_table_entry *lte;
697                 u8 hash[SHA1_HASH_SIZE];
698
699                 inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
700
701                 /* Empty files do not have to have a lookup table entry. */
702                 if (root_stbuf.st_size == 0)
703                         goto out;
704
705                 /* For each regular file, we must check to see if the file is in
706                  * the lookup table already; if it is, we increment its refcnt;
707                  * otherwise, we create a new lookup table entry and insert it.
708                  * */
709
710                 ret = sha1sum(root_disk_path, hash);
711                 if (ret != 0)
712                         goto out;
713
714                 lte = __lookup_resource(lookup_table, hash);
715                 if (lte) {
716                         lte->refcnt++;
717                         DEBUG("Add lte reference %u for `%s'", lte->refcnt,
718                               root_disk_path);
719                 } else {
720                         char *file_on_disk = STRDUP(root_disk_path);
721                         if (!file_on_disk) {
722                                 ERROR("Failed to allocate memory for file path");
723                                 ret = WIMLIB_ERR_NOMEM;
724                                 goto out;
725                         }
726                         lte = new_lookup_table_entry();
727                         if (!lte) {
728                                 FREE(file_on_disk);
729                                 ret = WIMLIB_ERR_NOMEM;
730                                 goto out;
731                         }
732                         lte->file_on_disk = file_on_disk;
733                         lte->resource_location = RESOURCE_IN_FILE_ON_DISK;
734                         lte->resource_entry.original_size = root_stbuf.st_size;
735                         lte->resource_entry.size = root_stbuf.st_size;
736                         copy_hash(lte->hash, hash);
737                         lookup_table_insert(lookup_table, lte);
738                 }
739                 root->d_inode->i_lte = lte;
740         } else if (S_ISDIR(root_stbuf.st_mode)) { /* Archiving a directory */
741
742                 inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
743
744                 DIR *dir;
745                 struct dirent entry, *result;
746                 struct wim_dentry *child;
747
748                 dir = opendir(root_disk_path);
749                 if (!dir) {
750                         ERROR_WITH_ERRNO("Failed to open the directory `%s'",
751                                          root_disk_path);
752                         ret = WIMLIB_ERR_OPEN;
753                         goto out;
754                 }
755
756                 /* Buffer for names of files in directory. */
757                 size_t len = strlen(root_disk_path);
758                 char name[len + 1 + FILENAME_MAX + 1];
759                 memcpy(name, root_disk_path, len);
760                 name[len] = '/';
761
762                 /* Create a dentry for each entry in the directory on disk, and recurse
763                  * to any subdirectories. */
764                 while (1) {
765                         errno = 0;
766                         ret = readdir_r(dir, &entry, &result);
767                         if (ret != 0) {
768                                 ret = WIMLIB_ERR_READ;
769                                 ERROR_WITH_ERRNO("Error reading the "
770                                                  "directory `%s'",
771                                                  root_disk_path);
772                                 break;
773                         }
774                         if (result == NULL)
775                                 break;
776                         if (result->d_name[0] == '.' && (result->d_name[1] == '\0'
777                               || (result->d_name[1] == '.' && result->d_name[2] == '\0')))
778                                         continue;
779                         strcpy(name + len + 1, result->d_name);
780                         ret = build_dentry_tree(&child, name, lookup_table,
781                                                 NULL, config, add_image_flags,
782                                                 progress_func, NULL);
783                         if (ret != 0)
784                                 break;
785                         if (child)
786                                 dentry_add_child(root, child);
787                 }
788                 closedir(dir);
789         } else { /* Archiving a symbolic link */
790                 inode->i_attributes = FILE_ATTRIBUTE_REPARSE_POINT;
791                 inode->i_reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
792
793                 /* The idea here is to call readlink() to get the UNIX target of
794                  * the symbolic link, then turn the target into a reparse point
795                  * data buffer that contains a relative or absolute symbolic
796                  * link (NOT a junction point or *full* path symbolic link with
797                  * drive letter).
798                  */
799
800                 char deref_name_buf[4096];
801                 ssize_t deref_name_len;
802
803                 deref_name_len = readlink(root_disk_path, deref_name_buf,
804                                           sizeof(deref_name_buf) - 1);
805                 if (deref_name_len >= 0) {
806                         deref_name_buf[deref_name_len] = '\0';
807                         DEBUG("Read symlink `%s'", deref_name_buf);
808                         ret = inode_set_symlink(root->d_inode, deref_name_buf,
809                                                 lookup_table, NULL);
810                         if (ret == 0) {
811                                 /*
812                                  * Unfortunately, Windows seems to have the
813                                  * concept of "file" symbolic links as being
814                                  * different from "directory" symbolic links...
815                                  * so FILE_ATTRIBUTE_DIRECTORY needs to be set
816                                  * on the symbolic link if the *target* of the
817                                  * symbolic link is a directory.
818                                  */
819                                 struct stat stbuf;
820                                 if (stat(root_disk_path, &stbuf) == 0 &&
821                                     S_ISDIR(stbuf.st_mode))
822                                 {
823                                         inode->i_attributes |= FILE_ATTRIBUTE_DIRECTORY;
824                                 }
825                         }
826                 } else {
827                         ERROR_WITH_ERRNO("Failed to read target of "
828                                          "symbolic link `%s'", root_disk_path);
829                         ret = WIMLIB_ERR_READLINK;
830                 }
831         }
832 #else
833         /* Win32 version of capturing a directory tree */
834
835         wchar_t *path_utf16;
836         size_t path_utf16_nchars;
837         struct sd_set *sd_set;
838         DWORD err;
839
840         if (extra_arg == NULL) {
841                 sd_set = alloca(sizeof(struct sd_set));
842                 sd_set->rb_root.rb_node = NULL,
843                 sd_set->sd = sd;
844         } else {
845                 sd_set = extra_arg;
846         }
847
848         ret = utf8_to_utf16(root_disk_path, strlen(root_disk_path),
849                             (char**)&path_utf16, &path_utf16_nchars);
850         if (ret)
851                 goto out;
852         path_utf16_nchars /= sizeof(wchar_t);
853
854         HANDLE hFile = win32_open_file_readonly(path_utf16);
855         if (hFile == INVALID_HANDLE_VALUE) {
856                 err = GetLastError();
857                 ERROR("Win32 API: Failed to open \"%s\"", root_disk_path);
858                 win32_error(err);
859                 ret = WIMLIB_ERR_OPEN;
860                 goto out_destroy_sd_set;
861         }
862
863         BY_HANDLE_FILE_INFORMATION file_info;
864         if (!GetFileInformationByHandle(hFile, &file_info)) {
865                 err = GetLastError();
866                 ERROR("Win32 API: Failed to get file information for \"%s\"",
867                       root_disk_path);
868                 win32_error(err);
869                 ret = WIMLIB_ERR_STAT;
870                 goto out_close_handle;
871         }
872
873         /* Create a WIM dentry */
874         root = new_dentry_with_timeless_inode(path_basename(root_disk_path));
875         if (!root) {
876                 if (errno == EILSEQ)
877                         ret = WIMLIB_ERR_INVALID_UTF8_STRING;
878                 else if (errno == ENOMEM)
879                         ret = WIMLIB_ERR_NOMEM;
880                 else
881                         ret = WIMLIB_ERR_ICONV_NOT_AVAILABLE;
882                 goto out_close_handle;
883         }
884
885         /* Start preparing the associated WIM inode */
886         inode = root->d_inode;
887
888         inode->i_attributes = file_info.dwFileAttributes;
889         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
890         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
891         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
892         inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
893                         (u64)file_info.nFileIndexLow;
894
895         inode->i_resolved = 1;
896         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
897
898         /* Get DOS name and security descriptor (if any). */
899         ret = win32_get_short_name(root, path_utf16);
900         if (ret)
901                 goto out_close_handle;
902         ret = win32_get_security_descriptor(root, sd_set, path_utf16);
903         if (ret)
904                 goto out_close_handle;
905
906         if (inode_is_directory(inode)) {
907                 /* Directory (not a reparse point) --- recurse to children */
908
909                 /* But first... directories may have alternate data streams that
910                  * need to be captured. */
911                 ret = win32_capture_streams(path_utf16,
912                                             path_utf16_nchars,
913                                             inode,
914                                             lookup_table);
915                 if (ret)
916                         goto out_close_handle;
917                 ret = win32_recurse_directory(root,
918                                               root_disk_path,
919                                               lookup_table,
920                                               sd,
921                                               config,
922                                               add_image_flags,
923                                               progress_func,
924                                               sd_set,
925                                               path_utf16,
926                                               path_utf16_nchars);
927         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
928                 /* Reparse point: save the reparse tag and data */
929                 ret = win32_capture_reparse_point(hFile,
930                                                   inode,
931                                                   lookup_table,
932                                                   root_disk_path);
933         } else {
934                 /* Not a directory, not a reparse point; capture the default
935                  * file contents and any alternate data streams. */
936                 ret = win32_capture_streams(path_utf16,
937                                             path_utf16_nchars,
938                                             inode,
939                                             lookup_table);
940         }
941 out_close_handle:
942         CloseHandle(hFile);
943 out_free_path_utf16:
944         FREE(path_utf16);
945 out_destroy_sd_set:
946         if (extra_arg == NULL)
947                 destroy_sd_set(sd_set);
948 #endif
949         /* The below lines of code are common to both UNIX and Win32 builds.  It
950          * simply returns the captured directory tree if the capture was
951          * successful, or frees it if the capture was unsuccessful. */
952 out:
953         if (ret == 0)
954                 *root_ret = root;
955         else
956                 free_dentry_tree(root, lookup_table);
957         return ret;
958 }
959
960 enum pattern_type {
961         NONE = 0,
962         EXCLUSION_LIST,
963         EXCLUSION_EXCEPTION,
964         COMPRESSION_EXCLUSION_LIST,
965         ALIGNMENT_LIST,
966 };
967
968 #define COMPAT_DEFAULT_CONFIG
969
970 /* Default capture configuration file when none is specified. */
971 static const char *default_config =
972 #ifdef COMPAT_DEFAULT_CONFIG /* XXX: This policy is being moved to library
973                                 users.  The next ABI-incompatible library
974                                 version will default to the empty string here. */
975 "[ExclusionList]\n"
976 "\\$ntfs.log\n"
977 "\\hiberfil.sys\n"
978 "\\pagefile.sys\n"
979 "\\System Volume Information\n"
980 "\\RECYCLER\n"
981 "\\Windows\\CSC\n"
982 "\n"
983 "[CompressionExclusionList]\n"
984 "*.mp3\n"
985 "*.zip\n"
986 "*.cab\n"
987 "\\WINDOWS\\inf\\*.pnf\n";
988 #else
989 "";
990 #endif
991
992 static void destroy_pattern_list(struct pattern_list *list)
993 {
994         FREE(list->pats);
995 }
996
997 static void destroy_capture_config(struct capture_config *config)
998 {
999         destroy_pattern_list(&config->exclusion_list);
1000         destroy_pattern_list(&config->exclusion_exception);
1001         destroy_pattern_list(&config->compression_exclusion_list);
1002         destroy_pattern_list(&config->alignment_list);
1003         FREE(config->config_str);
1004         FREE(config->prefix);
1005         memset(config, 0, sizeof(*config));
1006 }
1007
1008 static int pattern_list_add_pattern(struct pattern_list *list,
1009                                     const char *pattern)
1010 {
1011         const char **pats;
1012         if (list->num_pats >= list->num_allocated_pats) {
1013                 pats = REALLOC(list->pats,
1014                                sizeof(list->pats[0]) * (list->num_allocated_pats + 8));
1015                 if (!pats)
1016                         return WIMLIB_ERR_NOMEM;
1017                 list->num_allocated_pats += 8;
1018                 list->pats = pats;
1019         }
1020         list->pats[list->num_pats++] = pattern;
1021         return 0;
1022 }
1023
1024 /* Parses the contents of the image capture configuration file and fills in a
1025  * `struct capture_config'. */
1026 static int init_capture_config(struct capture_config *config,
1027                                const char *_config_str, size_t config_len)
1028 {
1029         char *config_str;
1030         char *p;
1031         char *eol;
1032         char *next_p;
1033         size_t bytes_remaining;
1034         enum pattern_type type = NONE;
1035         int ret;
1036         unsigned long line_no = 0;
1037
1038         DEBUG("config_len = %zu", config_len);
1039         bytes_remaining = config_len;
1040         memset(config, 0, sizeof(*config));
1041         config_str = MALLOC(config_len);
1042         if (!config_str) {
1043                 ERROR("Could not duplicate capture config string");
1044                 return WIMLIB_ERR_NOMEM;
1045         }
1046
1047         memcpy(config_str, _config_str, config_len);
1048         next_p = config_str;
1049         config->config_str = config_str;
1050         while (bytes_remaining) {
1051                 line_no++;
1052                 p = next_p;
1053                 eol = memchr(p, '\n', bytes_remaining);
1054                 if (!eol) {
1055                         ERROR("Expected end-of-line in capture config file on "
1056                               "line %lu", line_no);
1057                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1058                         goto out_destroy;
1059                 }
1060
1061                 next_p = eol + 1;
1062                 bytes_remaining -= (next_p - p);
1063                 if (eol == p)
1064                         continue;
1065
1066                 if (*(eol - 1) == '\r')
1067                         eol--;
1068                 *eol = '\0';
1069
1070                 /* Translate backslash to forward slash */
1071                 for (char *pp = p; pp != eol; pp++)
1072                         if (*pp == '\\')
1073                                 *pp = '/';
1074
1075                 /* Remove drive letter */
1076                 if (eol - p > 2 && isalpha(*p) && *(p + 1) == ':')
1077                         p += 2;
1078
1079                 ret = 0;
1080                 if (strcmp(p, "[ExclusionList]") == 0)
1081                         type = EXCLUSION_LIST;
1082                 else if (strcmp(p, "[ExclusionException]") == 0)
1083                         type = EXCLUSION_EXCEPTION;
1084                 else if (strcmp(p, "[CompressionExclusionList]") == 0)
1085                         type = COMPRESSION_EXCLUSION_LIST;
1086                 else if (strcmp(p, "[AlignmentList]") == 0)
1087                         type = ALIGNMENT_LIST;
1088                 else if (p[0] == '[' && strrchr(p, ']')) {
1089                         ERROR("Unknown capture configuration section `%s'", p);
1090                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1091                 } else switch (type) {
1092                 case EXCLUSION_LIST:
1093                         DEBUG("Adding pattern \"%s\" to exclusion list", p);
1094                         ret = pattern_list_add_pattern(&config->exclusion_list, p);
1095                         break;
1096                 case EXCLUSION_EXCEPTION:
1097                         DEBUG("Adding pattern \"%s\" to exclusion exception list", p);
1098                         ret = pattern_list_add_pattern(&config->exclusion_exception, p);
1099                         break;
1100                 case COMPRESSION_EXCLUSION_LIST:
1101                         DEBUG("Adding pattern \"%s\" to compression exclusion list", p);
1102                         ret = pattern_list_add_pattern(&config->compression_exclusion_list, p);
1103                         break;
1104                 case ALIGNMENT_LIST:
1105                         DEBUG("Adding pattern \"%s\" to alignment list", p);
1106                         ret = pattern_list_add_pattern(&config->alignment_list, p);
1107                         break;
1108                 default:
1109                         ERROR("Line %lu of capture configuration is not "
1110                               "in a block (such as [ExclusionList])",
1111                               line_no);
1112                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
1113                         break;
1114                 }
1115                 if (ret != 0)
1116                         goto out_destroy;
1117         }
1118         return 0;
1119 out_destroy:
1120         destroy_capture_config(config);
1121         return ret;
1122 }
1123
1124 static int capture_config_set_prefix(struct capture_config *config,
1125                                      const char *_prefix)
1126 {
1127         char *prefix = STRDUP(_prefix);
1128
1129         if (!prefix)
1130                 return WIMLIB_ERR_NOMEM;
1131         FREE(config->prefix);
1132         config->prefix = prefix;
1133         config->prefix_len = strlen(prefix);
1134         return 0;
1135 }
1136
1137 static bool match_pattern(const char *path, const char *path_basename,
1138                           const struct pattern_list *list)
1139 {
1140         for (size_t i = 0; i < list->num_pats; i++) {
1141                 const char *pat = list->pats[i];
1142                 const char *string;
1143                 if (pat[0] == '/')
1144                         /* Absolute path from root of capture */
1145                         string = path;
1146                 else {
1147                         if (strchr(pat, '/'))
1148                                 /* Relative path from root of capture */
1149                                 string = path + 1;
1150                         else
1151                                 /* A file name pattern */
1152                                 string = path_basename;
1153                 }
1154                 if (fnmatch(pat, string, FNM_PATHNAME
1155                         #ifdef FNM_CASEFOLD
1156                                         | FNM_CASEFOLD
1157                         #endif
1158                         ) == 0)
1159                 {
1160                         DEBUG("`%s' matches the pattern \"%s\"",
1161                               string, pat);
1162                         return true;
1163                 }
1164         }
1165         return false;
1166 }
1167
1168 /* Return true if the image capture configuration file indicates we should
1169  * exclude the filename @path from capture.
1170  *
1171  * If @exclude_prefix is %true, the part of the path up and including the name
1172  * of the directory being captured is not included in the path for matching
1173  * purposes.  This allows, for example, a pattern like /hiberfil.sys to match a
1174  * file /mnt/windows7/hiberfil.sys if we are capturing the /mnt/windows7
1175  * directory.
1176  */
1177 bool exclude_path(const char *path, const struct capture_config *config,
1178                   bool exclude_prefix)
1179 {
1180         const char *basename = path_basename(path);
1181         if (exclude_prefix) {
1182                 wimlib_assert(strlen(path) >= config->prefix_len);
1183                 if (memcmp(config->prefix, path, config->prefix_len) == 0
1184                      && path[config->prefix_len] == '/')
1185                         path += config->prefix_len;
1186         }
1187         return match_pattern(path, basename, &config->exclusion_list) &&
1188                 !match_pattern(path, basename, &config->exclusion_exception);
1189
1190 }
1191
1192 /* Strip leading and trailing forward slashes from a string.  Modifies it in
1193  * place and returns the stripped string. */
1194 static const char *canonicalize_target_path(char *target_path)
1195 {
1196         char *p;
1197         if (target_path == NULL)
1198                 return "";
1199         for (;;) {
1200                 if (*target_path == '\0')
1201                         return target_path;
1202                 else if (*target_path == '/')
1203                         target_path++;
1204                 else
1205                         break;
1206         }
1207
1208         p = target_path + strlen(target_path) - 1;
1209         while (*p == '/')
1210                 *p-- = '\0';
1211         return target_path;
1212 }
1213
1214 #if defined(__CYGWIN__) || defined(__WIN32__)
1215 static void zap_backslashes(char *s)
1216 {
1217         while (*s) {
1218                 if (*s == '\\')
1219                         *s = '/';
1220                 s++;
1221         }
1222 }
1223 #endif
1224
1225 /* Strip leading and trailing slashes from the target paths */
1226 static void canonicalize_targets(struct wimlib_capture_source *sources,
1227                                  size_t num_sources)
1228 {
1229         while (num_sources--) {
1230                 DEBUG("Canonicalizing { source: \"%s\", target=\"%s\"}",
1231                       sources->fs_source_path,
1232                       sources->wim_target_path);
1233 #if defined(__CYGWIN__) || defined(__WIN32__)
1234                 /* The Windows API can handle forward slashes.  Just get rid of
1235                  * backslashes to avoid confusing other parts of the library
1236                  * code. */
1237                 zap_backslashes(sources->fs_source_path);
1238                 if (sources->wim_target_path)
1239                         zap_backslashes(sources->wim_target_path);
1240 #endif
1241                 sources->wim_target_path =
1242                         (char*)canonicalize_target_path(sources->wim_target_path);
1243                 DEBUG("Canonical target: \"%s\"", sources->wim_target_path);
1244                 sources++;
1245         }
1246 }
1247
1248 static int capture_source_cmp(const void *p1, const void *p2)
1249 {
1250         const struct wimlib_capture_source *s1 = p1, *s2 = p2;
1251         return strcmp(s1->wim_target_path, s2->wim_target_path);
1252 }
1253
1254 /* Sorts the capture sources lexicographically by target path.  This occurs
1255  * after leading and trailing forward slashes are stripped.
1256  *
1257  * One purpose of this is to make sure that target paths that are inside other
1258  * target paths are added after the containing target paths. */
1259 static void sort_sources(struct wimlib_capture_source *sources,
1260                          size_t num_sources)
1261 {
1262         qsort(sources, num_sources, sizeof(sources[0]), capture_source_cmp);
1263 }
1264
1265 static int check_sorted_sources(struct wimlib_capture_source *sources,
1266                                 size_t num_sources, int add_image_flags)
1267 {
1268         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
1269                 if (num_sources != 1) {
1270                         ERROR("Must specify exactly 1 capture source "
1271                               "(the NTFS volume) in NTFS mode!");
1272                         return WIMLIB_ERR_INVALID_PARAM;
1273                 }
1274                 if (sources[0].wim_target_path[0] != '\0') {
1275                         ERROR("In NTFS capture mode the target path inside "
1276                               "the image must be the root directory!");
1277                         return WIMLIB_ERR_INVALID_PARAM;
1278                 }
1279         } else if (num_sources != 0) {
1280                 /* This code is disabled because the current code
1281                  * unconditionally attempts to do overlays.  So, duplicate
1282                  * target paths are OK. */
1283         #if 0
1284                 if (num_sources > 1 && sources[0].wim_target_path[0] == '\0') {
1285                         ERROR("Cannot specify root target when using multiple "
1286                               "capture sources!");
1287                         return WIMLIB_ERR_INVALID_PARAM;
1288                 }
1289                 for (size_t i = 0; i < num_sources - 1; i++) {
1290                         size_t len = strlen(sources[i].wim_target_path);
1291                         size_t j = i + 1;
1292                         const char *target1 = sources[i].wim_target_path;
1293                         do {
1294                                 const char *target2 = sources[j].wim_target_path;
1295                                 DEBUG("target1=%s, target2=%s",
1296                                       target1,target2);
1297                                 if (strncmp(target1, target2, len) ||
1298                                     target2[len] > '/')
1299                                         break;
1300                                 if (target2[len] == '/') {
1301                                         ERROR("Invalid target `%s': is a prefix of `%s'",
1302                                               target1, target2);
1303                                         return WIMLIB_ERR_INVALID_PARAM;
1304                                 }
1305                                 if (target2[len] == '\0') {
1306                                         ERROR("Invalid target `%s': is a duplicate of `%s'",
1307                                               target1, target2);
1308                                         return WIMLIB_ERR_INVALID_PARAM;
1309                                 }
1310                         } while (++j != num_sources);
1311                 }
1312         #endif
1313         }
1314         return 0;
1315
1316 }
1317
1318 /* Creates a new directory to place in the WIM image.  This is to create parent
1319  * directories that are not part of any target as needed.  */
1320 static struct wim_dentry *
1321 new_filler_directory(const char *name)
1322 {
1323         struct wim_dentry *dentry;
1324         DEBUG("Creating filler directory \"%s\"", name);
1325         dentry = new_dentry_with_inode(name);
1326         if (dentry) {
1327                 /* Set the inode number to 0 for now.  The final inode number
1328                  * will be assigned later by assign_inode_numbers(). */
1329                 dentry->d_inode->i_ino = 0;
1330                 dentry->d_inode->i_resolved = 1;
1331                 dentry->d_inode->i_attributes = FILE_ATTRIBUTE_DIRECTORY;
1332         }
1333         return dentry;
1334 }
1335
1336 /* Transfers the children of @branch to @target.  It is an error if @target is
1337  * not a directory or if both @branch and @target contain a child dentry with
1338  * the same name. */
1339 static int do_overlay(struct wim_dentry *target, struct wim_dentry *branch)
1340 {
1341         struct rb_root *rb_root;
1342
1343         if (!dentry_is_directory(target)) {
1344                 ERROR("Cannot overlay directory `%s' over non-directory",
1345                       branch->file_name_utf8);
1346                 return WIMLIB_ERR_INVALID_OVERLAY;
1347         }
1348
1349         rb_root = &branch->d_inode->i_children;
1350         while (rb_root->rb_node) { /* While @branch has children... */
1351                 struct wim_dentry *child = rbnode_dentry(rb_root->rb_node);
1352                 /* Move @child to the directory @target */
1353                 unlink_dentry(child);
1354                 if (!dentry_add_child(target, child)) {
1355                         /* Revert the change to avoid leaking the directory tree
1356                          * rooted at @child */
1357                         dentry_add_child(branch, child);
1358                         ERROR("Overlay error: file `%s' already exists "
1359                               "as a child of `%s'",
1360                               child->file_name_utf8, target->file_name_utf8);
1361                         return WIMLIB_ERR_INVALID_OVERLAY;
1362                 }
1363         }
1364         return 0;
1365
1366 }
1367
1368 /* Attach or overlay a branch onto the WIM image.
1369  *
1370  * @root_p:
1371  *      Pointer to the root of the WIM image, or pointer to NULL if it has not
1372  *      been created yet.
1373  * @branch
1374  *      Branch to add.
1375  * @target_path:
1376  *      Path in the WIM image to add the branch, with leading and trailing
1377  *      slashes stripped.
1378  */
1379 static int attach_branch(struct wim_dentry **root_p,
1380                          struct wim_dentry *branch,
1381                          char *target_path)
1382 {
1383         char *slash;
1384         struct wim_dentry *dentry, *parent, *target;
1385
1386         if (*target_path == '\0') {
1387                 /* Target: root directory */
1388                 if (*root_p) {
1389                         /* Overlay on existing root */
1390                         return do_overlay(*root_p, branch);
1391                 } else  {
1392                         /* Set as root */
1393                         *root_p = branch;
1394                         return 0;
1395                 }
1396         }
1397
1398         /* Adding a non-root branch.  Create root if it hasn't been created
1399          * already. */
1400         if (!*root_p) {
1401                 *root_p = new_filler_directory("");
1402                 if (!*root_p)
1403                         return WIMLIB_ERR_NOMEM;
1404         }
1405
1406         /* Walk the path to the branch, creating filler directories as needed.
1407          * */
1408         parent = *root_p;
1409         while ((slash = strchr(target_path, '/'))) {
1410                 *slash = '\0';
1411                 dentry = get_dentry_child_with_name(parent, target_path);
1412                 if (!dentry) {
1413                         dentry = new_filler_directory(target_path);
1414                         if (!dentry)
1415                                 return WIMLIB_ERR_NOMEM;
1416                         dentry_add_child(parent, dentry);
1417                 }
1418                 parent = dentry;
1419                 target_path = slash;
1420                 /* Skip over slashes.  Note: this cannot overrun the length of
1421                  * the string because the last character cannot be a slash, as
1422                  * trailing slashes were tripped.  */
1423                 do {
1424                         ++target_path;
1425                 } while (*target_path == '/');
1426         }
1427
1428         /* If the target path already existed, overlay the branch onto it.
1429          * Otherwise, set the branch as the target path. */
1430         target = get_dentry_child_with_name(parent, branch->file_name_utf8);
1431         if (target) {
1432                 return do_overlay(target, branch);
1433         } else {
1434                 dentry_add_child(parent, branch);
1435                 return 0;
1436         }
1437 }
1438
1439 WIMLIBAPI int wimlib_add_image_multisource(WIMStruct *w,
1440                                            struct wimlib_capture_source *sources,
1441                                            size_t num_sources,
1442                                            const char *name,
1443                                            const char *config_str,
1444                                            size_t config_len,
1445                                            int add_image_flags,
1446                                            wimlib_progress_func_t progress_func)
1447 {
1448         int (*capture_tree)(struct wim_dentry **, const char *,
1449                             struct wim_lookup_table *,
1450                             struct wim_security_data *,
1451                             const struct capture_config *,
1452                             int, wimlib_progress_func_t, void *);
1453         void *extra_arg;
1454         struct wim_dentry *root_dentry;
1455         struct wim_dentry *branch;
1456         struct wim_security_data *sd;
1457         struct capture_config config;
1458         struct wim_image_metadata *imd;
1459         int ret;
1460
1461         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NTFS) {
1462 #ifdef WITH_NTFS_3G
1463                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
1464                         ERROR("Cannot dereference files when capturing directly from NTFS");
1465                         return WIMLIB_ERR_INVALID_PARAM;
1466                 }
1467                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
1468                         ERROR("Capturing UNIX owner and mode not supported "
1469                               "when capturing directly from NTFS");
1470                         return WIMLIB_ERR_INVALID_PARAM;
1471                 }
1472                 capture_tree = build_dentry_tree_ntfs;
1473                 extra_arg = &w->ntfs_vol;
1474 #else
1475                 ERROR("wimlib was compiled without support for NTFS-3g, so\n"
1476                       "        cannot capture a WIM image directly from a NTFS volume!");
1477                 return WIMLIB_ERR_UNSUPPORTED;
1478 #endif
1479         } else {
1480                 capture_tree = build_dentry_tree;
1481                 extra_arg = NULL;
1482         }
1483
1484 #if defined(__CYGWIN__) || defined(__WIN32__)
1485         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) {
1486                 ERROR("Capturing UNIX-specific data is not supported on Windows");
1487                 return WIMLIB_ERR_INVALID_PARAM;
1488         }
1489         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE) {
1490                 ERROR("Dereferencing symbolic links is not supported on Windows");
1491                 return WIMLIB_ERR_INVALID_PARAM;
1492         }
1493 #endif
1494
1495         if (!name || !*name) {
1496                 ERROR("Must specify a non-empty string for the image name");
1497                 return WIMLIB_ERR_INVALID_PARAM;
1498         }
1499
1500         if (w->hdr.total_parts != 1) {
1501                 ERROR("Cannot add an image to a split WIM");
1502                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1503         }
1504
1505         if (wimlib_image_name_in_use(w, name)) {
1506                 ERROR("There is already an image named \"%s\" in `%s'",
1507                       name, w->filename);
1508                 return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1509         }
1510
1511         if (!config_str) {
1512                 DEBUG("Using default capture configuration");
1513                 config_str = default_config;
1514                 config_len = strlen(default_config);
1515         }
1516         ret = init_capture_config(&config, config_str, config_len);
1517         if (ret)
1518                 goto out;
1519
1520         DEBUG("Allocating security data");
1521         sd = CALLOC(1, sizeof(struct wim_security_data));
1522         if (!sd) {
1523                 ret = WIMLIB_ERR_NOMEM;
1524                 goto out_destroy_capture_config;
1525         }
1526         sd->total_length = 8;
1527         sd->refcnt = 1;
1528
1529         DEBUG("Using %zu capture sources", num_sources);
1530         canonicalize_targets(sources, num_sources);
1531         sort_sources(sources, num_sources);
1532         ret = check_sorted_sources(sources, num_sources, add_image_flags);
1533         if (ret) {
1534                 ret = WIMLIB_ERR_INVALID_PARAM;
1535                 goto out_free_security_data;
1536         }
1537
1538         DEBUG("Building dentry tree.");
1539         if (num_sources == 0) {
1540                 root_dentry = new_filler_directory("");
1541                 if (!root_dentry) {
1542                         ret = WIMLIB_ERR_NOMEM;
1543                         goto out_free_security_data;
1544                 }
1545         } else {
1546                 size_t i;
1547
1548 #if defined(__CYGWIN__) || defined(__WIN32__)
1549                 win32_acquire_privilege(SE_BACKUP_NAME);
1550                 win32_acquire_privilege(SE_SECURITY_NAME);
1551                 win32_acquire_privilege(SE_TAKE_OWNERSHIP_NAME);
1552 #endif
1553                 root_dentry = NULL;
1554                 i = 0;
1555                 do {
1556                         int flags;
1557                         union wimlib_progress_info progress;
1558
1559                         DEBUG("Building dentry tree for source %zu of %zu "
1560                               "(\"%s\" => \"%s\")", i + 1, num_sources,
1561                               sources[i].fs_source_path,
1562                               sources[i].wim_target_path);
1563                         if (progress_func) {
1564                                 memset(&progress, 0, sizeof(progress));
1565                                 progress.scan.source = sources[i].fs_source_path;
1566                                 progress.scan.wim_target_path = sources[i].wim_target_path;
1567                                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_BEGIN, &progress);
1568                         }
1569                         ret = capture_config_set_prefix(&config,
1570                                                         sources[i].fs_source_path);
1571                         if (ret)
1572                                 goto out_free_dentry_tree;
1573                         flags = add_image_flags | WIMLIB_ADD_IMAGE_FLAG_SOURCE;
1574                         if (!*sources[i].wim_target_path)
1575                                 flags |= WIMLIB_ADD_IMAGE_FLAG_ROOT;
1576                         ret = (*capture_tree)(&branch, sources[i].fs_source_path,
1577                                               w->lookup_table, sd,
1578                                               &config,
1579                                               flags,
1580                                               progress_func, extra_arg);
1581                         if (ret) {
1582                                 ERROR("Failed to build dentry tree for `%s'",
1583                                       sources[i].fs_source_path);
1584                                 goto out_free_dentry_tree;
1585                         }
1586                         if (branch) {
1587                                 /* Use the target name, not the source name, for
1588                                  * the root of each branch from a capture
1589                                  * source.  (This will also set the root dentry
1590                                  * of the entire image to be unnamed.) */
1591                                 ret = set_dentry_name(branch,
1592                                                       path_basename(sources[i].wim_target_path));
1593                                 if (ret)
1594                                         goto out_free_branch;
1595
1596                                 ret = attach_branch(&root_dentry, branch,
1597                                                     sources[i].wim_target_path);
1598                                 if (ret)
1599                                         goto out_free_branch;
1600                         }
1601                         if (progress_func)
1602                                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_END, &progress);
1603                 } while (++i != num_sources);
1604         }
1605
1606         DEBUG("Calculating full paths of dentries.");
1607         ret = for_dentry_in_tree(root_dentry, calculate_dentry_full_path, NULL);
1608         if (ret != 0)
1609                 goto out_free_dentry_tree;
1610
1611         ret = add_new_dentry_tree(w, root_dentry, sd);
1612         if (ret != 0)
1613                 goto out_free_dentry_tree;
1614
1615         imd = &w->image_metadata[w->hdr.image_count - 1];
1616
1617         ret = dentry_tree_fix_inodes(root_dentry, &imd->inode_list);
1618         if (ret != 0)
1619                 goto out_destroy_imd;
1620
1621         DEBUG("Assigning hard link group IDs");
1622         assign_inode_numbers(&imd->inode_list);
1623
1624         ret = xml_add_image(w, name);
1625         if (ret != 0)
1626                 goto out_destroy_imd;
1627
1628         if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_BOOT)
1629                 wimlib_set_boot_idx(w, w->hdr.image_count);
1630         ret = 0;
1631         goto out;
1632 out_destroy_imd:
1633         destroy_image_metadata(&w->image_metadata[w->hdr.image_count - 1],
1634                                w->lookup_table);
1635         w->hdr.image_count--;
1636         goto out;
1637 out_free_branch:
1638         free_dentry_tree(branch, w->lookup_table);
1639 out_free_dentry_tree:
1640         free_dentry_tree(root_dentry, w->lookup_table);
1641 out_free_security_data:
1642         free_security_data(sd);
1643 out_destroy_capture_config:
1644         destroy_capture_config(&config);
1645 out:
1646 #if defined(__CYGWIN__) || defined(__WIN32__)
1647         win32_release_privilege(SE_BACKUP_NAME);
1648         win32_release_privilege(SE_SECURITY_NAME);
1649         win32_release_privilege(SE_TAKE_OWNERSHIP_NAME);
1650 #endif
1651         return ret;
1652 }
1653
1654 WIMLIBAPI int wimlib_add_image(WIMStruct *w, const char *source,
1655                                const char *name, const char *config_str,
1656                                size_t config_len, int add_image_flags,
1657                                wimlib_progress_func_t progress_func)
1658 {
1659         if (!source || !*source)
1660                 return WIMLIB_ERR_INVALID_PARAM;
1661
1662         char *fs_source_path = STRDUP(source);
1663         int ret;
1664         struct wimlib_capture_source capture_src = {
1665                 .fs_source_path = fs_source_path,
1666                 .wim_target_path = NULL,
1667                 .reserved = 0,
1668         };
1669         ret = wimlib_add_image_multisource(w, &capture_src, 1, name,
1670                                            config_str, config_len,
1671                                            add_image_flags, progress_func);
1672         FREE(fs_source_path);
1673         return ret;
1674 }