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