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