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