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