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