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