wimlib-imagex: Tweak invalid image error message
[wimlib] / programs / imagex.c
1 /*
2  * imagex.c
3  *
4  * Use wimlib to create, modify, extract, mount, unmount, or display information
5  * about a WIM file
6  */
7
8 /*
9  * Copyright (C) 2012, 2013 Eric Biggers
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h" /* Need for PACKAGE_VERSION, etc. */
27 #endif
28
29 #include "wimlib.h"
30 #include "wimlib_tchar.h"
31
32 #include <ctype.h>
33 #include <errno.h>
34
35 #include <inttypes.h>
36 #include <libgen.h>
37 #include <limits.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/stat.h>
42 #include <unistd.h>
43 #include <locale.h>
44
45 #ifdef HAVE_ALLOCA_H
46 #  include <alloca.h>
47 #endif
48
49 #ifdef __WIN32__
50 #  include "imagex-win32.h"
51 #  define tbasename     win32_wbasename
52 #  define OS_PREFERRED_PATH_SEPARATOR L'\\'
53 #  define OS_PREFERRED_PATH_SEPARATOR_STRING L"\\"
54 #else /* __WIN32__ */
55 #  include <glob.h>
56 #  include <getopt.h>
57 #  include <langinfo.h>
58 #  define tbasename     basename
59 #  define OS_PREFERRED_PATH_SEPARATOR '/'
60 #  define OS_PREFERRED_PATH_SEPARATOR_STRING "/"
61 static inline void set_fd_to_binary_mode(int fd)
62 {
63 }
64 #endif /* !__WIN32 */
65
66 /* Don't confuse the user by presenting the mounting commands on Windows when
67  * they will never work.  However on UNIX-like systems we always present them,
68  * even if WITH_FUSE is not defined at this point, as to not tie the build of
69  * wimlib-imagex to a specific build of wimlib.  */
70 #ifdef __WIN32__
71 #  define WIM_MOUNTING_SUPPORTED 0
72 #else
73 #  define WIM_MOUNTING_SUPPORTED 1
74 #endif
75
76 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
77
78 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (tchar**)argv, T(""), \
79                                 opts, NULL)) != -1)
80
81 enum {
82         CMD_NONE = -1,
83         CMD_APPEND = 0,
84         CMD_APPLY,
85         CMD_CAPTURE,
86         CMD_DELETE,
87         CMD_DIR,
88         CMD_EXPORT,
89         CMD_EXTRACT,
90         CMD_INFO,
91         CMD_JOIN,
92 #if WIM_MOUNTING_SUPPORTED
93         CMD_MOUNT,
94         CMD_MOUNTRW,
95 #endif
96         CMD_OPTIMIZE,
97         CMD_SPLIT,
98 #if WIM_MOUNTING_SUPPORTED
99         CMD_UNMOUNT,
100 #endif
101         CMD_UPDATE,
102         CMD_MAX,
103 };
104
105 static void usage(int cmd, FILE *fp);
106 static void usage_all(FILE *fp);
107 static void recommend_man_page(int cmd, FILE *fp);
108 static const tchar *get_cmd_string(int cmd, bool nospace);
109
110 static int imagex_progress_func(enum wimlib_progress_msg msg,
111                                 const union wimlib_progress_info *info);
112
113 static bool imagex_be_quiet = false;
114 static FILE *imagex_info_file;
115
116 #define imagex_printf(format, ...) \
117                 tfprintf(imagex_info_file, format, ##__VA_ARGS__)
118
119 enum {
120         IMAGEX_ALLOW_OTHER_OPTION,
121         IMAGEX_BOOT_OPTION,
122         IMAGEX_CHECK_OPTION,
123         IMAGEX_COMMAND_OPTION,
124         IMAGEX_COMMIT_OPTION,
125         IMAGEX_COMPRESS_OPTION,
126         IMAGEX_CONFIG_OPTION,
127         IMAGEX_DEBUG_OPTION,
128         IMAGEX_DELTA_FROM_OPTION,
129         IMAGEX_DEREFERENCE_OPTION,
130         IMAGEX_DEST_DIR_OPTION,
131         IMAGEX_EXTRACT_XML_OPTION,
132         IMAGEX_FLAGS_OPTION,
133         IMAGEX_FORCE_OPTION,
134         IMAGEX_HARDLINK_OPTION,
135         IMAGEX_HEADER_OPTION,
136         IMAGEX_INCLUDE_INVALID_NAMES_OPTION,
137         IMAGEX_LAZY_OPTION,
138         IMAGEX_LOOKUP_TABLE_OPTION,
139         IMAGEX_METADATA_OPTION,
140         IMAGEX_NORPFIX_OPTION,
141         IMAGEX_NOCHECK_OPTION,
142         IMAGEX_NO_ACLS_OPTION,
143         IMAGEX_NOT_PIPABLE_OPTION,
144         IMAGEX_PATH_OPTION,
145         IMAGEX_PIPABLE_OPTION,
146         IMAGEX_REBUILD_OPTION,
147         IMAGEX_RECOMPRESS_OPTION,
148         IMAGEX_RECURSIVE_OPTION,
149         IMAGEX_REF_OPTION,
150         IMAGEX_RESUME_OPTION,
151         IMAGEX_RPFIX_OPTION,
152         IMAGEX_SOFT_OPTION,
153         IMAGEX_SOURCE_LIST_OPTION,
154         IMAGEX_STAGING_DIR_OPTION,
155         IMAGEX_STREAMS_INTERFACE_OPTION,
156         IMAGEX_STRICT_ACLS_OPTION,
157         IMAGEX_SYMLINK_OPTION,
158         IMAGEX_THREADS_OPTION,
159         IMAGEX_TO_STDOUT_OPTION,
160         IMAGEX_UNIX_DATA_OPTION,
161         IMAGEX_UPDATE_OF_OPTION,
162         IMAGEX_VERBOSE_OPTION,
163         IMAGEX_XML_OPTION,
164 };
165
166 static const struct option apply_options[] = {
167         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
168         {T("hardlink"),    no_argument,       NULL, IMAGEX_HARDLINK_OPTION},
169         {T("symlink"),     no_argument,       NULL, IMAGEX_SYMLINK_OPTION},
170         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
171         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
172         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
173         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
174         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
175         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
176         {T("rpfix"),       no_argument,       NULL, IMAGEX_RPFIX_OPTION},
177         {T("norpfix"),     no_argument,       NULL, IMAGEX_NORPFIX_OPTION},
178         {T("include-invalid-names"), no_argument,       NULL, IMAGEX_INCLUDE_INVALID_NAMES_OPTION},
179
180         /* --resume is undocumented for now as it needs improvement.  */
181         {T("resume"),      no_argument,       NULL, IMAGEX_RESUME_OPTION},
182         {NULL, 0, NULL, 0},
183 };
184
185 static const struct option capture_or_append_options[] = {
186         {T("boot"),        no_argument,       NULL, IMAGEX_BOOT_OPTION},
187         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
188         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
189         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
190         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
191         {T("config"),      required_argument, NULL, IMAGEX_CONFIG_OPTION},
192         {T("dereference"), no_argument,       NULL, IMAGEX_DEREFERENCE_OPTION},
193         {T("flags"),       required_argument, NULL, IMAGEX_FLAGS_OPTION},
194         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
195         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
196         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
197         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
198         {T("source-list"), no_argument,       NULL, IMAGEX_SOURCE_LIST_OPTION},
199         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
200         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
201         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
202         {T("rpfix"),       no_argument,       NULL, IMAGEX_RPFIX_OPTION},
203         {T("norpfix"),     no_argument,       NULL, IMAGEX_NORPFIX_OPTION},
204         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
205         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
206         {T("update-of"),   required_argument, NULL, IMAGEX_UPDATE_OF_OPTION},
207         {T("delta-from"),  required_argument, NULL, IMAGEX_DELTA_FROM_OPTION},
208         {NULL, 0, NULL, 0},
209 };
210
211 static const struct option delete_options[] = {
212         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
213         {T("soft"),  no_argument, NULL, IMAGEX_SOFT_OPTION},
214         {NULL, 0, NULL, 0},
215 };
216
217 static const struct option dir_options[] = {
218         {T("path"), required_argument, NULL, IMAGEX_PATH_OPTION},
219         {NULL, 0, NULL, 0},
220 };
221
222 static const struct option export_options[] = {
223         {T("boot"),        no_argument,       NULL, IMAGEX_BOOT_OPTION},
224         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
225         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
226         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
227         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
228         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
229         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
230         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
231         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
232         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
233         {NULL, 0, NULL, 0},
234 };
235
236 static const struct option extract_options[] = {
237         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
238         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
239         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
240         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
241         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
242         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
243         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
244         {T("dest-dir"),    required_argument, NULL, IMAGEX_DEST_DIR_OPTION},
245         {T("to-stdout"),   no_argument,       NULL, IMAGEX_TO_STDOUT_OPTION},
246         {T("include-invalid-names"), no_argument, NULL, IMAGEX_INCLUDE_INVALID_NAMES_OPTION},
247         {NULL, 0, NULL, 0},
248 };
249
250 static const struct option info_options[] = {
251         {T("boot"),         no_argument,       NULL, IMAGEX_BOOT_OPTION},
252         {T("check"),        no_argument,       NULL, IMAGEX_CHECK_OPTION},
253         {T("nocheck"),      no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
254         {T("no-check"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
255         {T("extract-xml"),  required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
256         {T("header"),       no_argument,       NULL, IMAGEX_HEADER_OPTION},
257         {T("lookup-table"), no_argument,       NULL, IMAGEX_LOOKUP_TABLE_OPTION},
258         {T("metadata"),     no_argument,       NULL, IMAGEX_METADATA_OPTION},
259         {T("xml"),          no_argument,       NULL, IMAGEX_XML_OPTION},
260         {NULL, 0, NULL, 0},
261 };
262
263 static const struct option join_options[] = {
264         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
265         {NULL, 0, NULL, 0},
266 };
267
268 static const struct option mount_options[] = {
269         {T("check"),             no_argument,       NULL, IMAGEX_CHECK_OPTION},
270         {T("debug"),             no_argument,       NULL, IMAGEX_DEBUG_OPTION},
271         {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
272         {T("ref"),               required_argument, NULL, IMAGEX_REF_OPTION},
273         {T("staging-dir"),       required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
274         {T("unix-data"),         no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
275         {T("allow-other"),       no_argument,       NULL, IMAGEX_ALLOW_OTHER_OPTION},
276         {NULL, 0, NULL, 0},
277 };
278
279 static const struct option optimize_options[] = {
280         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
281         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
282         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
283         {T("recompress"),  no_argument,       NULL, IMAGEX_RECOMPRESS_OPTION},
284         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
285         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
286         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
287         {NULL, 0, NULL, 0},
288 };
289
290 static const struct option split_options[] = {
291         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
292         {NULL, 0, NULL, 0},
293 };
294
295 static const struct option unmount_options[] = {
296         {T("commit"),  no_argument, NULL, IMAGEX_COMMIT_OPTION},
297         {T("check"),   no_argument, NULL, IMAGEX_CHECK_OPTION},
298         {T("rebuild"), no_argument, NULL, IMAGEX_REBUILD_OPTION},
299         {T("lazy"),    no_argument, NULL, IMAGEX_LAZY_OPTION},
300         {NULL, 0, NULL, 0},
301 };
302
303 static const struct option update_options[] = {
304         /* Careful: some of the options here set the defaults for update
305          * commands, but the flags given to an actual update command (and not to
306          * `imagex update' itself are also handled in
307          * update_command_add_option().  */
308         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
309         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
310         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
311         {T("command"),     required_argument, NULL, IMAGEX_COMMAND_OPTION},
312
313         /* Default delete options */
314         {T("force"),       no_argument,       NULL, IMAGEX_FORCE_OPTION},
315         {T("recursive"),   no_argument,       NULL, IMAGEX_RECURSIVE_OPTION},
316
317         /* Global add option */
318         {T("config"),      required_argument, NULL, IMAGEX_CONFIG_OPTION},
319
320         /* Default add options */
321         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
322         {T("dereference"), no_argument,       NULL, IMAGEX_DEREFERENCE_OPTION},
323         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
324         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
325         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
326         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
327
328         {NULL, 0, NULL, 0},
329 };
330
331 #if 0
332 #       define _format_attribute(type, format_str, args_start) \
333                         __attribute__((format(type, format_str, args_start)))
334 #else
335 #       define _format_attribute(type, format_str, args_start)
336 #endif
337
338 /* Print formatted error message to stderr. */
339 static void _format_attribute(printf, 1, 2)
340 imagex_error(const tchar *format, ...)
341 {
342         va_list va;
343         va_start(va, format);
344         tfputs(T("ERROR: "), stderr);
345         tvfprintf(stderr, format, va);
346         tputc(T('\n'), stderr);
347         va_end(va);
348 }
349
350 /* Print formatted error message to stderr. */
351 static void _format_attribute(printf, 1, 2)
352 imagex_error_with_errno(const tchar *format, ...)
353 {
354         int errno_save = errno;
355         va_list va;
356         va_start(va, format);
357         tfputs(T("ERROR: "), stderr);
358         tvfprintf(stderr, format, va);
359         tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
360         va_end(va);
361 }
362
363 static int
364 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
365 {
366         if (image == WIMLIB_NO_IMAGE) {
367                 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
368                              "       Please specify a 1-based image index or "
369                              "image name.  To list the images\n"
370                              "       contained in the WIM archive, run\n"
371                              "\n"
372                              "           %"TS" \"%"TS"\"\n"),
373                              image_name, wim_name,
374                              get_cmd_string(CMD_INFO, false), wim_name);
375                 return WIMLIB_ERR_INVALID_IMAGE;
376         }
377         return 0;
378 }
379
380 static int
381 verify_image_is_single(int image)
382 {
383         if (image == WIMLIB_ALL_IMAGES) {
384                 imagex_error(T("Cannot specify all images for this action!"));
385                 return WIMLIB_ERR_INVALID_IMAGE;
386         }
387         return 0;
388 }
389
390 static int
391 verify_image_exists_and_is_single(int image, const tchar *image_name,
392                                   const tchar *wim_name)
393 {
394         int ret;
395         ret = verify_image_exists(image, image_name, wim_name);
396         if (ret == 0)
397                 ret = verify_image_is_single(image);
398         return ret;
399 }
400
401 /* Parse the argument to --compress */
402 static int
403 get_compression_type(const tchar *optarg)
404 {
405         if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
406                 return WIMLIB_COMPRESSION_TYPE_LZX;
407         else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
408                 return WIMLIB_COMPRESSION_TYPE_XPRESS;
409         else if (!tstrcasecmp(optarg, T("none")))
410                 return WIMLIB_COMPRESSION_TYPE_NONE;
411         else {
412                 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
413                              "\"maximum\", \"fast\", or \"none\"."), optarg);
414                 return WIMLIB_COMPRESSION_TYPE_INVALID;
415         }
416 }
417
418 struct refglob_set {
419         const tchar **globs;
420         unsigned num_globs;
421         unsigned num_alloc_globs;
422 };
423
424 #define REFGLOB_SET_INITIALIZER \
425         { .globs = NULL, .num_globs = 0, .num_alloc_globs = 0, }
426
427 #define REFGLOB_SET(_refglobs) \
428         struct refglob_set _refglobs = REFGLOB_SET_INITIALIZER
429
430 static int
431 refglob_set_append(struct refglob_set *set, const tchar *glob)
432 {
433         unsigned num_alloc_globs = set->num_alloc_globs;
434
435         if (set->num_globs == num_alloc_globs) {
436                 const tchar **new_globs;
437
438                 num_alloc_globs += 4;
439                 new_globs = realloc(set->globs, sizeof(set->globs[0]) * num_alloc_globs);
440                 if (!new_globs) {
441                         imagex_error(T("Out of memory!"));
442                         return -1;
443                 }
444                 set->globs = new_globs;
445                 set->num_alloc_globs = num_alloc_globs;
446         }
447         set->globs[set->num_globs++] = glob;
448         return 0;
449 }
450
451 static int
452 wim_reference_globs(WIMStruct *wim, struct refglob_set *set, int open_flags)
453 {
454         return wimlib_reference_resource_files(wim, set->globs, set->num_globs,
455                                                WIMLIB_REF_FLAG_GLOB_ENABLE,
456                                                open_flags,
457                                                imagex_progress_func);
458 }
459
460 static void
461 refglob_set_destroy(struct refglob_set *set)
462 {
463         free(set->globs);
464 }
465
466 static void
467 do_resource_not_found_warning(const tchar *wimfile,
468                               const struct wimlib_wim_info *info,
469                               const struct refglob_set *refglobs)
470 {
471         if (info->total_parts > 1) {
472                 if (refglobs->num_globs == 0) {
473                         imagex_error(T("\"%"TS"\" is part of a split WIM. "
474                                        "Use --ref to specify the other parts."),
475                                      wimfile);
476                 } else {
477                         imagex_error(T("Perhaps the '--ref' argument did not "
478                                        "specify all other parts of the split "
479                                        "WIM?"));
480                 }
481         } else {
482                 imagex_error(T("If this is a delta WIM, use the --ref argument "
483                                "to specify the WIM on which it is based."));
484         }
485 }
486
487 /* Returns the size of a file given its name, or -1 if the file does not exist
488  * or its size cannot be determined.  */
489 static off_t
490 file_get_size(const tchar *filename)
491 {
492         struct stat st;
493         if (tstat(filename, &st) == 0)
494                 return st.st_size;
495         else
496                 return (off_t)-1;
497 }
498
499 enum {
500         PARSE_STRING_SUCCESS = 0,
501         PARSE_STRING_FAILURE = 1,
502         PARSE_STRING_NONE = 2,
503 };
504
505 /*
506  * Parses a string token from an array of characters.
507  *
508  * Tokens are either whitespace-delimited, or double or single-quoted.
509  *
510  * @line_p:  Pointer to the pointer to the line of data.  Will be updated
511  *           to point past the string token iff the return value is
512  *           PARSE_STRING_SUCCESS.  If *len_p > 0, (*line_p)[*len_p - 1] must
513  *           be '\0'.
514  *
515  * @len_p:   @len_p initially stores the length of the line of data, which may
516  *           be 0, and it will be updated to the number of bytes remaining in
517  *           the line iff the return value is PARSE_STRING_SUCCESS.
518  *
519  * @fn_ret:  Iff the return value is PARSE_STRING_SUCCESS, a pointer to the
520  *           parsed string token will be returned here.
521  *
522  * Returns: PARSE_STRING_SUCCESS if a string token was successfully parsed; or
523  *          PARSE_STRING_FAILURE if the data was invalid due to a missing
524  *          closing quote; or PARSE_STRING_NONE if the line ended before the
525  *          beginning of a string token was found.
526  */
527 static int
528 parse_string(tchar **line_p, size_t *len_p, tchar **fn_ret)
529 {
530         size_t len = *len_p;
531         tchar *line = *line_p;
532         tchar *fn;
533         tchar quote_char;
534
535         /* Skip leading whitespace */
536         for (;;) {
537                 if (len == 0)
538                         return PARSE_STRING_NONE;
539                 if (!istspace(*line) && *line != T('\0'))
540                         break;
541                 line++;
542                 len--;
543         }
544         quote_char = *line;
545         if (quote_char == T('"') || quote_char == T('\'')) {
546                 /* Quoted string */
547                 line++;
548                 len--;
549                 fn = line;
550                 line = tmemchr(line, quote_char, len);
551                 if (!line) {
552                         imagex_error(T("Missing closing quote: %"TS), fn - 1);
553                         return PARSE_STRING_FAILURE;
554                 }
555         } else {
556                 /* Unquoted string.  Go until whitespace.  Line is terminated
557                  * by '\0', so no need to check 'len'. */
558                 fn = line;
559                 do {
560                         line++;
561                 } while (!istspace(*line) && *line != T('\0'));
562         }
563         *line = T('\0');
564         len -= line - fn;
565         *len_p = len;
566         *line_p = line;
567         *fn_ret = fn;
568         return PARSE_STRING_SUCCESS;
569 }
570
571 /* Parses a line of data (not an empty line or comment) in the source list file
572  * format.  (See the man page for 'wimlib-imagex capture' for details on this
573  * format and the meaning.)
574  *
575  * @line:  Line of data to be parsed.  line[len - 1] must be '\0', unless
576  *         len == 0.  The data in @line will be modified by this function call.
577  *
578  * @len:   Length of the line of data.
579  *
580  * @source:  On success, the capture source and target described by the line is
581  *           written into this destination.  Note that it will contain pointers
582  *           to data in the @line array.
583  *
584  * Returns true if the line was valid; false otherwise.  */
585 static bool
586 parse_source_list_line(tchar *line, size_t len,
587                        struct wimlib_capture_source *source)
588 {
589         /* SOURCE [DEST] */
590         int ret;
591         ret = parse_string(&line, &len, &source->fs_source_path);
592         if (ret != PARSE_STRING_SUCCESS)
593                 return false;
594         ret = parse_string(&line, &len, &source->wim_target_path);
595         if (ret == PARSE_STRING_NONE)
596                 source->wim_target_path = source->fs_source_path;
597         return ret != PARSE_STRING_FAILURE;
598 }
599
600 /* Returns %true if the given line of length @len > 0 is a comment or empty line
601  * in the source list file format. */
602 static bool
603 is_comment_line(const tchar *line, size_t len)
604 {
605         for (;;) {
606                 if (*line == T('#'))
607                         return true;
608                 if (!istspace(*line) && *line != T('\0'))
609                         return false;
610                 ++line;
611                 --len;
612                 if (len == 0)
613                         return true;
614         }
615 }
616
617 static ssize_t
618 text_file_count_lines(tchar **contents_p, size_t *nchars_p)
619 {
620         ssize_t nlines = 0;
621         tchar *contents = *contents_p;
622         size_t nchars = *nchars_p;
623         size_t i;
624
625         for (i = 0; i < nchars; i++)
626                 if (contents[i] == T('\n'))
627                         nlines++;
628
629         /* Handle last line not terminated by a newline */
630         if (nchars != 0 && contents[nchars - 1] != T('\n')) {
631                 contents = realloc(contents, (nchars + 1) * sizeof(tchar));
632                 if (!contents) {
633                         imagex_error(T("Out of memory!"));
634                         return -1;
635                 }
636                 contents[nchars] = T('\n');
637                 *contents_p = contents;
638                 nchars++;
639                 nlines++;
640         }
641         *nchars_p = nchars;
642         return nlines;
643 }
644
645 /* Parses a file in the source list format.  (See the man page for
646  * 'wimlib-imagex capture' for details on this format and the meaning.)
647  *
648  * @source_list_contents:  Contents of the source list file.  Note that this
649  *                         buffer will be modified to save memory allocations,
650  *                         and cannot be freed until the returned array of
651  *                         wimlib_capture_source's has also been freed.
652  *
653  * @source_list_nbytes:    Number of bytes of data in the @source_list_contents
654  *                         buffer.
655  *
656  * @nsources_ret:          On success, the length of the returned array is
657  *                         returned here.
658  *
659  * Returns:   An array of `struct wimlib_capture_source's that can be passed to
660  * the wimlib_add_image_multisource() function to specify how a WIM image is to
661  * be created.  */
662 static struct wimlib_capture_source *
663 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
664                   size_t *nsources_ret)
665 {
666         ssize_t nlines;
667         tchar *p;
668         struct wimlib_capture_source *sources;
669         size_t i, j;
670
671         nlines = text_file_count_lines(source_list_contents_p,
672                                        &source_list_nchars);
673         if (nlines < 0)
674                 return NULL;
675
676         /* Always allocate at least 1 slot, just in case the implementation of
677          * calloc() returns NULL if 0 bytes are requested. */
678         sources = calloc(nlines ?: 1, sizeof(*sources));
679         if (!sources) {
680                 imagex_error(T("out of memory"));
681                 return NULL;
682         }
683         p = *source_list_contents_p;
684         j = 0;
685         for (i = 0; i < nlines; i++) {
686                 /* XXX: Could use rawmemchr() here instead, but it may not be
687                  * available on all platforms. */
688                 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
689                 size_t len = endp - p + 1;
690                 *endp = T('\0');
691                 if (!is_comment_line(p, len)) {
692                         if (!parse_source_list_line(p, len, &sources[j++])) {
693                                 free(sources);
694                                 return NULL;
695                         }
696                 }
697                 p = endp + 1;
698
699         }
700         *nsources_ret = j;
701         return sources;
702 }
703
704
705 enum capture_config_section {
706         CAPTURE_CONFIG_NO_SECTION,
707         CAPTURE_CONFIG_EXCLUSION_SECTION,
708         CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION,
709         CAPTURE_CONFIG_IGNORE_SECTION,
710 };
711
712 enum {
713         CAPTURE_CONFIG_INVALID_SECTION,
714         CAPTURE_CONFIG_CHANGED_SECTION,
715         CAPTURE_CONFIG_SAME_SECTION,
716 };
717
718 static int
719 check_config_section(tchar *line, size_t len,
720                      enum capture_config_section *cur_section)
721 {
722         while (istspace(*line))
723                 line++;
724
725         if (*line != T('['))
726                 return CAPTURE_CONFIG_SAME_SECTION;
727
728         line++;
729         tchar *endbrace = tstrrchr(line, T(']'));
730         if (!endbrace)
731                 return CAPTURE_CONFIG_SAME_SECTION;
732
733         if (!tmemcmp(line, T("ExclusionList"), endbrace - line)) {
734                 *cur_section = CAPTURE_CONFIG_EXCLUSION_SECTION;
735         } else if (!tmemcmp(line, T("ExclusionException"), endbrace - line)) {
736                 *cur_section = CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION;
737         } else if (!tmemcmp(line, T("CompressionExclusionList"), endbrace - line)) {
738                 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
739                 tfputs(T("WARNING: Ignoring [CompressionExclusionList] section "
740                          "of capture config file\n"),
741                        stderr);
742         } else if (!tmemcmp(line, T("AlignmentList"), endbrace - line)) {
743                 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
744                 tfputs(T("WARNING: Ignoring [AlignmentList] section "
745                          "of capture config file\n"),
746                        stderr);
747         } else {
748                 imagex_error(T("Invalid capture config file section \"%"TS"\""),
749                              line - 1);
750                 return CAPTURE_CONFIG_INVALID_SECTION;
751         }
752         return CAPTURE_CONFIG_CHANGED_SECTION;
753 }
754
755
756 static bool
757 pattern_list_add_pattern(struct wimlib_pattern_list *pat_list,
758                          tchar *pat)
759 {
760         if (pat_list->num_pats == pat_list->num_allocated_pats) {
761                 tchar **pats;
762                 size_t num_allocated_pats = pat_list->num_pats + 8;
763
764                 pats = realloc(pat_list->pats,
765                                num_allocated_pats * sizeof(pat_list->pats[0]));
766                 if (!pats) {
767                         imagex_error(T("Out of memory!"));
768                         return false;
769                 }
770                 pat_list->pats = pats;
771                 pat_list->num_allocated_pats = num_allocated_pats;
772         }
773         pat_list->pats[pat_list->num_pats++] = pat;
774         return true;
775 }
776
777 static bool
778 parse_capture_config_line(tchar *line, size_t len,
779                           enum capture_config_section *cur_section,
780                           struct wimlib_capture_config *config)
781 {
782         tchar *filename;
783         int ret;
784
785         ret = check_config_section(line, len, cur_section);
786         if (ret == CAPTURE_CONFIG_INVALID_SECTION)
787                 return false;
788         if (ret == CAPTURE_CONFIG_CHANGED_SECTION)
789                 return true;
790
791         switch (*cur_section) {
792         case CAPTURE_CONFIG_NO_SECTION:
793                 imagex_error(T("Line \"%"TS"\" is not in a section "
794                                "(such as [ExclusionList]"), line);
795                 return false;
796         case CAPTURE_CONFIG_EXCLUSION_SECTION:
797                 if (parse_string(&line, &len, &filename) != PARSE_STRING_SUCCESS)
798                         return false;
799                 return pattern_list_add_pattern(&config->exclusion_pats,
800                                                 filename);
801         case CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION:
802                 if (parse_string(&line, &len, &filename) != PARSE_STRING_SUCCESS)
803                         return false;
804                 return pattern_list_add_pattern(&config->exclusion_exception_pats,
805                                                 filename);
806         case CAPTURE_CONFIG_IGNORE_SECTION:
807                 return true;
808         }
809         return false;
810 }
811
812 static int
813 parse_capture_config(tchar **contents_p, size_t nchars,
814                      struct wimlib_capture_config *config)
815 {
816         ssize_t nlines;
817         tchar *p;
818         size_t i;
819         enum capture_config_section cur_section;
820
821         memset(config, 0, sizeof(*config));
822
823         nlines = text_file_count_lines(contents_p, &nchars);
824         if (nlines < 0)
825                 return -1;
826
827         cur_section = CAPTURE_CONFIG_NO_SECTION;
828         p = *contents_p;
829         for (i = 0; i < nlines; i++) {
830                 tchar *endp = tmemchr(p, T('\n'), nchars);
831                 size_t len = endp - p + 1;
832                 *endp = T('\0');
833                 if (!is_comment_line(p, len))
834                         if (!parse_capture_config_line(p, len, &cur_section, config))
835                                 return -1;
836                 p = endp + 1;
837
838         }
839         return 0;
840 }
841
842 /* Reads the contents of a file into memory. */
843 static char *
844 file_get_contents(const tchar *filename, size_t *len_ret)
845 {
846         struct stat stbuf;
847         void *buf = NULL;
848         size_t len;
849         FILE *fp;
850
851         if (tstat(filename, &stbuf) != 0) {
852                 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
853                 goto out;
854         }
855         len = stbuf.st_size;
856
857         fp = tfopen(filename, T("rb"));
858         if (!fp) {
859                 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
860                 goto out;
861         }
862
863         buf = malloc(len ? len : 1);
864         if (!buf) {
865                 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
866                                "contents of file \"%"TS"\""), len, filename);
867                 goto out_fclose;
868         }
869         if (fread(buf, 1, len, fp) != len) {
870                 imagex_error_with_errno(T("Failed to read %zu bytes from the "
871                                           "file \"%"TS"\""), len, filename);
872                 goto out_free_buf;
873         }
874         *len_ret = len;
875         goto out_fclose;
876 out_free_buf:
877         free(buf);
878         buf = NULL;
879 out_fclose:
880         fclose(fp);
881 out:
882         return buf;
883 }
884
885 /* Read standard input until EOF and return the full contents in a malloc()ed
886  * buffer and the number of bytes of data in @len_ret.  Returns NULL on read
887  * error. */
888 static char *
889 stdin_get_contents(size_t *len_ret)
890 {
891         /* stdin can, of course, be a pipe or other non-seekable file, so the
892          * total length of the data cannot be pre-determined */
893         char *buf = NULL;
894         size_t newlen = 1024;
895         size_t pos = 0;
896         size_t inc = 1024;
897         for (;;) {
898                 char *p = realloc(buf, newlen);
899                 size_t bytes_read, bytes_to_read;
900                 if (!p) {
901                         imagex_error(T("out of memory while reading stdin"));
902                         break;
903                 }
904                 buf = p;
905                 bytes_to_read = newlen - pos;
906                 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
907                 pos += bytes_read;
908                 if (bytes_read != bytes_to_read) {
909                         if (feof(stdin)) {
910                                 *len_ret = pos;
911                                 return buf;
912                         } else {
913                                 imagex_error_with_errno(T("error reading stdin"));
914                                 break;
915                         }
916                 }
917                 newlen += inc;
918                 inc *= 3;
919                 inc /= 2;
920         }
921         free(buf);
922         return NULL;
923 }
924
925
926 static tchar *
927 translate_text_to_tstr(char *text, size_t num_bytes, size_t *num_tchars_ret)
928 {
929 #ifndef __WIN32__
930         /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
931          * */
932         *num_tchars_ret = num_bytes;
933         return text;
934 #else /* !__WIN32__ */
935         /* On Windows, translate the text to UTF-16LE */
936         wchar_t *text_wstr;
937         size_t num_wchars;
938
939         if (num_bytes >= 2 &&
940             ((text[0] == 0xff && text[1] == 0xfe) ||
941              (text[0] <= 0x7f && text[1] == 0x00)))
942         {
943                 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
944                  * with something that looks like an ASCII character encoded as
945                  * a UTF-16LE code unit.  Assume the file is encoded as
946                  * UTF-16LE.  This is not a 100% reliable check. */
947                 num_wchars = num_bytes / 2;
948                 text_wstr = (wchar_t*)text;
949         } else {
950                 /* File does not look like UTF-16LE.  Assume it is encoded in
951                  * the current Windows code page.  I think these are always
952                  * ASCII-compatible, so any so-called "plain-text" (ASCII) files
953                  * should work as expected. */
954                 text_wstr = win32_mbs_to_wcs(text,
955                                              num_bytes,
956                                              &num_wchars);
957                 free(text);
958         }
959         *num_tchars_ret = num_wchars;
960         return text_wstr;
961 #endif /* __WIN32__ */
962 }
963
964 static tchar *
965 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
966 {
967         char *contents;
968         size_t num_bytes;
969
970         contents = file_get_contents(filename, &num_bytes);
971         if (!contents)
972                 return NULL;
973         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
974 }
975
976 static tchar *
977 stdin_get_text_contents(size_t *num_tchars_ret)
978 {
979         char *contents;
980         size_t num_bytes;
981
982         contents = stdin_get_contents(&num_bytes);
983         if (!contents)
984                 return NULL;
985         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
986 }
987
988 #define TO_PERCENT(numerator, denominator) \
989         (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
990
991 /* Given an enumerated value for WIM compression type, return a descriptive
992  * string. */
993 static const tchar *
994 get_data_type(int ctype)
995 {
996         switch (ctype) {
997         case WIMLIB_COMPRESSION_TYPE_NONE:
998                 return T("uncompressed");
999         case WIMLIB_COMPRESSION_TYPE_LZX:
1000                 return T("LZX-compressed");
1001         case WIMLIB_COMPRESSION_TYPE_XPRESS:
1002                 return T("XPRESS-compressed");
1003         }
1004         return NULL;
1005 }
1006
1007 #define GIBIBYTE_MIN_NBYTES 10000000000ULL
1008 #define MEBIBYTE_MIN_NBYTES 10000000ULL
1009 #define KIBIBYTE_MIN_NBYTES 10000ULL
1010
1011 static unsigned
1012 get_unit(uint64_t total_bytes, const tchar **name_ret)
1013 {
1014         if (total_bytes >= GIBIBYTE_MIN_NBYTES) {
1015                 *name_ret = T("GiB");
1016                 return 30;
1017         } else if (total_bytes >= MEBIBYTE_MIN_NBYTES) {
1018                 *name_ret = T("MiB");
1019                 return 20;
1020         } else if (total_bytes >= KIBIBYTE_MIN_NBYTES) {
1021                 *name_ret = T("KiB");
1022                 return 10;
1023         } else {
1024                 *name_ret = T("bytes");
1025                 return 0;
1026         }
1027 }
1028
1029 /* Progress callback function passed to various wimlib functions. */
1030 static int
1031 imagex_progress_func(enum wimlib_progress_msg msg,
1032                      const union wimlib_progress_info *info)
1033 {
1034         unsigned percent_done;
1035         unsigned unit_shift;
1036         const tchar *unit_name;
1037         if (imagex_be_quiet)
1038                 return 0;
1039         switch (msg) {
1040         case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
1041                 unit_shift = get_unit(info->write_streams.total_bytes, &unit_name);
1042                 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
1043                                           info->write_streams.total_bytes);
1044
1045                 if (info->write_streams.completed_streams == 0) {
1046                         const tchar *data_type;
1047
1048                         data_type = get_data_type(info->write_streams.compression_type);
1049                         imagex_printf(T("Writing %"TS" data using %u thread%"TS"\n"),
1050                                 data_type, info->write_streams.num_threads,
1051                                 (info->write_streams.num_threads == 1) ? T("") : T("s"));
1052                 }
1053                 if (info->write_streams.total_parts <= 1) {
1054                         imagex_printf(T("\r%"PRIu64" %"TS" of %"PRIu64" %"TS" (uncompressed) "
1055                                 "written (%u%% done)"),
1056                                 info->write_streams.completed_bytes >> unit_shift,
1057                                 unit_name,
1058                                 info->write_streams.total_bytes >> unit_shift,
1059                                 unit_name,
1060                                 percent_done);
1061                 } else {
1062                         imagex_printf(T("\rWriting resources from part %u of %u: "
1063                                   "%"PRIu64 " %"TS" of %"PRIu64" %"TS" (%u%%) written"),
1064                                 (info->write_streams.completed_parts ==
1065                                         info->write_streams.total_parts) ?
1066                                                 info->write_streams.completed_parts :
1067                                                 info->write_streams.completed_parts + 1,
1068                                 info->write_streams.total_parts,
1069                                 info->write_streams.completed_bytes >> unit_shift,
1070                                 unit_name,
1071                                 info->write_streams.total_bytes >> unit_shift,
1072                                 unit_name,
1073                                 percent_done);
1074                 }
1075                 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
1076                         imagex_printf(T("\n"));
1077                 break;
1078         case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
1079                 imagex_printf(T("Scanning \"%"TS"\""), info->scan.source);
1080                 if (*info->scan.wim_target_path) {
1081                         imagex_printf(T(" (loading as WIM path: "
1082                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING"%"TS"\")...\n"),
1083                                info->scan.wim_target_path);
1084                 } else {
1085                         imagex_printf(T(" (loading as root of WIM image)...\n"));
1086                 }
1087                 break;
1088         case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
1089                 switch (info->scan.status) {
1090                 case WIMLIB_SCAN_DENTRY_OK:
1091                         imagex_printf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
1092                         break;
1093                 case WIMLIB_SCAN_DENTRY_EXCLUDED:
1094                         imagex_printf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
1095                         break;
1096                 case WIMLIB_SCAN_DENTRY_UNSUPPORTED:
1097                         imagex_printf(T("WARNING: Excluding unsupported file or directory\n"
1098                                         "         \"%"TS"\" from capture\n"), info->scan.cur_path);
1099                         break;
1100                 }
1101                 break;
1102         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
1103                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1104                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1105                                           info->integrity.total_bytes);
1106                 imagex_printf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" %"TS" "
1107                         "of %"PRIu64" %"TS" (%u%%) done"),
1108                         info->integrity.filename,
1109                         info->integrity.completed_bytes >> unit_shift,
1110                         unit_name,
1111                         info->integrity.total_bytes >> unit_shift,
1112                         unit_name,
1113                         percent_done);
1114                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1115                         imagex_printf(T("\n"));
1116                 break;
1117         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
1118                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1119                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1120                                           info->integrity.total_bytes);
1121                 imagex_printf(T("\rCalculating integrity table for WIM: %"PRIu64" %"TS" "
1122                           "of %"PRIu64" %"TS" (%u%%) done"),
1123                         info->integrity.completed_bytes >> unit_shift,
1124                         unit_name,
1125                         info->integrity.total_bytes >> unit_shift,
1126                         unit_name,
1127                         percent_done);
1128                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1129                         imagex_printf(T("\n"));
1130                 break;
1131         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
1132                 imagex_printf(T("Applying image %d (\"%"TS"\") from \"%"TS"\" "
1133                           "to %"TS" \"%"TS"\"\n"),
1134                         info->extract.image,
1135                         info->extract.image_name,
1136                         info->extract.wimfile_name,
1137                         ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
1138                          T("NTFS volume") : T("directory")),
1139                         info->extract.target);
1140                 break;
1141         case WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN:
1142                 imagex_printf(T("Extracting "
1143                           "\""WIMLIB_WIM_PATH_SEPARATOR_STRING"%"TS"\" from image %d (\"%"TS"\") "
1144                           "in \"%"TS"\" to \"%"TS"\"\n"),
1145                         info->extract.extract_root_wim_source_path,
1146                         info->extract.image,
1147                         info->extract.image_name,
1148                         info->extract.wimfile_name,
1149                         info->extract.target);
1150                 break;
1151         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1152                 percent_done = TO_PERCENT(info->extract.completed_bytes,
1153                                           info->extract.total_bytes);
1154                 unit_shift = get_unit(info->extract.total_bytes, &unit_name);
1155                 imagex_printf(T("\rExtracting files: "
1156                           "%"PRIu64" %"TS" of %"PRIu64" %"TS" (%u%%) done"),
1157                         info->extract.completed_bytes >> unit_shift,
1158                         unit_name,
1159                         info->extract.total_bytes >> unit_shift,
1160                         unit_name,
1161                         percent_done);
1162                 if (info->extract.completed_bytes >= info->extract.total_bytes)
1163                         imagex_printf(T("\n"));
1164                 break;
1165         case WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN:
1166                 if (info->extract.total_parts != 1) {
1167                         imagex_printf(T("\nReading split pipable WIM part %u of %u\n"),
1168                                       info->extract.part_number,
1169                                       info->extract.total_parts);
1170                 }
1171                 break;
1172         case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1173                 if (info->extract.extract_root_wim_source_path[0] == T('\0'))
1174                         imagex_printf(T("Setting timestamps on all extracted files...\n"));
1175                 break;
1176         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1177                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1178                         imagex_printf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1179                                 info->extract.target);
1180                 }
1181                 break;
1182         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1183                 percent_done = TO_PERCENT(info->split.completed_bytes,
1184                                           info->split.total_bytes);
1185                 unit_shift = get_unit(info->split.total_bytes, &unit_name);
1186                 imagex_printf(T("Writing \"%"TS"\" (part %u of %u): %"PRIu64" %"TS" of "
1187                           "%"PRIu64" %"TS" (%u%%) written\n"),
1188                         info->split.part_name,
1189                         info->split.cur_part_number,
1190                         info->split.total_parts,
1191                         info->split.completed_bytes >> unit_shift,
1192                         unit_name,
1193                         info->split.total_bytes >> unit_shift,
1194                         unit_name,
1195                         percent_done);
1196                 break;
1197         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1198                 if (info->split.completed_bytes == info->split.total_bytes) {
1199                         imagex_printf(T("Finished writing split WIM part %u of %u\n"),
1200                                 info->split.cur_part_number,
1201                                 info->split.total_parts);
1202                 }
1203                 break;
1204         case WIMLIB_PROGRESS_MSG_UPDATE_END_COMMAND:
1205                 switch (info->update.command->op) {
1206                 case WIMLIB_UPDATE_OP_DELETE:
1207                         imagex_printf(T("Deleted WIM path "
1208                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1209                                 info->update.command->delete_.wim_path);
1210                         break;
1211                 case WIMLIB_UPDATE_OP_RENAME:
1212                         imagex_printf(T("Renamed WIM path "
1213                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\" => "
1214                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1215                                 info->update.command->rename.wim_source_path,
1216                                 info->update.command->rename.wim_target_path);
1217                         break;
1218                 case WIMLIB_UPDATE_OP_ADD:
1219                 default:
1220                         break;
1221                 }
1222                 break;
1223         default:
1224                 break;
1225         }
1226         fflush(imagex_info_file);
1227         return 0;
1228 }
1229
1230 static unsigned
1231 parse_num_threads(const tchar *optarg)
1232 {
1233         tchar *tmp;
1234         unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1235         if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1236                 imagex_error(T("Number of threads must be a non-negative integer!"));
1237                 return UINT_MAX;
1238         } else {
1239                 return ul_nthreads;
1240         }
1241 }
1242
1243 /*
1244  * Parse an option passed to an update command.
1245  *
1246  * @op:         One of WIMLIB_UPDATE_OP_* that indicates the command being
1247  *              parsed.
1248  *
1249  * @option:     Text string for the option (beginning with --)
1250  *
1251  * @cmd:        `struct wimlib_update_command' that is being constructed for
1252  *              this command.
1253  *
1254  * Returns true if the option was recognized; false if not.
1255  */
1256 static bool
1257 update_command_add_option(int op, const tchar *option,
1258                           struct wimlib_update_command *cmd)
1259 {
1260         bool recognized = true;
1261         switch (op) {
1262         case WIMLIB_UPDATE_OP_ADD:
1263                 if (!tstrcmp(option, T("--verbose")))
1264                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_VERBOSE;
1265                 else if (!tstrcmp(option, T("--unix-data")))
1266                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_UNIX_DATA;
1267                 else if (!tstrcmp(option, T("--no-acls")) || !tstrcmp(option, T("--noacls")))
1268                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_NO_ACLS;
1269                 else if (!tstrcmp(option, T("--strict-acls")))
1270                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_STRICT_ACLS;
1271                 else if (!tstrcmp(option, T("--dereference")))
1272                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_DEREFERENCE;
1273                 else
1274                         recognized = false;
1275                 break;
1276         case WIMLIB_UPDATE_OP_DELETE:
1277                 if (!tstrcmp(option, T("--force")))
1278                         cmd->delete_.delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
1279                 else if (!tstrcmp(option, T("--recursive")))
1280                         cmd->delete_.delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
1281                 else
1282                         recognized = false;
1283                 break;
1284         default:
1285                 recognized = false;
1286                 break;
1287         }
1288         return recognized;
1289 }
1290
1291 /* How many nonoption arguments each `imagex update' command expects */
1292 static const unsigned update_command_num_nonoptions[] = {
1293         [WIMLIB_UPDATE_OP_ADD] = 2,
1294         [WIMLIB_UPDATE_OP_DELETE] = 1,
1295         [WIMLIB_UPDATE_OP_RENAME] = 2,
1296 };
1297
1298 static void
1299 update_command_add_nonoption(int op, const tchar *nonoption,
1300                              struct wimlib_update_command *cmd,
1301                              unsigned num_nonoptions)
1302 {
1303         switch (op) {
1304         case WIMLIB_UPDATE_OP_ADD:
1305                 if (num_nonoptions == 0)
1306                         cmd->add.fs_source_path = (tchar*)nonoption;
1307                 else
1308                         cmd->add.wim_target_path = (tchar*)nonoption;
1309                 break;
1310         case WIMLIB_UPDATE_OP_DELETE:
1311                 cmd->delete_.wim_path = (tchar*)nonoption;
1312                 break;
1313         case WIMLIB_UPDATE_OP_RENAME:
1314                 if (num_nonoptions == 0)
1315                         cmd->rename.wim_source_path = (tchar*)nonoption;
1316                 else
1317                         cmd->rename.wim_target_path = (tchar*)nonoption;
1318                 break;
1319         }
1320 }
1321
1322 /*
1323  * Parse a command passed on stdin to `imagex update'.
1324  *
1325  * @line:       Text of the command.
1326  * @len:        Length of the line, including a null terminator
1327  *              at line[len - 1].
1328  *
1329  * @command:    A `struct wimlib_update_command' to fill in from the parsed
1330  *              line.
1331  *
1332  * @line_number: Line number of the command, for diagnostics.
1333  *
1334  * Returns true on success; returns false on parse error.
1335  */
1336 static bool
1337 parse_update_command(tchar *line, size_t len,
1338                      struct wimlib_update_command *command,
1339                      size_t line_number)
1340 {
1341         int ret;
1342         tchar *command_name;
1343         int op;
1344         size_t num_nonoptions;
1345
1346         /* Get the command name ("add", "delete", "rename") */
1347         ret = parse_string(&line, &len, &command_name);
1348         if (ret != PARSE_STRING_SUCCESS)
1349                 return false;
1350
1351         if (!tstrcasecmp(command_name, T("add"))) {
1352                 op = WIMLIB_UPDATE_OP_ADD;
1353         } else if (!tstrcasecmp(command_name, T("delete"))) {
1354                 op = WIMLIB_UPDATE_OP_DELETE;
1355         } else if (!tstrcasecmp(command_name, T("rename"))) {
1356                 op = WIMLIB_UPDATE_OP_RENAME;
1357         } else {
1358                 imagex_error(T("Unknown update command \"%"TS"\" on line %zu"),
1359                              command_name, line_number);
1360                 return false;
1361         }
1362         command->op = op;
1363
1364         /* Parse additional options and non-options as needed */
1365         num_nonoptions = 0;
1366         for (;;) {
1367                 tchar *next_string;
1368
1369                 ret = parse_string(&line, &len, &next_string);
1370                 if (ret == PARSE_STRING_NONE) /* End of line */
1371                         break;
1372                 else if (ret != PARSE_STRING_SUCCESS) /* Parse failure */
1373                         return false;
1374                 if (next_string[0] == T('-') && next_string[1] == T('-')) {
1375                         /* Option */
1376                         if (!update_command_add_option(op, next_string, command))
1377                         {
1378                                 imagex_error(T("Unrecognized option \"%"TS"\" to "
1379                                                "update command \"%"TS"\" on line %zu"),
1380                                              next_string, command_name, line_number);
1381
1382                                 return false;
1383                         }
1384                 } else {
1385                         /* Nonoption */
1386                         if (num_nonoptions == update_command_num_nonoptions[op])
1387                         {
1388                                 imagex_error(T("Unexpected argument \"%"TS"\" in "
1389                                                "update command on line %zu\n"
1390                                                "       (The \"%"TS"\" command only "
1391                                                "takes %zu nonoption arguments!)\n"),
1392                                              next_string, line_number,
1393                                              command_name, num_nonoptions);
1394                                 return false;
1395                         }
1396                         update_command_add_nonoption(op, next_string,
1397                                                      command, num_nonoptions);
1398                         num_nonoptions++;
1399                 }
1400         }
1401
1402         if (num_nonoptions != update_command_num_nonoptions[op]) {
1403                 imagex_error(T("Not enough arguments to update command "
1404                                "\"%"TS"\" on line %zu"), command_name, line_number);
1405                 return false;
1406         }
1407         return true;
1408 }
1409
1410 static struct wimlib_update_command *
1411 parse_update_command_file(tchar **cmd_file_contents_p, size_t cmd_file_nchars,
1412                           size_t *num_cmds_ret)
1413 {
1414         ssize_t nlines;
1415         tchar *p;
1416         struct wimlib_update_command *cmds;
1417         size_t i, j;
1418
1419         nlines = text_file_count_lines(cmd_file_contents_p,
1420                                        &cmd_file_nchars);
1421         if (nlines < 0)
1422                 return NULL;
1423
1424         /* Always allocate at least 1 slot, just in case the implementation of
1425          * calloc() returns NULL if 0 bytes are requested. */
1426         cmds = calloc(nlines ?: 1, sizeof(struct wimlib_update_command));
1427         if (!cmds) {
1428                 imagex_error(T("out of memory"));
1429                 return NULL;
1430         }
1431         p = *cmd_file_contents_p;
1432         j = 0;
1433         for (i = 0; i < nlines; i++) {
1434                 /* XXX: Could use rawmemchr() here instead, but it may not be
1435                  * available on all platforms. */
1436                 tchar *endp = tmemchr(p, T('\n'), cmd_file_nchars);
1437                 size_t len = endp - p + 1;
1438                 *endp = T('\0');
1439                 if (!is_comment_line(p, len)) {
1440                         if (!parse_update_command(p, len, &cmds[j++], i + 1)) {
1441                                 free(cmds);
1442                                 return NULL;
1443                         }
1444                 }
1445                 p = endp + 1;
1446         }
1447         *num_cmds_ret = j;
1448         return cmds;
1449 }
1450
1451 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1452  * one image from a WIM file to a NTFS volume.  */
1453 static int
1454 imagex_apply(int argc, tchar **argv, int cmd)
1455 {
1456         int c;
1457         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1458         int image = WIMLIB_NO_IMAGE;
1459         WIMStruct *wim;
1460         struct wimlib_wim_info info;
1461         int ret;
1462         const tchar *wimfile;
1463         const tchar *target;
1464         const tchar *image_num_or_name = NULL;
1465         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1466
1467         REFGLOB_SET(refglobs);
1468
1469         for_opt(c, apply_options) {
1470                 switch (c) {
1471                 case IMAGEX_CHECK_OPTION:
1472                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1473                         break;
1474                 case IMAGEX_HARDLINK_OPTION:
1475                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1476                         break;
1477                 case IMAGEX_SYMLINK_OPTION:
1478                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1479                         break;
1480                 case IMAGEX_VERBOSE_OPTION:
1481                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1482                         break;
1483                 case IMAGEX_REF_OPTION:
1484                         ret = refglob_set_append(&refglobs, optarg);
1485                         if (ret)
1486                                 goto out_free_refglobs;
1487                         break;
1488                 case IMAGEX_UNIX_DATA_OPTION:
1489                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1490                         break;
1491                 case IMAGEX_NO_ACLS_OPTION:
1492                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1493                         break;
1494                 case IMAGEX_STRICT_ACLS_OPTION:
1495                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1496                         break;
1497                 case IMAGEX_NORPFIX_OPTION:
1498                         extract_flags |= WIMLIB_EXTRACT_FLAG_NORPFIX;
1499                         break;
1500                 case IMAGEX_RPFIX_OPTION:
1501                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1502                         break;
1503                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
1504                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
1505                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
1506                         break;
1507                 case IMAGEX_RESUME_OPTION:
1508                         extract_flags |= WIMLIB_EXTRACT_FLAG_RESUME;
1509                         break;
1510                 default:
1511                         goto out_usage;
1512                 }
1513         }
1514         argc -= optind;
1515         argv += optind;
1516         if (argc != 2 && argc != 3)
1517                 goto out_usage;
1518
1519         wimfile = argv[0];
1520
1521         if (!tstrcmp(wimfile, T("-"))) {
1522                 /* Attempt to apply pipable WIM from standard input.  */
1523                 if (argc == 2) {
1524                         image_num_or_name = NULL;
1525                         target = argv[1];
1526                 } else {
1527                         image_num_or_name = argv[1];
1528                         target = argv[2];
1529                 }
1530                 wim = NULL;
1531         } else {
1532                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
1533                                       imagex_progress_func);
1534                 if (ret)
1535                         goto out_free_refglobs;
1536
1537                 wimlib_get_wim_info(wim, &info);
1538
1539                 if (argc >= 3) {
1540                         /* Image explicitly specified.  */
1541                         image_num_or_name = argv[1];
1542                         image = wimlib_resolve_image(wim, image_num_or_name);
1543                         ret = verify_image_exists(image, image_num_or_name, wimfile);
1544                         if (ret)
1545                                 goto out_wimlib_free;
1546                         target = argv[2];
1547                 } else {
1548                         /* No image specified; default to image 1, but only if the WIM
1549                          * contains exactly one image.  */
1550
1551                         if (info.image_count != 1) {
1552                                 imagex_error(T("\"%"TS"\" contains %d images; "
1553                                                "Please select one (or all)."),
1554                                              wimfile, info.image_count);
1555                                 wimlib_free(wim);
1556                                 goto out_usage;
1557                         }
1558                         image = 1;
1559                         target = argv[1];
1560                 }
1561         }
1562
1563         if (refglobs.num_globs) {
1564                 if (wim == NULL) {
1565                         imagex_error(T("Can't specify --ref when applying from stdin!"));
1566                         ret = -1;
1567                         goto out_wimlib_free;
1568                 }
1569                 ret = wim_reference_globs(wim, &refglobs, open_flags);
1570                 if (ret)
1571                         goto out_wimlib_free;
1572         }
1573
1574 #ifndef __WIN32__
1575         {
1576                 /* Interpret a regular file or block device target as a NTFS
1577                  * volume.  */
1578                 struct stat stbuf;
1579
1580                 if (tstat(target, &stbuf)) {
1581                         if (errno != ENOENT) {
1582                                 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1583                                                         target);
1584                                 ret = -1;
1585                                 goto out_wimlib_free;
1586                         }
1587                 } else {
1588                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1589                                 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1590                 }
1591         }
1592 #endif
1593
1594         if (wim) {
1595                 ret = wimlib_extract_image(wim, image, target, extract_flags,
1596                                            imagex_progress_func);
1597         } else {
1598                 set_fd_to_binary_mode(STDIN_FILENO);
1599                 ret = wimlib_extract_image_from_pipe(STDIN_FILENO,
1600                                                      image_num_or_name,
1601                                                      target, extract_flags,
1602                                                      imagex_progress_func);
1603         }
1604         if (ret == 0) {
1605                 imagex_printf(T("Done applying WIM image.\n"));
1606         } else if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
1607                 if (wim) {
1608                         do_resource_not_found_warning(wimfile, &info, &refglobs);
1609                 } else {
1610                         imagex_error(T(        "If you are applying an image "
1611                                                "from a split pipable WIM,\n"
1612                                        "       make sure you have "
1613                                        "concatenated together all parts."));
1614                 }
1615         }
1616 out_wimlib_free:
1617         wimlib_free(wim);
1618 out_free_refglobs:
1619         refglob_set_destroy(&refglobs);
1620         return ret;
1621
1622 out_usage:
1623         usage(CMD_APPLY, stderr);
1624         ret = -1;
1625         goto out_free_refglobs;
1626 }
1627
1628 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1629  * directory trees.  'wimlib-imagex capture': create a new WIM file containing
1630  * the desired image.  'wimlib-imagex append': add a new image to an existing
1631  * WIM file. */
1632 static int
1633 imagex_capture_or_append(int argc, tchar **argv, int cmd)
1634 {
1635         int c;
1636         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
1637         int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE |
1638                               WIMLIB_ADD_IMAGE_FLAG_WINCONFIG;
1639         int write_flags = 0;
1640         int compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
1641         const tchar *wimfile;
1642         int wim_fd;
1643         const tchar *name;
1644         const tchar *desc;
1645         const tchar *flags_element = NULL;
1646
1647         WIMStruct *wim;
1648         WIMStruct *base_wim;
1649         const tchar *base_wimfile = NULL;
1650         WIMStruct *template_wim;
1651         const tchar *template_wimfile = NULL;
1652         const tchar *template_image_name_or_num = NULL;
1653         int template_image = WIMLIB_NO_IMAGE;
1654
1655         int ret;
1656         unsigned num_threads = 0;
1657
1658         tchar *source;
1659         tchar *source_copy;
1660
1661         const tchar *config_file = NULL;
1662         tchar *config_str;
1663         struct wimlib_capture_config *config;
1664
1665         bool source_list = false;
1666         size_t source_list_nchars = 0;
1667         tchar *source_list_contents;
1668         bool capture_sources_malloced;
1669         struct wimlib_capture_source *capture_sources;
1670         size_t num_sources;
1671         bool name_defaulted;
1672
1673         for_opt(c, capture_or_append_options) {
1674                 switch (c) {
1675                 case IMAGEX_BOOT_OPTION:
1676                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1677                         break;
1678                 case IMAGEX_CHECK_OPTION:
1679                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1680                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1681                         break;
1682                 case IMAGEX_NOCHECK_OPTION:
1683                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
1684                         break;
1685                 case IMAGEX_CONFIG_OPTION:
1686                         config_file = optarg;
1687                         add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_WINCONFIG;
1688                         break;
1689                 case IMAGEX_COMPRESS_OPTION:
1690                         compression_type = get_compression_type(optarg);
1691                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1692                                 goto out_err;
1693                         break;
1694                 case IMAGEX_FLAGS_OPTION:
1695                         flags_element = optarg;
1696                         break;
1697                 case IMAGEX_DEREFERENCE_OPTION:
1698                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1699                         break;
1700                 case IMAGEX_VERBOSE_OPTION:
1701                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1702                         break;
1703                 case IMAGEX_THREADS_OPTION:
1704                         num_threads = parse_num_threads(optarg);
1705                         if (num_threads == UINT_MAX)
1706                                 goto out_err;
1707                         break;
1708                 case IMAGEX_REBUILD_OPTION:
1709                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1710                         break;
1711                 case IMAGEX_UNIX_DATA_OPTION:
1712                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1713                         break;
1714                 case IMAGEX_SOURCE_LIST_OPTION:
1715                         source_list = true;
1716                         break;
1717                 case IMAGEX_NO_ACLS_OPTION:
1718                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1719                         break;
1720                 case IMAGEX_STRICT_ACLS_OPTION:
1721                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1722                         break;
1723                 case IMAGEX_RPFIX_OPTION:
1724                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
1725                         break;
1726                 case IMAGEX_NORPFIX_OPTION:
1727                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NORPFIX;
1728                         break;
1729                 case IMAGEX_PIPABLE_OPTION:
1730                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1731                         break;
1732                 case IMAGEX_NOT_PIPABLE_OPTION:
1733                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
1734                         break;
1735                 case IMAGEX_UPDATE_OF_OPTION:
1736                         if (template_image_name_or_num) {
1737                                 imagex_error(T("'--update-of' can only be "
1738                                                "specified one time!"));
1739                                 goto out_err;
1740                         } else {
1741                                 tchar *colon;
1742                                 colon = tstrrchr(optarg, T(':'));
1743
1744                                 if (colon) {
1745                                         template_wimfile = optarg;
1746                                         *colon = T('\0');
1747                                         template_image_name_or_num = colon + 1;
1748                                 } else {
1749                                         template_wimfile = NULL;
1750                                         template_image_name_or_num = optarg;
1751                                 }
1752                         }
1753                         break;
1754                 case IMAGEX_DELTA_FROM_OPTION:
1755                         if (cmd != CMD_CAPTURE) {
1756                                 imagex_error(T("'--delta-from' is only "
1757                                                "valid for capture!"));
1758                                 goto out_usage;
1759                         }
1760                         if (base_wimfile) {
1761                                 imagex_error(T("'--delta-from' can only be "
1762                                                "specified one time!"));
1763                                 goto out_err;
1764                         }
1765                         base_wimfile = optarg;
1766                         write_flags |= WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
1767                         break;
1768                 default:
1769                         goto out_usage;
1770                 }
1771         }
1772         argc -= optind;
1773         argv += optind;
1774
1775         if (argc < 2 || argc > 4)
1776                 goto out_usage;
1777
1778         source = argv[0];
1779         wimfile = argv[1];
1780
1781         if (!tstrcmp(wimfile, T("-"))) {
1782                 /* Writing captured WIM to standard output.  */
1783         #if 0
1784                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
1785                         imagex_error("Can't write a non-pipable WIM to "
1786                                      "standard output!  Specify --pipable\n"
1787                                      "       if you want to create a pipable WIM "
1788                                      "(but read the docs first).");
1789                         goto out_err;
1790                 }
1791         #else
1792                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1793         #endif
1794                 if (cmd == CMD_APPEND) {
1795                         imagex_error(T("Using standard output for append does "
1796                                        "not make sense."));
1797                         goto out_err;
1798                 }
1799                 wim_fd = STDOUT_FILENO;
1800                 wimfile = NULL;
1801                 imagex_info_file = stderr;
1802                 set_fd_to_binary_mode(wim_fd);
1803         }
1804
1805         /* If template image was specified using --update-of=IMAGE rather
1806          * than --update-of=WIMFILE:IMAGE, set the default WIMFILE.  */
1807         if (template_image_name_or_num && !template_wimfile) {
1808                 if (base_wimfile) {
1809                         /* Capturing delta WIM:  default to base WIM.  */
1810                         template_wimfile = base_wimfile;
1811                 } else if (cmd == CMD_APPEND) {
1812                         /* Appending to WIM:  default to WIM being appended to.
1813                          */
1814                         template_wimfile = wimfile;
1815                 } else {
1816                         /* Capturing a normal (non-delta) WIM, so the WIM file
1817                          * *must* be explicitly specified.  */
1818                         imagex_error(T("For capture of non-delta WIM, "
1819                                        "'--update-of' must specify "
1820                                        "WIMFILE:IMAGE!"));
1821                         goto out_usage;
1822                 }
1823         }
1824
1825         if (argc >= 3) {
1826                 name = argv[2];
1827                 name_defaulted = false;
1828         } else {
1829                 /* Set default name to SOURCE argument, omitting any directory
1830                  * prefixes and trailing slashes.  This requires making a copy
1831                  * of @source.  Leave some free characters at the end in case we
1832                  * append a number to keep the name unique. */
1833                 size_t source_name_len;
1834
1835                 source_name_len = tstrlen(source);
1836                 source_copy = alloca((source_name_len + 1 + 25) * sizeof(tchar));
1837                 name = tbasename(tstrcpy(source_copy, source));
1838                 name_defaulted = true;
1839         }
1840         /* Image description defaults to NULL if not given. */
1841         if (argc >= 4)
1842                 desc = argv[3];
1843         else
1844                 desc = NULL;
1845
1846         if (source_list) {
1847                 /* Set up capture sources in source list mode */
1848                 if (source[0] == T('-') && source[1] == T('\0')) {
1849                         source_list_contents = stdin_get_text_contents(&source_list_nchars);
1850                 } else {
1851                         source_list_contents = file_get_text_contents(source,
1852                                                                       &source_list_nchars);
1853                 }
1854                 if (!source_list_contents)
1855                         goto out_err;
1856
1857                 capture_sources = parse_source_list(&source_list_contents,
1858                                                     source_list_nchars,
1859                                                     &num_sources);
1860                 if (!capture_sources) {
1861                         ret = -1;
1862                         goto out_free_source_list_contents;
1863                 }
1864                 capture_sources_malloced = true;
1865         } else {
1866                 /* Set up capture source in non-source-list mode.  */
1867                 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1868                 capture_sources[0].fs_source_path = source;
1869                 capture_sources[0].wim_target_path = NULL;
1870                 capture_sources[0].reserved = 0;
1871                 num_sources = 1;
1872                 capture_sources_malloced = false;
1873                 source_list_contents = NULL;
1874         }
1875
1876         if (config_file) {
1877                 /* Read and parse capture configuration file.  */
1878                 size_t config_len;
1879
1880                 config_str = file_get_text_contents(config_file, &config_len);
1881                 if (!config_str) {
1882                         ret = -1;
1883                         goto out_free_capture_sources;
1884                 }
1885
1886                 config = alloca(sizeof(*config));
1887                 ret = parse_capture_config(&config_str, config_len, config);
1888                 if (ret)
1889                         goto out_free_config;
1890         } else {
1891                 /* No capture configuration file specified; use default
1892                  * configuration for capturing Windows operating systems.  */
1893                 config = NULL;
1894                 add_image_flags |= WIMLIB_ADD_FLAG_WINCONFIG;
1895         }
1896
1897         /* Open the existing WIM, or create a new one.  */
1898         if (cmd == CMD_APPEND)
1899                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
1900                                       imagex_progress_func);
1901         else
1902                 ret = wimlib_create_new_wim(compression_type, &wim);
1903         if (ret)
1904                 goto out_free_config;
1905
1906 #ifndef __WIN32__
1907         /* Detect if source is regular file or block device and set NTFS volume
1908          * capture mode.  */
1909         if (!source_list) {
1910                 struct stat stbuf;
1911
1912                 if (tstat(source, &stbuf) == 0) {
1913                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1914                                 imagex_printf(T("Capturing WIM image from NTFS "
1915                                           "filesystem on \"%"TS"\"\n"), source);
1916                                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1917                         }
1918                 } else {
1919                         if (errno != ENOENT) {
1920                                 imagex_error_with_errno(T("Failed to stat "
1921                                                           "\"%"TS"\""), source);
1922                                 ret = -1;
1923                                 goto out_free_wim;
1924                         }
1925                 }
1926         }
1927 #endif
1928
1929         /* If the user did not specify an image name, and the basename of the
1930          * source already exists as an image name in the WIM file, append a
1931          * suffix to make it unique. */
1932         if (cmd == CMD_APPEND && name_defaulted) {
1933                 unsigned long conflict_idx;
1934                 tchar *name_end = tstrchr(name, T('\0'));
1935                 for (conflict_idx = 1;
1936                      wimlib_image_name_in_use(wim, name);
1937                      conflict_idx++)
1938                 {
1939                         tsprintf(name_end, T(" (%lu)"), conflict_idx);
1940                 }
1941         }
1942
1943         /* If capturing a delta WIM, reference resources from the base WIM
1944          * before adding the new image.  */
1945         if (base_wimfile) {
1946                 ret = wimlib_open_wim(base_wimfile, open_flags,
1947                                       &base_wim, imagex_progress_func);
1948                 if (ret)
1949                         goto out_free_wim;
1950
1951                 imagex_printf(T("Capturing delta WIM based on \"%"TS"\"\n"),
1952                               base_wimfile);
1953
1954                 ret = wimlib_reference_resources(wim, &base_wim, 1, 0);
1955                 if (ret)
1956                         goto out_free_base_wim;
1957         } else {
1958                 base_wim = NULL;
1959         }
1960
1961         /* If capturing or appending as an update of an existing (template) image,
1962          * open the WIM if needed and parse the image index.  */
1963         if (template_image_name_or_num) {
1964
1965
1966                 if (template_wimfile == base_wimfile) {
1967                         template_wim = base_wim;
1968                 } else if (template_wimfile == wimfile) {
1969                         template_wim = wim;
1970                 } else {
1971                         ret = wimlib_open_wim(template_wimfile, open_flags,
1972                                               &template_wim, imagex_progress_func);
1973                         if (ret)
1974                                 goto out_free_base_wim;
1975                 }
1976
1977                 template_image = wimlib_resolve_image(template_wim,
1978                                                       template_image_name_or_num);
1979
1980                 if (template_image_name_or_num[0] == T('-')) {
1981                         tchar *tmp;
1982                         unsigned long n;
1983                         struct wimlib_wim_info info;
1984
1985                         wimlib_get_wim_info(wim, &info);
1986                         n = tstrtoul(template_image_name_or_num + 1, &tmp, 10);
1987                         if (n >= 1 && n <= info.image_count &&
1988                             *tmp == T('\0') &&
1989                             tmp != template_image_name_or_num + 1)
1990                         {
1991                                 template_image = info.image_count - (n - 1);
1992                         }
1993                 }
1994                 ret = verify_image_exists_and_is_single(template_image,
1995                                                         template_image_name_or_num,
1996                                                         template_wimfile);
1997                 if (ret)
1998                         goto out_free_template_wim;
1999         } else {
2000                 template_wim = NULL;
2001         }
2002
2003         ret = wimlib_add_image_multisource(wim,
2004                                            capture_sources,
2005                                            num_sources,
2006                                            name,
2007                                            config,
2008                                            add_image_flags,
2009                                            imagex_progress_func);
2010         if (ret)
2011                 goto out_free_template_wim;
2012
2013         if (desc || flags_element || template_image_name_or_num) {
2014                 /* User provided <DESCRIPTION> or <FLAGS> element, or an image
2015                  * on which the added one is to be based has been specified with
2016                  * --update-of.  Get the index of the image we just
2017                  *  added, then use it to call the appropriate functions.  */
2018                 struct wimlib_wim_info info;
2019
2020                 wimlib_get_wim_info(wim, &info);
2021
2022                 if (desc) {
2023                         ret = wimlib_set_image_descripton(wim,
2024                                                           info.image_count,
2025                                                           desc);
2026                         if (ret)
2027                                 goto out_free_template_wim;
2028                 }
2029
2030                 if (flags_element) {
2031                         ret = wimlib_set_image_flags(wim, info.image_count,
2032                                                      flags_element);
2033                         if (ret)
2034                                 goto out_free_template_wim;
2035                 }
2036
2037                 /* Reference template image if the user provided one.  */
2038                 if (template_image_name_or_num) {
2039                         imagex_printf(T("Using image %d "
2040                                         "from \"%"TS"\" as template\n"),
2041                                         template_image, template_wimfile);
2042                         ret = wimlib_reference_template_image(wim,
2043                                                               info.image_count,
2044                                                               template_wim,
2045                                                               template_image,
2046                                                               0, NULL);
2047                         if (ret)
2048                                 goto out_free_template_wim;
2049                 }
2050         }
2051
2052         /* Write the new WIM or overwrite the existing WIM with the new image
2053          * appended.  */
2054         if (cmd == CMD_APPEND) {
2055                 ret = wimlib_overwrite(wim, write_flags, num_threads,
2056                                        imagex_progress_func);
2057         } else if (wimfile) {
2058                 ret = wimlib_write(wim, wimfile, WIMLIB_ALL_IMAGES,
2059                                    write_flags, num_threads,
2060                                    imagex_progress_func);
2061         } else {
2062                 ret = wimlib_write_to_fd(wim, wim_fd, WIMLIB_ALL_IMAGES,
2063                                          write_flags, num_threads,
2064                                          imagex_progress_func);
2065         }
2066 out_free_template_wim:
2067         /* template_wim may alias base_wim or wim.  */
2068         if (template_wim != base_wim && template_wim != wim)
2069                 wimlib_free(template_wim);
2070 out_free_base_wim:
2071         wimlib_free(base_wim);
2072 out_free_wim:
2073         wimlib_free(wim);
2074 out_free_config:
2075         if (config) {
2076                 free(config->exclusion_pats.pats);
2077                 free(config->exclusion_exception_pats.pats);
2078                 free(config_str);
2079         }
2080 out_free_capture_sources:
2081         if (capture_sources_malloced)
2082                 free(capture_sources);
2083 out_free_source_list_contents:
2084         free(source_list_contents);
2085 out:
2086         return ret;
2087
2088 out_usage:
2089         usage(cmd, stderr);
2090 out_err:
2091         ret = -1;
2092         goto out;
2093 }
2094
2095 /* Remove image(s) from a WIM. */
2096 static int
2097 imagex_delete(int argc, tchar **argv, int cmd)
2098 {
2099         int c;
2100         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
2101         int write_flags = 0;
2102         const tchar *wimfile;
2103         const tchar *image_num_or_name;
2104         WIMStruct *wim;
2105         int image;
2106         int ret;
2107
2108         for_opt(c, delete_options) {
2109                 switch (c) {
2110                 case IMAGEX_CHECK_OPTION:
2111                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2112                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2113                         break;
2114                 case IMAGEX_SOFT_OPTION:
2115                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
2116                         break;
2117                 default:
2118                         goto out_usage;
2119                 }
2120         }
2121         argc -= optind;
2122         argv += optind;
2123
2124         if (argc != 2) {
2125                 if (argc < 1)
2126                         imagex_error(T("Must specify a WIM file"));
2127                 if (argc < 2)
2128                         imagex_error(T("Must specify an image"));
2129                 goto out_usage;
2130         }
2131         wimfile = argv[0];
2132         image_num_or_name = argv[1];
2133
2134         ret = wimlib_open_wim(wimfile, open_flags, &wim,
2135                               imagex_progress_func);
2136         if (ret)
2137                 goto out;
2138
2139         image = wimlib_resolve_image(wim, image_num_or_name);
2140
2141         ret = verify_image_exists(image, image_num_or_name, wimfile);
2142         if (ret)
2143                 goto out_wimlib_free;
2144
2145         ret = wimlib_delete_image(wim, image);
2146         if (ret) {
2147                 imagex_error(T("Failed to delete image from \"%"TS"\""),
2148                              wimfile);
2149                 goto out_wimlib_free;
2150         }
2151
2152         ret = wimlib_overwrite(wim, write_flags, 0, imagex_progress_func);
2153         if (ret) {
2154                 imagex_error(T("Failed to write the file \"%"TS"\" with image "
2155                                "deleted"), wimfile);
2156         }
2157 out_wimlib_free:
2158         wimlib_free(wim);
2159 out:
2160         return ret;
2161
2162 out_usage:
2163         usage(CMD_DELETE, stderr);
2164         ret = -1;
2165         goto out;
2166 }
2167
2168 static int
2169 print_full_path(const struct wimlib_dir_entry *wdentry, void *_ignore)
2170 {
2171         int ret = tprintf(T("%"TS"\n"), wdentry->full_path);
2172         return (ret >= 0) ? 0 : -1;
2173 }
2174
2175 /* Print the files contained in an image(s) in a WIM file. */
2176 static int
2177 imagex_dir(int argc, tchar **argv, int cmd)
2178 {
2179         const tchar *wimfile;
2180         WIMStruct *wim = NULL;
2181         int image;
2182         int ret;
2183         const tchar *path = T("");
2184         int c;
2185
2186         for_opt(c, dir_options) {
2187                 switch (c) {
2188                 case IMAGEX_PATH_OPTION:
2189                         path = optarg;
2190                         break;
2191                 default:
2192                         goto out_usage;
2193                 }
2194         }
2195         argc -= optind;
2196         argv += optind;
2197
2198         if (argc < 1) {
2199                 imagex_error(T("Must specify a WIM file"));
2200                 goto out_usage;
2201         }
2202         if (argc > 2) {
2203                 imagex_error(T("Too many arguments"));
2204                 goto out_usage;
2205         }
2206
2207         wimfile = argv[0];
2208         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &wim,
2209                               imagex_progress_func);
2210         if (ret)
2211                 goto out;
2212
2213         if (argc >= 2) {
2214                 image = wimlib_resolve_image(wim, argv[1]);
2215                 ret = verify_image_exists(image, argv[1], wimfile);
2216                 if (ret)
2217                         goto out_wimlib_free;
2218         } else {
2219                 /* No image specified; default to image 1, but only if the WIM
2220                  * contains exactly one image.  */
2221
2222                 struct wimlib_wim_info info;
2223
2224                 wimlib_get_wim_info(wim, &info);
2225                 if (info.image_count != 1) {
2226                         imagex_error(T("\"%"TS"\" contains %d images; Please "
2227                                        "select one (or all)."),
2228                                      wimfile, info.image_count);
2229                         wimlib_free(wim);
2230                         goto out_usage;
2231                 }
2232                 image = 1;
2233         }
2234
2235         ret = wimlib_iterate_dir_tree(wim, image, path,
2236                                       WIMLIB_ITERATE_DIR_TREE_FLAG_RECURSIVE,
2237                                       print_full_path, NULL);
2238 out_wimlib_free:
2239         wimlib_free(wim);
2240 out:
2241         return ret;
2242
2243 out_usage:
2244         usage(CMD_DIR, stderr);
2245         ret = -1;
2246         goto out;
2247 }
2248
2249 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
2250  * WIM file. */
2251 static int
2252 imagex_export(int argc, tchar **argv, int cmd)
2253 {
2254         int c;
2255         int open_flags = 0;
2256         int export_flags = 0;
2257         int write_flags = 0;
2258         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
2259         const tchar *src_wimfile;
2260         const tchar *src_image_num_or_name;
2261         const tchar *dest_wimfile;
2262         int dest_wim_fd;
2263         const tchar *dest_name;
2264         const tchar *dest_desc;
2265         WIMStruct *src_wim;
2266         struct wimlib_wim_info src_info;
2267         WIMStruct *dest_wim;
2268         int ret;
2269         int image;
2270         struct stat stbuf;
2271         bool wim_is_new;
2272         REFGLOB_SET(refglobs);
2273         unsigned num_threads = 0;
2274
2275         for_opt(c, export_options) {
2276                 switch (c) {
2277                 case IMAGEX_BOOT_OPTION:
2278                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
2279                         break;
2280                 case IMAGEX_CHECK_OPTION:
2281                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2282                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2283                         break;
2284                 case IMAGEX_NOCHECK_OPTION:
2285                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
2286                         break;
2287                 case IMAGEX_COMPRESS_OPTION:
2288                         compression_type = get_compression_type(optarg);
2289                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
2290                                 goto out_err;
2291                         break;
2292                 case IMAGEX_REF_OPTION:
2293                         ret = refglob_set_append(&refglobs, optarg);
2294                         if (ret)
2295                                 goto out_free_refglobs;
2296                         break;
2297                 case IMAGEX_THREADS_OPTION:
2298                         num_threads = parse_num_threads(optarg);
2299                         if (num_threads == UINT_MAX)
2300                                 goto out_err;
2301                         break;
2302                 case IMAGEX_REBUILD_OPTION:
2303                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
2304                         break;
2305                 case IMAGEX_PIPABLE_OPTION:
2306                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2307                         break;
2308                 case IMAGEX_NOT_PIPABLE_OPTION:
2309                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
2310                         break;
2311                 default:
2312                         goto out_usage;
2313                 }
2314         }
2315         argc -= optind;
2316         argv += optind;
2317         if (argc < 3 || argc > 5)
2318                 goto out_usage;
2319         src_wimfile           = argv[0];
2320         src_image_num_or_name = argv[1];
2321         dest_wimfile          = argv[2];
2322         dest_name             = (argc >= 4) ? argv[3] : NULL;
2323         dest_desc             = (argc >= 5) ? argv[4] : NULL;
2324         ret = wimlib_open_wim(src_wimfile,
2325                               open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_wim,
2326                               imagex_progress_func);
2327         if (ret)
2328                 goto out_free_refglobs;
2329
2330         wimlib_get_wim_info(src_wim, &src_info);
2331
2332         /* Determine if the destination is an existing file or not.  If so, we
2333          * try to append the exported image(s) to it; otherwise, we create a new
2334          * WIM containing the exported image(s).  Furthermore, determine if we
2335          * need to write a pipable WIM directly to standard output.  */
2336
2337         if (tstrcmp(dest_wimfile, T("-")) == 0) {
2338         #if 0
2339                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2340                         imagex_error("Can't write a non-pipable WIM to "
2341                                      "standard output!  Specify --pipable\n"
2342                                      "       if you want to create a pipable WIM "
2343                                      "(but read the docs first).");
2344                         ret = -1;
2345                         goto out_free_src_wim;
2346                 }
2347         #else
2348                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2349         #endif
2350                 dest_wimfile = NULL;
2351                 dest_wim_fd = STDOUT_FILENO;
2352                 imagex_info_file = stderr;
2353                 set_fd_to_binary_mode(dest_wim_fd);
2354         }
2355         errno = ENOENT;
2356         if (dest_wimfile != NULL && tstat(dest_wimfile, &stbuf) == 0) {
2357                 wim_is_new = false;
2358                 /* Destination file exists. */
2359
2360                 if (!S_ISREG(stbuf.st_mode)) {
2361                         imagex_error(T("\"%"TS"\" is not a regular file"),
2362                                      dest_wimfile);
2363                         ret = -1;
2364                         goto out_free_src_wim;
2365                 }
2366                 ret = wimlib_open_wim(dest_wimfile, open_flags | WIMLIB_OPEN_FLAG_WRITE_ACCESS,
2367                                       &dest_wim, imagex_progress_func);
2368                 if (ret)
2369                         goto out_free_src_wim;
2370
2371                 if (compression_type != WIMLIB_COMPRESSION_TYPE_INVALID) {
2372                         /* The user specified a compression type, but we're
2373                          * exporting to an existing WIM.  Make sure the
2374                          * specified compression type is the same as the
2375                          * compression type of the existing destination WIM. */
2376                         struct wimlib_wim_info dest_info;
2377
2378                         wimlib_get_wim_info(dest_wim, &dest_info);
2379                         if (compression_type != dest_info.compression_type) {
2380                                 imagex_error(T("Cannot specify a compression type that is "
2381                                                "not the same as that used in the "
2382                                                "destination WIM"));
2383                                 ret = -1;
2384                                 goto out_free_dest_wim;
2385                         }
2386                 }
2387         } else {
2388                 wim_is_new = true;
2389
2390                 if (errno != ENOENT) {
2391                         imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
2392                                                 dest_wimfile);
2393                         ret = -1;
2394                         goto out_free_src_wim;
2395                 }
2396
2397                 /* dest_wimfile is not an existing file, so create a new WIM. */
2398
2399                 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID) {
2400                         /* The user did not specify a compression type; default
2401                          * to that of the source WIM.  */
2402
2403                         compression_type = src_info.compression_type;
2404                 }
2405                 ret = wimlib_create_new_wim(compression_type, &dest_wim);
2406                 if (ret)
2407                         goto out_free_src_wim;
2408         }
2409
2410         image = wimlib_resolve_image(src_wim, src_image_num_or_name);
2411         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
2412         if (ret)
2413                 goto out_free_dest_wim;
2414
2415         if (refglobs.num_globs) {
2416                 ret = wim_reference_globs(src_wim, &refglobs, open_flags);
2417                 if (ret)
2418                         goto out_free_dest_wim;
2419         }
2420
2421         if ((export_flags & WIMLIB_EXPORT_FLAG_BOOT) &&
2422             image == WIMLIB_ALL_IMAGES && src_info.boot_index == 0)
2423         {
2424                 imagex_error(T("--boot specified for all-images export, but source WIM "
2425                                "has no bootable image."));
2426                 ret = -1;
2427                 goto out_free_dest_wim;
2428         }
2429
2430         ret = wimlib_export_image(src_wim, image, dest_wim, dest_name,
2431                                   dest_desc, export_flags, imagex_progress_func);
2432         if (ret) {
2433                 if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
2434                         do_resource_not_found_warning(src_wimfile,
2435                                                       &src_info, &refglobs);
2436                 }
2437                 goto out_free_dest_wim;
2438         }
2439
2440         if (!wim_is_new)
2441                 ret = wimlib_overwrite(dest_wim, write_flags, num_threads,
2442                                        imagex_progress_func);
2443         else if (dest_wimfile)
2444                 ret = wimlib_write(dest_wim, dest_wimfile, WIMLIB_ALL_IMAGES,
2445                                    write_flags, num_threads,
2446                                    imagex_progress_func);
2447         else
2448                 ret = wimlib_write_to_fd(dest_wim, dest_wim_fd,
2449                                          WIMLIB_ALL_IMAGES, write_flags,
2450                                          num_threads, imagex_progress_func);
2451 out_free_dest_wim:
2452         wimlib_free(dest_wim);
2453 out_free_src_wim:
2454         wimlib_free(src_wim);
2455 out_free_refglobs:
2456         refglob_set_destroy(&refglobs);
2457         return ret;
2458
2459 out_usage:
2460         usage(CMD_EXPORT, stderr);
2461 out_err:
2462         ret = -1;
2463         goto out_free_refglobs;
2464 }
2465
2466 static bool
2467 is_root_wim_path(const tchar *path)
2468 {
2469         const tchar *p;
2470         for (p = path; *p; p++)
2471                 if (*p != T('\\') && *p != T('/'))
2472                         return false;
2473         return true;
2474 }
2475
2476 static void
2477 free_extract_commands(struct wimlib_extract_command *cmds, size_t num_cmds,
2478                       const tchar *dest_dir)
2479 {
2480         for (size_t i = 0; i < num_cmds; i++)
2481                 if (cmds[i].fs_dest_path != dest_dir)
2482                         free(cmds[i].fs_dest_path);
2483         free(cmds);
2484 }
2485
2486 static struct wimlib_extract_command *
2487 prepare_extract_commands(tchar **paths, unsigned num_paths,
2488                          int extract_flags, tchar *dest_dir,
2489                          size_t *num_cmds_ret)
2490 {
2491         struct wimlib_extract_command *cmds;
2492         size_t num_cmds;
2493         tchar *emptystr = T("");
2494
2495         if (num_paths == 0) {
2496                 num_paths = 1;
2497                 paths = &emptystr;
2498         }
2499         num_cmds = num_paths;
2500         cmds = calloc(num_cmds, sizeof(cmds[0]));
2501         if (!cmds) {
2502                 imagex_error(T("Out of memory!"));
2503                 return NULL;
2504         }
2505
2506         for (size_t i = 0; i < num_cmds; i++) {
2507                 cmds[i].extract_flags = extract_flags;
2508                 cmds[i].wim_source_path = paths[i];
2509                 if (is_root_wim_path(paths[i])) {
2510                         cmds[i].fs_dest_path = dest_dir;
2511                 } else {
2512                         size_t len = tstrlen(dest_dir) + 1 + tstrlen(paths[i]);
2513                         cmds[i].fs_dest_path = malloc((len + 1) * sizeof(tchar));
2514                         if (!cmds[i].fs_dest_path) {
2515                                 free_extract_commands(cmds, num_cmds, dest_dir);
2516                                 return NULL;
2517                         }
2518                         tsprintf(cmds[i].fs_dest_path,
2519                                  T("%"TS""OS_PREFERRED_PATH_SEPARATOR_STRING"%"TS),
2520                                  dest_dir, tbasename(paths[i]));
2521                 }
2522         }
2523         *num_cmds_ret = num_cmds;
2524         return cmds;
2525 }
2526
2527 /* Extract files or directories from a WIM image */
2528 static int
2529 imagex_extract(int argc, tchar **argv, int cmd)
2530 {
2531         int c;
2532         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2533         int image;
2534         WIMStruct *wim;
2535         int ret;
2536         const tchar *wimfile;
2537         const tchar *image_num_or_name;
2538         tchar *dest_dir = T(".");
2539         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL | WIMLIB_EXTRACT_FLAG_NORPFIX;
2540
2541         REFGLOB_SET(refglobs);
2542
2543         struct wimlib_extract_command *cmds;
2544         size_t num_cmds;
2545
2546         for_opt(c, extract_options) {
2547                 switch (c) {
2548                 case IMAGEX_CHECK_OPTION:
2549                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2550                         break;
2551                 case IMAGEX_VERBOSE_OPTION:
2552                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
2553                         break;
2554                 case IMAGEX_REF_OPTION:
2555                         ret = refglob_set_append(&refglobs, optarg);
2556                         if (ret)
2557                                 goto out_free_refglobs;
2558                         break;
2559                 case IMAGEX_UNIX_DATA_OPTION:
2560                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
2561                         break;
2562                 case IMAGEX_NO_ACLS_OPTION:
2563                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
2564                         break;
2565                 case IMAGEX_STRICT_ACLS_OPTION:
2566                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
2567                         break;
2568                 case IMAGEX_DEST_DIR_OPTION:
2569                         dest_dir = optarg;
2570                         break;
2571                 case IMAGEX_TO_STDOUT_OPTION:
2572                         extract_flags |= WIMLIB_EXTRACT_FLAG_TO_STDOUT;
2573                         imagex_info_file = stderr;
2574                         imagex_be_quiet = true;
2575                         break;
2576                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
2577                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
2578                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
2579                         break;
2580                 default:
2581                         goto out_usage;
2582                 }
2583         }
2584         argc -= optind;
2585         argv += optind;
2586
2587         if (argc < 2)
2588                 goto out_usage;
2589
2590         wimfile = argv[0];
2591         image_num_or_name = argv[1];
2592
2593         argc -= 2;
2594         argv += 2;
2595
2596         cmds = prepare_extract_commands(argv, argc, extract_flags, dest_dir,
2597                                         &num_cmds);
2598         if (!cmds)
2599                 goto out_err;
2600
2601         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2602         if (ret)
2603                 goto out_free_cmds;
2604
2605         image = wimlib_resolve_image(wim, image_num_or_name);
2606         ret = verify_image_exists_and_is_single(image,
2607                                                 image_num_or_name,
2608                                                 wimfile);
2609         if (ret)
2610                 goto out_wimlib_free;
2611
2612         if (refglobs.num_globs) {
2613                 ret = wim_reference_globs(wim, &refglobs, open_flags);
2614                 if (ret)
2615                         goto out_wimlib_free;
2616         }
2617
2618         ret = wimlib_extract_files(wim, image, cmds, num_cmds, 0,
2619                                    imagex_progress_func);
2620         if (ret == 0) {
2621                 if (!imagex_be_quiet)
2622                         imagex_printf(T("Done extracting files.\n"));
2623         } else if (ret == WIMLIB_ERR_PATH_DOES_NOT_EXIST) {
2624                 tfprintf(stderr, T("Note: You can use `%"TS"' to see what "
2625                                    "files and directories\n"
2626                                    "      are in the WIM image.\n"),
2627                                 get_cmd_string(CMD_INFO, false));
2628         } else if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
2629                 struct wimlib_wim_info info;
2630
2631                 wimlib_get_wim_info(wim, &info);
2632                 do_resource_not_found_warning(wimfile, &info, &refglobs);
2633         }
2634 out_wimlib_free:
2635         wimlib_free(wim);
2636 out_free_cmds:
2637         free_extract_commands(cmds, num_cmds, dest_dir);
2638 out_free_refglobs:
2639         refglob_set_destroy(&refglobs);
2640         return ret;
2641
2642 out_usage:
2643         usage(CMD_EXTRACT, stderr);
2644 out_err:
2645         ret = -1;
2646         goto out_free_refglobs;
2647 }
2648
2649 static void print_byte_field(const uint8_t field[], size_t len)
2650 {
2651         while (len--)
2652                 tprintf(T("%02hhx"), *field++);
2653 }
2654
2655 static void
2656 print_wim_information(const tchar *wimfile, const struct wimlib_wim_info *info)
2657 {
2658         tputs(T("WIM Information:"));
2659         tputs(T("----------------"));
2660         tprintf(T("Path:           %"TS"\n"), wimfile);
2661         tprintf(T("GUID:           0x"));
2662         print_byte_field(info->guid, sizeof(info->guid));
2663         tputchar(T('\n'));
2664         tprintf(T("Image Count:    %d\n"), info->image_count);
2665         tprintf(T("Compression:    %"TS"\n"),
2666                 wimlib_get_compression_type_string(info->compression_type));
2667         tprintf(T("Part Number:    %d/%d\n"), info->part_number, info->total_parts);
2668         tprintf(T("Boot Index:     %d\n"), info->boot_index);
2669         tprintf(T("Size:           %"PRIu64" bytes\n"), info->total_bytes);
2670         tprintf(T("Integrity Info: %"TS"\n"),
2671                 info->has_integrity_table ? T("yes") : T("no"));
2672         tprintf(T("Relative path junction: %"TS"\n"),
2673                 info->has_rpfix ? T("yes") : T("no"));
2674         tprintf(T("Pipable:        %"TS"\n"),
2675                 info->pipable ? T("yes") : T("no"));
2676         tputchar(T('\n'));
2677 }
2678
2679 static int
2680 print_resource(const struct wimlib_resource_entry *resource,
2681                void *_ignore)
2682 {
2683
2684         tprintf(T("Uncompressed size   = %"PRIu64" bytes\n"),
2685                 resource->uncompressed_size);
2686
2687         tprintf(T("Compressed size     = %"PRIu64" bytes\n"),
2688                 resource->compressed_size);
2689
2690         tprintf(T("Offset              = %"PRIu64" bytes\n"),
2691                 resource->offset);
2692
2693
2694         tprintf(T("Part Number         = %u\n"), resource->part_number);
2695         tprintf(T("Reference Count     = %u\n"), resource->reference_count);
2696
2697         tprintf(T("Hash                = 0x"));
2698         print_byte_field(resource->sha1_hash, sizeof(resource->sha1_hash));
2699         tputchar(T('\n'));
2700
2701         tprintf(T("Flags               = "));
2702         if (resource->is_compressed)
2703                 tprintf(T("WIM_RESHDR_FLAG_COMPRESSED  "));
2704         if (resource->is_metadata)
2705                 tprintf(T("WIM_RESHDR_FLAG_METADATA  "));
2706         if (resource->is_free)
2707                 tprintf(T("WIM_RESHDR_FLAG_FREE  "));
2708         if (resource->is_spanned)
2709                 tprintf(T("WIM_RESHDR_FLAG_SPANNED  "));
2710         tputchar(T('\n'));
2711         tputchar(T('\n'));
2712         return 0;
2713 }
2714
2715 static void
2716 print_lookup_table(WIMStruct *wim)
2717 {
2718         wimlib_iterate_lookup_table(wim, 0, print_resource, NULL);
2719 }
2720
2721 /* Prints information about a WIM file; also can mark an image as bootable,
2722  * change the name of an image, or change the description of an image. */
2723 static int
2724 imagex_info(int argc, tchar **argv, int cmd)
2725 {
2726         int c;
2727         bool boot         = false;
2728         bool check        = false;
2729         bool nocheck      = false;
2730         bool header       = false;
2731         bool lookup_table = false;
2732         bool xml          = false;
2733         bool metadata     = false;
2734         bool short_header = true;
2735         const tchar *xml_out_file = NULL;
2736         const tchar *wimfile;
2737         const tchar *image_num_or_name;
2738         const tchar *new_name;
2739         const tchar *new_desc;
2740         WIMStruct *wim;
2741         int image;
2742         int ret;
2743         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2744         struct wimlib_wim_info info;
2745
2746         for_opt(c, info_options) {
2747                 switch (c) {
2748                 case IMAGEX_BOOT_OPTION:
2749                         boot = true;
2750                         break;
2751                 case IMAGEX_CHECK_OPTION:
2752                         check = true;
2753                         break;
2754                 case IMAGEX_NOCHECK_OPTION:
2755                         nocheck = true;
2756                         break;
2757                 case IMAGEX_HEADER_OPTION:
2758                         header = true;
2759                         short_header = false;
2760                         break;
2761                 case IMAGEX_LOOKUP_TABLE_OPTION:
2762                         lookup_table = true;
2763                         short_header = false;
2764                         break;
2765                 case IMAGEX_XML_OPTION:
2766                         xml = true;
2767                         short_header = false;
2768                         break;
2769                 case IMAGEX_EXTRACT_XML_OPTION:
2770                         xml_out_file = optarg;
2771                         short_header = false;
2772                         break;
2773                 case IMAGEX_METADATA_OPTION:
2774                         metadata = true;
2775                         short_header = false;
2776                         break;
2777                 default:
2778                         goto out_usage;
2779                 }
2780         }
2781
2782         argc -= optind;
2783         argv += optind;
2784         if (argc < 1 || argc > 4)
2785                 goto out_usage;
2786
2787         wimfile           = argv[0];
2788         image_num_or_name = (argc >= 2) ? argv[1] : T("all");
2789         new_name          = (argc >= 3) ? argv[2] : NULL;
2790         new_desc          = (argc >= 4) ? argv[3] : NULL;
2791
2792         if (check && nocheck) {
2793                 imagex_error(T("Can't specify both --check and --nocheck"));
2794                 goto out_err;
2795         }
2796
2797         if (check)
2798                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2799
2800         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2801         if (ret)
2802                 goto out;
2803
2804         wimlib_get_wim_info(wim, &info);
2805
2806         image = wimlib_resolve_image(wim, image_num_or_name);
2807         ret = WIMLIB_ERR_INVALID_IMAGE;
2808         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
2809                 verify_image_exists(image, image_num_or_name, wimfile);
2810                 if (boot) {
2811                         imagex_error(T("If you would like to set the boot "
2812                                        "index to 0, specify image \"0\" with "
2813                                        "the --boot flag."));
2814                 }
2815                 goto out_wimlib_free;
2816         }
2817
2818         if (boot && info.image_count == 0) {
2819                 imagex_error(T("--boot is meaningless on a WIM with no images"));
2820                 goto out_wimlib_free;
2821         }
2822
2823         if (image == WIMLIB_ALL_IMAGES && info.image_count > 1) {
2824                 if (boot) {
2825                         imagex_error(T("Cannot specify the --boot flag "
2826                                        "without specifying a specific "
2827                                        "image in a multi-image WIM"));
2828                         goto out_wimlib_free;
2829                 }
2830                 if (new_name) {
2831                         imagex_error(T("Cannot specify the NEW_NAME "
2832                                        "without specifying a specific "
2833                                        "image in a multi-image WIM"));
2834                         goto out_wimlib_free;
2835                 }
2836         }
2837
2838         /* Operations that print information are separated from operations that
2839          * recreate the WIM file. */
2840         if (!new_name && !boot) {
2841
2842                 /* Read-only operations */
2843
2844                 if (image == WIMLIB_NO_IMAGE) {
2845                         imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\""),
2846                                      image_num_or_name, wimfile);
2847                         goto out_wimlib_free;
2848                 }
2849
2850                 if (image == WIMLIB_ALL_IMAGES && short_header)
2851                         print_wim_information(wimfile, &info);
2852
2853                 if (header)
2854                         wimlib_print_header(wim);
2855
2856                 if (lookup_table) {
2857                         if (info.total_parts != 1) {
2858                                 tfprintf(stderr, T("Warning: Only showing the lookup table "
2859                                                    "for part %d of a %d-part WIM.\n"),
2860                                          info.part_number, info.total_parts);
2861                         }
2862                         print_lookup_table(wim);
2863                 }
2864
2865                 if (xml) {
2866                         ret = wimlib_extract_xml_data(wim, stdout);
2867                         if (ret)
2868                                 goto out_wimlib_free;
2869                 }
2870
2871                 if (xml_out_file) {
2872                         FILE *fp;
2873
2874                         fp = tfopen(xml_out_file, T("wb"));
2875                         if (!fp) {
2876                                 imagex_error_with_errno(T("Failed to open the "
2877                                                           "file \"%"TS"\" for "
2878                                                           "writing"),
2879                                                         xml_out_file);
2880                                 ret = -1;
2881                                 goto out_wimlib_free;
2882                         }
2883                         ret = wimlib_extract_xml_data(wim, fp);
2884                         if (fclose(fp)) {
2885                                 imagex_error(T("Failed to close the file "
2886                                                "\"%"TS"\""),
2887                                              xml_out_file);
2888                                 ret = -1;
2889                         }
2890                         if (ret)
2891                                 goto out_wimlib_free;
2892                 }
2893
2894                 if (short_header)
2895                         wimlib_print_available_images(wim, image);
2896
2897                 if (metadata) {
2898                         ret = wimlib_print_metadata(wim, image);
2899                         if (ret)
2900                                 goto out_wimlib_free;
2901                 }
2902                 ret = 0;
2903         } else {
2904
2905                 /* Modification operations */
2906
2907                 if (image == WIMLIB_ALL_IMAGES)
2908                         image = 1;
2909
2910                 if (image == WIMLIB_NO_IMAGE && new_name) {
2911                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2912                                        "when using image 0"), new_name);
2913                         ret = -1;
2914                         goto out_wimlib_free;
2915                 }
2916
2917                 if (boot) {
2918                         if (image == info.boot_index) {
2919                                 imagex_printf(T("Image %d is already marked as "
2920                                           "bootable.\n"), image);
2921                                 boot = false;
2922                         } else {
2923                                 imagex_printf(T("Marking image %d as bootable.\n"),
2924                                         image);
2925                                 info.boot_index = image;
2926                                 ret = wimlib_set_wim_info(wim, &info,
2927                                                           WIMLIB_CHANGE_BOOT_INDEX);
2928                                 if (ret)
2929                                         goto out_wimlib_free;
2930                         }
2931                 }
2932                 if (new_name) {
2933                         if (!tstrcmp(wimlib_get_image_name(wim, image), new_name))
2934                         {
2935                                 imagex_printf(T("Image %d is already named \"%"TS"\".\n"),
2936                                         image, new_name);
2937                                 new_name = NULL;
2938                         } else {
2939                                 imagex_printf(T("Changing the name of image %d to "
2940                                           "\"%"TS"\".\n"), image, new_name);
2941                                 ret = wimlib_set_image_name(wim, image, new_name);
2942                                 if (ret)
2943                                         goto out_wimlib_free;
2944                         }
2945                 }
2946                 if (new_desc) {
2947                         const tchar *old_desc;
2948                         old_desc = wimlib_get_image_description(wim, image);
2949                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
2950                                 imagex_printf(T("The description of image %d is already "
2951                                           "\"%"TS"\".\n"), image, new_desc);
2952                                 new_desc = NULL;
2953                         } else {
2954                                 imagex_printf(T("Changing the description of image %d "
2955                                           "to \"%"TS"\".\n"), image, new_desc);
2956                                 ret = wimlib_set_image_descripton(wim, image,
2957                                                                   new_desc);
2958                                 if (ret)
2959                                         goto out_wimlib_free;
2960                         }
2961                 }
2962
2963                 /* Only call wimlib_overwrite() if something actually needs to
2964                  * be changed.  */
2965                 if (boot || new_name || new_desc ||
2966                     (check && !info.has_integrity_table) ||
2967                     (nocheck && info.has_integrity_table))
2968                 {
2969                         int write_flags = 0;
2970
2971                         if (check)
2972                                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2973                         if (nocheck)
2974                                 write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
2975                         ret = wimlib_overwrite(wim, write_flags, 1,
2976                                                imagex_progress_func);
2977                 } else {
2978                         imagex_printf(T("The file \"%"TS"\" was not modified "
2979                                         "because nothing needed to be done.\n"),
2980                                       wimfile);
2981                         ret = 0;
2982                 }
2983         }
2984 out_wimlib_free:
2985         wimlib_free(wim);
2986 out:
2987         return ret;
2988
2989 out_usage:
2990         usage(CMD_INFO, stderr);
2991 out_err:
2992         ret = -1;
2993         goto out;
2994 }
2995
2996 /* Join split WIMs into one part WIM */
2997 static int
2998 imagex_join(int argc, tchar **argv, int cmd)
2999 {
3000         int c;
3001         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
3002         int wim_write_flags = 0;
3003         const tchar *output_path;
3004         int ret;
3005
3006         for_opt(c, join_options) {
3007                 switch (c) {
3008                 case IMAGEX_CHECK_OPTION:
3009                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3010                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3011                         break;
3012                 default:
3013                         goto out_usage;
3014                 }
3015         }
3016         argc -= optind;
3017         argv += optind;
3018
3019         if (argc < 2) {
3020                 imagex_error(T("Must specify one or more split WIM (.swm) "
3021                                "parts to join"));
3022                 goto out_usage;
3023         }
3024         output_path = argv[0];
3025         ret = wimlib_join((const tchar * const *)++argv,
3026                           --argc,
3027                           output_path,
3028                           swm_open_flags,
3029                           wim_write_flags,
3030                           imagex_progress_func);
3031 out:
3032         return ret;
3033
3034 out_usage:
3035         usage(CMD_JOIN, stderr);
3036         ret = -1;
3037         goto out;
3038 }
3039
3040 #if WIM_MOUNTING_SUPPORTED
3041
3042 /* Mounts a WIM image.  */
3043 static int
3044 imagex_mount_rw_or_ro(int argc, tchar **argv, int cmd)
3045 {
3046         int c;
3047         int mount_flags = 0;
3048         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
3049         const tchar *staging_dir = NULL;
3050         const tchar *wimfile;
3051         const tchar *dir;
3052         WIMStruct *wim;
3053         struct wimlib_wim_info info;
3054         int image;
3055         int ret;
3056
3057         REFGLOB_SET(refglobs);
3058
3059         if (cmd == CMD_MOUNTRW) {
3060                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
3061                 open_flags |= WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3062         }
3063
3064         for_opt(c, mount_options) {
3065                 switch (c) {
3066                 case IMAGEX_ALLOW_OTHER_OPTION:
3067                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
3068                         break;
3069                 case IMAGEX_CHECK_OPTION:
3070                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3071                         break;
3072                 case IMAGEX_DEBUG_OPTION:
3073                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
3074                         break;
3075                 case IMAGEX_STREAMS_INTERFACE_OPTION:
3076                         if (!tstrcasecmp(optarg, T("none")))
3077                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
3078                         else if (!tstrcasecmp(optarg, T("xattr")))
3079                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
3080                         else if (!tstrcasecmp(optarg, T("windows")))
3081                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
3082                         else {
3083                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
3084                                              optarg);
3085                                 goto out_usage;
3086                         }
3087                         break;
3088                 case IMAGEX_REF_OPTION:
3089                         ret = refglob_set_append(&refglobs, optarg);
3090                         if (ret)
3091                                 goto out_free_refglobs;
3092                         break;
3093                 case IMAGEX_STAGING_DIR_OPTION:
3094                         staging_dir = optarg;
3095                         break;
3096                 case IMAGEX_UNIX_DATA_OPTION:
3097                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
3098                         break;
3099                 default:
3100                         goto out_usage;
3101                 }
3102         }
3103         argc -= optind;
3104         argv += optind;
3105         if (argc != 2 && argc != 3)
3106                 goto out_usage;
3107
3108         wimfile = argv[0];
3109
3110         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3111         if (ret)
3112                 goto out_free_refglobs;
3113
3114         wimlib_get_wim_info(wim, &info);
3115
3116         if (argc >= 3) {
3117                 /* Image explicitly specified.  */
3118                 image = wimlib_resolve_image(wim, argv[1]);
3119                 dir = argv[2];
3120                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
3121                 if (ret)
3122                         goto out_free_wim;
3123         } else {
3124                 /* No image specified; default to image 1, but only if the WIM
3125                  * contains exactly one image.  */
3126
3127                 if (info.image_count != 1) {
3128                         imagex_error(T("\"%"TS"\" contains %d images; Please "
3129                                        "select one."), wimfile, info.image_count);
3130                         wimlib_free(wim);
3131                         goto out_usage;
3132                 }
3133                 image = 1;
3134                 dir = argv[1];
3135         }
3136
3137         if (refglobs.num_globs) {
3138                 ret = wim_reference_globs(wim, &refglobs, open_flags);
3139                 if (ret)
3140                         goto out_free_wim;
3141         }
3142
3143         ret = wimlib_mount_image(wim, image, dir, mount_flags, staging_dir);
3144         if (ret) {
3145                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
3146                                "on \"%"TS"\""),
3147                              image, wimfile, dir);
3148         }
3149 out_free_wim:
3150         wimlib_free(wim);
3151 out_free_refglobs:
3152         refglob_set_destroy(&refglobs);
3153         return ret;
3154
3155 out_usage:
3156         usage(cmd, stderr);
3157         ret = -1;
3158         goto out_free_refglobs;
3159 }
3160 #endif /* WIM_MOUNTING_SUPPORTED */
3161
3162 /* Rebuild a WIM file */
3163 static int
3164 imagex_optimize(int argc, tchar **argv, int cmd)
3165 {
3166         int c;
3167         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3168         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
3169         int ret;
3170         WIMStruct *wim;
3171         const tchar *wimfile;
3172         off_t old_size;
3173         off_t new_size;
3174         unsigned num_threads = 0;
3175
3176         for_opt(c, optimize_options) {
3177                 switch (c) {
3178                 case IMAGEX_CHECK_OPTION:
3179                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3180                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3181                         break;
3182                 case IMAGEX_NOCHECK_OPTION:
3183                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3184                         break;
3185                 case IMAGEX_RECOMPRESS_OPTION:
3186                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3187                         break;
3188                 case IMAGEX_THREADS_OPTION:
3189                         num_threads = parse_num_threads(optarg);
3190                         if (num_threads == UINT_MAX)
3191                                 goto out_err;
3192                         break;
3193                 case IMAGEX_PIPABLE_OPTION:
3194                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
3195                         break;
3196                 case IMAGEX_NOT_PIPABLE_OPTION:
3197                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
3198                         break;
3199                 default:
3200                         goto out_usage;
3201                 }
3202         }
3203         argc -= optind;
3204         argv += optind;
3205
3206         if (argc != 1)
3207                 goto out_usage;
3208
3209         wimfile = argv[0];
3210
3211         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3212         if (ret)
3213                 goto out;
3214
3215         old_size = file_get_size(wimfile);
3216         tprintf(T("\"%"TS"\" original size: "), wimfile);
3217         if (old_size == -1)
3218                 tputs(T("Unknown"));
3219         else
3220                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
3221
3222         ret = wimlib_overwrite(wim, write_flags, num_threads,
3223                                imagex_progress_func);
3224         if (ret) {
3225                 imagex_error(T("Optimization of \"%"TS"\" failed."), wimfile);
3226                 goto out_wimlib_free;
3227         }
3228
3229         new_size = file_get_size(wimfile);
3230         tprintf(T("\"%"TS"\" optimized size: "), wimfile);
3231         if (new_size == -1)
3232                 tputs(T("Unknown"));
3233         else
3234                 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
3235
3236         tfputs(T("Space saved: "), stdout);
3237         if (new_size != -1 && old_size != -1) {
3238                 tprintf(T("%lld KiB\n"),
3239                        ((long long)old_size - (long long)new_size) >> 10);
3240         } else {
3241                 tputs(T("Unknown"));
3242         }
3243         ret = 0;
3244 out_wimlib_free:
3245         wimlib_free(wim);
3246 out:
3247         return ret;
3248
3249 out_usage:
3250         usage(CMD_OPTIMIZE, stderr);