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