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