]> wimlib.net Git - wimlib/blob - programs/imagex.c
Expose symlink exclusions through WIMLIB_PROGRESS_MSG_SCAN_DENTRY 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                 case WIMLIB_SCAN_DENTRY_EXCLUDED_SYMLINK:
1163                         imagex_printf(T("\nWARNING: Ignoring absolute symbolic link "
1164                                         "with out-of-tree target:\n"
1165                                         "           \"%"TS"\" => \"%"TS"\"\n"
1166                                         "           (Use --norpfix to capture "
1167                                         "absolute symbolic links as-is)\n"),
1168                                         info->scan.cur_path, info->scan.symlink_target);
1169                         break;
1170                 }
1171                 break;
1172         case WIMLIB_PROGRESS_MSG_SCAN_END:
1173                 report_scan_progress(&info->scan, true);
1174                 imagex_printf(T("\n"));
1175                 break;
1176         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
1177                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1178                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1179                                           info->integrity.total_bytes);
1180                 imagex_printf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" %"TS" "
1181                         "of %"PRIu64" %"TS" (%u%%) done"),
1182                         info->integrity.filename,
1183                         info->integrity.completed_bytes >> unit_shift,
1184                         unit_name,
1185                         info->integrity.total_bytes >> unit_shift,
1186                         unit_name,
1187                         percent_done);
1188                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1189                         imagex_printf(T("\n"));
1190                 break;
1191         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
1192                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1193                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1194                                           info->integrity.total_bytes);
1195                 imagex_printf(T("\rCalculating integrity table for WIM: %"PRIu64" %"TS" "
1196                           "of %"PRIu64" %"TS" (%u%%) done"),
1197                         info->integrity.completed_bytes >> unit_shift,
1198                         unit_name,
1199                         info->integrity.total_bytes >> unit_shift,
1200                         unit_name,
1201                         percent_done);
1202                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1203                         imagex_printf(T("\n"));
1204                 break;
1205         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
1206                 imagex_printf(T("Applying image %d (\"%"TS"\") from \"%"TS"\" "
1207                           "to %"TS" \"%"TS"\"\n"),
1208                         info->extract.image,
1209                         info->extract.image_name,
1210                         info->extract.wimfile_name,
1211                         ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
1212                          T("NTFS volume") : T("directory")),
1213                         info->extract.target);
1214                 break;
1215         case WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN:
1216                 if (info->extract.extract_root_wim_source_path[0] != T('\0')) {
1217                         imagex_printf(T("Extracting "
1218                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING"%"TS"\" "
1219                                   "from image %d (\"%"TS"\") "
1220                                   "in \"%"TS"\" to \"%"TS"\"\n"),
1221                                 info->extract.extract_root_wim_source_path,
1222                                 info->extract.image,
1223                                 info->extract.image_name,
1224                                 info->extract.wimfile_name,
1225                                 info->extract.target);
1226                 }
1227                 break;
1228         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1229                 percent_done = TO_PERCENT(info->extract.completed_bytes,
1230                                           info->extract.total_bytes);
1231                 unit_shift = get_unit(info->extract.total_bytes, &unit_name);
1232                 imagex_printf(T("\rExtracting files: "
1233                           "%"PRIu64" %"TS" of %"PRIu64" %"TS" (%u%%) done"),
1234                         info->extract.completed_bytes >> unit_shift,
1235                         unit_name,
1236                         info->extract.total_bytes >> unit_shift,
1237                         unit_name,
1238                         percent_done);
1239                 if (info->extract.completed_bytes >= info->extract.total_bytes)
1240                         imagex_printf(T("\n"));
1241                 break;
1242         case WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN:
1243                 if (info->extract.total_parts != 1) {
1244                         imagex_printf(T("\nReading split pipable WIM part %u of %u\n"),
1245                                       info->extract.part_number,
1246                                       info->extract.total_parts);
1247                 }
1248                 break;
1249         case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1250                 if (info->extract.extract_root_wim_source_path[0] == T('\0'))
1251                         imagex_printf(T("Setting timestamps on all extracted files...\n"));
1252                 break;
1253         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1254                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1255                         imagex_printf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1256                                 info->extract.target);
1257                 }
1258                 break;
1259         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1260                 percent_done = TO_PERCENT(info->split.completed_bytes,
1261                                           info->split.total_bytes);
1262                 unit_shift = get_unit(info->split.total_bytes, &unit_name);
1263                 imagex_printf(T("Writing \"%"TS"\" (part %u of %u): %"PRIu64" %"TS" of "
1264                           "%"PRIu64" %"TS" (%u%%) written\n"),
1265                         info->split.part_name,
1266                         info->split.cur_part_number,
1267                         info->split.total_parts,
1268                         info->split.completed_bytes >> unit_shift,
1269                         unit_name,
1270                         info->split.total_bytes >> unit_shift,
1271                         unit_name,
1272                         percent_done);
1273                 break;
1274         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1275                 if (info->split.completed_bytes == info->split.total_bytes) {
1276                         imagex_printf(T("Finished writing split WIM part %u of %u\n"),
1277                                 info->split.cur_part_number,
1278                                 info->split.total_parts);
1279                 }
1280                 break;
1281         case WIMLIB_PROGRESS_MSG_UPDATE_END_COMMAND:
1282                 switch (info->update.command->op) {
1283                 case WIMLIB_UPDATE_OP_DELETE:
1284                         imagex_printf(T("Deleted WIM path "
1285                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1286                                 info->update.command->delete_.wim_path);
1287                         break;
1288                 case WIMLIB_UPDATE_OP_RENAME:
1289                         imagex_printf(T("Renamed WIM path "
1290                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\" => "
1291                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1292                                 info->update.command->rename.wim_source_path,
1293                                 info->update.command->rename.wim_target_path);
1294                         break;
1295                 case WIMLIB_UPDATE_OP_ADD:
1296                 default:
1297                         break;
1298                 }
1299                 break;
1300         default:
1301                 break;
1302         }
1303         fflush(imagex_info_file);
1304         return 0;
1305 }
1306
1307 static unsigned
1308 parse_num_threads(const tchar *optarg)
1309 {
1310         tchar *tmp;
1311         unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1312         if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1313                 imagex_error(T("Number of threads must be a non-negative integer!"));
1314                 return UINT_MAX;
1315         } else {
1316                 return ul_nthreads;
1317         }
1318 }
1319
1320 static uint32_t parse_chunk_size(const tchar *optarg)
1321 {
1322        tchar *tmp;
1323        unsigned long chunk_size = tstrtoul(optarg, &tmp, 10);
1324        if (chunk_size >= UINT32_MAX || *tmp || tmp == optarg) {
1325                imagex_error(T("Chunk size must be a non-negative integer!"));
1326                return UINT32_MAX;
1327        } else {
1328                return chunk_size;
1329        }
1330 }
1331
1332
1333 /*
1334  * Parse an option passed to an update command.
1335  *
1336  * @op:         One of WIMLIB_UPDATE_OP_* that indicates the command being
1337  *              parsed.
1338  *
1339  * @option:     Text string for the option (beginning with --)
1340  *
1341  * @cmd:        `struct wimlib_update_command' that is being constructed for
1342  *              this command.
1343  *
1344  * Returns true if the option was recognized; false if not.
1345  */
1346 static bool
1347 update_command_add_option(int op, const tchar *option,
1348                           struct wimlib_update_command *cmd)
1349 {
1350         bool recognized = true;
1351         switch (op) {
1352         case WIMLIB_UPDATE_OP_ADD:
1353                 if (!tstrcmp(option, T("--verbose")))
1354                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_VERBOSE;
1355                 else if (!tstrcmp(option, T("--unix-data")))
1356                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_UNIX_DATA;
1357                 else if (!tstrcmp(option, T("--no-acls")) || !tstrcmp(option, T("--noacls")))
1358                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_NO_ACLS;
1359                 else if (!tstrcmp(option, T("--strict-acls")))
1360                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_STRICT_ACLS;
1361                 else if (!tstrcmp(option, T("--dereference")))
1362                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_DEREFERENCE;
1363                 else
1364                         recognized = false;
1365                 break;
1366         case WIMLIB_UPDATE_OP_DELETE:
1367                 if (!tstrcmp(option, T("--force")))
1368                         cmd->delete_.delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
1369                 else if (!tstrcmp(option, T("--recursive")))
1370                         cmd->delete_.delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
1371                 else
1372                         recognized = false;
1373                 break;
1374         default:
1375                 recognized = false;
1376                 break;
1377         }
1378         return recognized;
1379 }
1380
1381 /* How many nonoption arguments each `imagex update' command expects */
1382 static const unsigned update_command_num_nonoptions[] = {
1383         [WIMLIB_UPDATE_OP_ADD] = 2,
1384         [WIMLIB_UPDATE_OP_DELETE] = 1,
1385         [WIMLIB_UPDATE_OP_RENAME] = 2,
1386 };
1387
1388 static void
1389 update_command_add_nonoption(int op, const tchar *nonoption,
1390                              struct wimlib_update_command *cmd,
1391                              unsigned num_nonoptions)
1392 {
1393         switch (op) {
1394         case WIMLIB_UPDATE_OP_ADD:
1395                 if (num_nonoptions == 0)
1396                         cmd->add.fs_source_path = (tchar*)nonoption;
1397                 else
1398                         cmd->add.wim_target_path = (tchar*)nonoption;
1399                 break;
1400         case WIMLIB_UPDATE_OP_DELETE:
1401                 cmd->delete_.wim_path = (tchar*)nonoption;
1402                 break;
1403         case WIMLIB_UPDATE_OP_RENAME:
1404                 if (num_nonoptions == 0)
1405                         cmd->rename.wim_source_path = (tchar*)nonoption;
1406                 else
1407                         cmd->rename.wim_target_path = (tchar*)nonoption;
1408                 break;
1409         }
1410 }
1411
1412 /*
1413  * Parse a command passed on stdin to `imagex update'.
1414  *
1415  * @line:       Text of the command.
1416  * @len:        Length of the line, including a null terminator
1417  *              at line[len - 1].
1418  *
1419  * @command:    A `struct wimlib_update_command' to fill in from the parsed
1420  *              line.
1421  *
1422  * @line_number: Line number of the command, for diagnostics.
1423  *
1424  * Returns true on success; returns false on parse error.
1425  */
1426 static bool
1427 parse_update_command(tchar *line, size_t len,
1428                      struct wimlib_update_command *command,
1429                      size_t line_number)
1430 {
1431         int ret;
1432         tchar *command_name;
1433         int op;
1434         size_t num_nonoptions;
1435
1436         /* Get the command name ("add", "delete", "rename") */
1437         ret = parse_string(&line, &len, &command_name);
1438         if (ret != PARSE_STRING_SUCCESS)
1439                 return false;
1440
1441         if (!tstrcasecmp(command_name, T("add"))) {
1442                 op = WIMLIB_UPDATE_OP_ADD;
1443         } else if (!tstrcasecmp(command_name, T("delete"))) {
1444                 op = WIMLIB_UPDATE_OP_DELETE;
1445         } else if (!tstrcasecmp(command_name, T("rename"))) {
1446                 op = WIMLIB_UPDATE_OP_RENAME;
1447         } else {
1448                 imagex_error(T("Unknown update command \"%"TS"\" on line %zu"),
1449                              command_name, line_number);
1450                 return false;
1451         }
1452         command->op = op;
1453
1454         /* Parse additional options and non-options as needed */
1455         num_nonoptions = 0;
1456         for (;;) {
1457                 tchar *next_string;
1458
1459                 ret = parse_string(&line, &len, &next_string);
1460                 if (ret == PARSE_STRING_NONE) /* End of line */
1461                         break;
1462                 else if (ret != PARSE_STRING_SUCCESS) /* Parse failure */
1463                         return false;
1464                 if (next_string[0] == T('-') && next_string[1] == T('-')) {
1465                         /* Option */
1466                         if (!update_command_add_option(op, next_string, command))
1467                         {
1468                                 imagex_error(T("Unrecognized option \"%"TS"\" to "
1469                                                "update command \"%"TS"\" on line %zu"),
1470                                              next_string, command_name, line_number);
1471
1472                                 return false;
1473                         }
1474                 } else {
1475                         /* Nonoption */
1476                         if (num_nonoptions == update_command_num_nonoptions[op])
1477                         {
1478                                 imagex_error(T("Unexpected argument \"%"TS"\" in "
1479                                                "update command on line %zu\n"
1480                                                "       (The \"%"TS"\" command only "
1481                                                "takes %zu nonoption arguments!)\n"),
1482                                              next_string, line_number,
1483                                              command_name, num_nonoptions);
1484                                 return false;
1485                         }
1486                         update_command_add_nonoption(op, next_string,
1487                                                      command, num_nonoptions);
1488                         num_nonoptions++;
1489                 }
1490         }
1491
1492         if (num_nonoptions != update_command_num_nonoptions[op]) {
1493                 imagex_error(T("Not enough arguments to update command "
1494                                "\"%"TS"\" on line %zu"), command_name, line_number);
1495                 return false;
1496         }
1497         return true;
1498 }
1499
1500 static struct wimlib_update_command *
1501 parse_update_command_file(tchar **cmd_file_contents_p, size_t cmd_file_nchars,
1502                           size_t *num_cmds_ret)
1503 {
1504         ssize_t nlines;
1505         tchar *p;
1506         struct wimlib_update_command *cmds;
1507         size_t i, j;
1508
1509         nlines = text_file_count_lines(cmd_file_contents_p,
1510                                        &cmd_file_nchars);
1511         if (nlines < 0)
1512                 return NULL;
1513
1514         /* Always allocate at least 1 slot, just in case the implementation of
1515          * calloc() returns NULL if 0 bytes are requested. */
1516         cmds = calloc(nlines ?: 1, sizeof(struct wimlib_update_command));
1517         if (!cmds) {
1518                 imagex_error(T("out of memory"));
1519                 return NULL;
1520         }
1521         p = *cmd_file_contents_p;
1522         j = 0;
1523         for (i = 0; i < nlines; i++) {
1524                 /* XXX: Could use rawmemchr() here instead, but it may not be
1525                  * available on all platforms. */
1526                 tchar *endp = tmemchr(p, T('\n'), cmd_file_nchars);
1527                 size_t len = endp - p + 1;
1528                 *endp = T('\0');
1529                 if (!is_comment_line(p, len)) {
1530                         if (!parse_update_command(p, len, &cmds[j++], i + 1)) {
1531                                 free(cmds);
1532                                 return NULL;
1533                         }
1534                 }
1535                 p = endp + 1;
1536         }
1537         *num_cmds_ret = j;
1538         return cmds;
1539 }
1540
1541 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1542  * one image from a WIM file to a NTFS volume.  */
1543 static int
1544 imagex_apply(int argc, tchar **argv, int cmd)
1545 {
1546         int c;
1547         int open_flags = 0;
1548         int image = WIMLIB_NO_IMAGE;
1549         WIMStruct *wim;
1550         struct wimlib_wim_info info;
1551         int ret;
1552         const tchar *wimfile;
1553         const tchar *target;
1554         const tchar *image_num_or_name = NULL;
1555         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1556
1557         STRING_SET(refglobs);
1558
1559         for_opt(c, apply_options) {
1560                 switch (c) {
1561                 case IMAGEX_CHECK_OPTION:
1562                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1563                         break;
1564                 case IMAGEX_HARDLINK_OPTION:
1565                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1566                         break;
1567                 case IMAGEX_SYMLINK_OPTION:
1568                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1569                         break;
1570                 case IMAGEX_VERBOSE_OPTION:
1571                         /* No longer does anything.  */
1572                         break;
1573                 case IMAGEX_REF_OPTION:
1574                         ret = string_set_append(&refglobs, optarg);
1575                         if (ret)
1576                                 goto out_free_refglobs;
1577                         break;
1578                 case IMAGEX_UNIX_DATA_OPTION:
1579                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1580                         break;
1581                 case IMAGEX_NO_ACLS_OPTION:
1582                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1583                         break;
1584                 case IMAGEX_STRICT_ACLS_OPTION:
1585                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1586                         break;
1587                 case IMAGEX_NORPFIX_OPTION:
1588                         extract_flags |= WIMLIB_EXTRACT_FLAG_NORPFIX;
1589                         break;
1590                 case IMAGEX_RPFIX_OPTION:
1591                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1592                         break;
1593                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
1594                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
1595                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
1596                         break;
1597                 case IMAGEX_RESUME_OPTION:
1598                         extract_flags |= WIMLIB_EXTRACT_FLAG_RESUME;
1599                         break;
1600                 default:
1601                         goto out_usage;
1602                 }
1603         }
1604         argc -= optind;
1605         argv += optind;
1606         if (argc != 2 && argc != 3)
1607                 goto out_usage;
1608
1609         wimfile = argv[0];
1610
1611         if (!tstrcmp(wimfile, T("-"))) {
1612                 /* Attempt to apply pipable WIM from standard input.  */
1613                 if (argc == 2) {
1614                         image_num_or_name = NULL;
1615                         target = argv[1];
1616                 } else {
1617                         image_num_or_name = argv[1];
1618                         target = argv[2];
1619                 }
1620                 wim = NULL;
1621         } else {
1622                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
1623                                       imagex_progress_func);
1624                 if (ret)
1625                         goto out_free_refglobs;
1626
1627                 wimlib_get_wim_info(wim, &info);
1628
1629                 if (argc >= 3) {
1630                         /* Image explicitly specified.  */
1631                         image_num_or_name = argv[1];
1632                         image = wimlib_resolve_image(wim, image_num_or_name);
1633                         ret = verify_image_exists(image, image_num_or_name, wimfile);
1634                         if (ret)
1635                                 goto out_wimlib_free;
1636                         target = argv[2];
1637                 } else {
1638                         /* No image specified; default to image 1, but only if the WIM
1639                          * contains exactly one image.  */
1640
1641                         if (info.image_count != 1) {
1642                                 imagex_error(T("\"%"TS"\" contains %d images; "
1643                                                "Please select one (or all)."),
1644                                              wimfile, info.image_count);
1645                                 wimlib_free(wim);
1646                                 goto out_usage;
1647                         }
1648                         image = 1;
1649                         target = argv[1];
1650                 }
1651         }
1652
1653         if (refglobs.num_strings) {
1654                 if (wim == NULL) {
1655                         imagex_error(T("Can't specify --ref when applying from stdin!"));
1656                         ret = -1;
1657                         goto out_wimlib_free;
1658                 }
1659                 ret = wim_reference_globs(wim, &refglobs, open_flags);
1660                 if (ret)
1661                         goto out_wimlib_free;
1662         }
1663
1664 #ifndef __WIN32__
1665         {
1666                 /* Interpret a regular file or block device target as a NTFS
1667                  * volume.  */
1668                 struct stat stbuf;
1669
1670                 if (tstat(target, &stbuf)) {
1671                         if (errno != ENOENT) {
1672                                 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1673                                                         target);
1674                                 ret = -1;
1675                                 goto out_wimlib_free;
1676                         }
1677                 } else {
1678                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1679                                 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1680                 }
1681         }
1682 #endif
1683
1684         if (wim) {
1685                 ret = wimlib_extract_image(wim, image, target, extract_flags,
1686                                            imagex_progress_func);
1687         } else {
1688                 set_fd_to_binary_mode(STDIN_FILENO);
1689                 ret = wimlib_extract_image_from_pipe(STDIN_FILENO,
1690                                                      image_num_or_name,
1691                                                      target, extract_flags,
1692                                                      imagex_progress_func);
1693         }
1694         if (ret == 0) {
1695                 imagex_printf(T("Done applying WIM image.\n"));
1696         } else if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
1697                 if (wim) {
1698                         do_resource_not_found_warning(wimfile, &info, &refglobs);
1699                 } else {
1700                         imagex_error(T(        "If you are applying an image "
1701                                                "from a split pipable WIM,\n"
1702                                        "       make sure you have "
1703                                        "concatenated together all parts."));
1704                 }
1705         }
1706 out_wimlib_free:
1707         wimlib_free(wim);
1708 out_free_refglobs:
1709         string_set_destroy(&refglobs);
1710         return ret;
1711
1712 out_usage:
1713         usage(CMD_APPLY, stderr);
1714         ret = -1;
1715         goto out_free_refglobs;
1716 }
1717
1718 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1719  * directory trees.  'wimlib-imagex capture': create a new WIM file containing
1720  * the desired image.  'wimlib-imagex append': add a new image to an existing
1721  * WIM file. */
1722 static int
1723 imagex_capture_or_append(int argc, tchar **argv, int cmd)
1724 {
1725         int c;
1726         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
1727         int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE |
1728                               WIMLIB_ADD_IMAGE_FLAG_WINCONFIG |
1729                               WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1730         int write_flags = 0;
1731         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
1732         uint32_t chunk_size = UINT32_MAX;
1733         const tchar *wimfile;
1734         int wim_fd;
1735         const tchar *name;
1736         const tchar *desc;
1737         const tchar *flags_element = NULL;
1738
1739         WIMStruct *wim;
1740         STRING_SET(base_wimfiles);
1741         WIMStruct **base_wims;
1742
1743         WIMStruct *template_wim;
1744         const tchar *template_wimfile = NULL;
1745         const tchar *template_image_name_or_num = NULL;
1746         int template_image = WIMLIB_NO_IMAGE;
1747
1748         int ret;
1749         unsigned num_threads = 0;
1750
1751         tchar *source;
1752         tchar *source_copy;
1753
1754         const tchar *config_file = NULL;
1755         tchar *config_str;
1756         struct wimlib_capture_config *config;
1757
1758         bool source_list = false;
1759         size_t source_list_nchars = 0;
1760         tchar *source_list_contents;
1761         bool capture_sources_malloced;
1762         struct wimlib_capture_source *capture_sources;
1763         size_t num_sources;
1764         bool name_defaulted;
1765
1766         for_opt(c, capture_or_append_options) {
1767                 switch (c) {
1768                 case IMAGEX_BOOT_OPTION:
1769                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1770                         break;
1771                 case IMAGEX_CHECK_OPTION:
1772                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1773                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1774                         break;
1775                 case IMAGEX_NOCHECK_OPTION:
1776                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
1777                         break;
1778                 case IMAGEX_CONFIG_OPTION:
1779                         config_file = optarg;
1780                         add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_WINCONFIG;
1781                         break;
1782                 case IMAGEX_COMPRESS_OPTION:
1783                         compression_type = get_compression_type(optarg);
1784                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1785                                 goto out_err;
1786                         break;
1787                 case IMAGEX_COMPRESS_SLOW_OPTION:
1788                         ret = set_compress_slow();
1789                         if (ret)
1790                                 goto out_err;
1791                         compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
1792                         break;
1793                 case IMAGEX_CHUNK_SIZE_OPTION:
1794                         chunk_size = parse_chunk_size(optarg);
1795                         if (chunk_size == UINT32_MAX)
1796                                 goto out_err;
1797                         break;
1798                 case IMAGEX_PACK_STREAMS_OPTION:
1799                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
1800                         break;
1801                 case IMAGEX_FLAGS_OPTION:
1802                         flags_element = optarg;
1803                         break;
1804                 case IMAGEX_DEREFERENCE_OPTION:
1805                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1806                         break;
1807                 case IMAGEX_VERBOSE_OPTION:
1808                         /* No longer does anything.  */
1809                         break;
1810                 case IMAGEX_THREADS_OPTION:
1811                         num_threads = parse_num_threads(optarg);
1812                         if (num_threads == UINT_MAX)
1813                                 goto out_err;
1814                         break;
1815                 case IMAGEX_REBUILD_OPTION:
1816                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1817                         break;
1818                 case IMAGEX_UNIX_DATA_OPTION:
1819                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1820                         break;
1821                 case IMAGEX_SOURCE_LIST_OPTION:
1822                         source_list = true;
1823                         break;
1824                 case IMAGEX_NO_ACLS_OPTION:
1825                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1826                         break;
1827                 case IMAGEX_STRICT_ACLS_OPTION:
1828                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1829                         break;
1830                 case IMAGEX_RPFIX_OPTION:
1831                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
1832                         break;
1833                 case IMAGEX_NORPFIX_OPTION:
1834                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NORPFIX;
1835                         break;
1836                 case IMAGEX_PIPABLE_OPTION:
1837                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1838                         break;
1839                 case IMAGEX_NOT_PIPABLE_OPTION:
1840                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
1841                         break;
1842                 case IMAGEX_UPDATE_OF_OPTION:
1843                         if (template_image_name_or_num) {
1844                                 imagex_error(T("'--update-of' can only be "
1845                                                "specified one time!"));
1846                                 goto out_err;
1847                         } else {
1848                                 tchar *colon;
1849                                 colon = tstrrchr(optarg, T(':'));
1850
1851                                 if (colon) {
1852                                         template_wimfile = optarg;
1853                                         *colon = T('\0');
1854                                         template_image_name_or_num = colon + 1;
1855                                 } else {
1856                                         template_wimfile = NULL;
1857                                         template_image_name_or_num = optarg;
1858                                 }
1859                         }
1860                         break;
1861                 case IMAGEX_DELTA_FROM_OPTION:
1862                         if (cmd != CMD_CAPTURE) {
1863                                 imagex_error(T("'--delta-from' is only "
1864                                                "valid for capture!"));
1865                                 goto out_usage;
1866                         }
1867                         ret = string_set_append(&base_wimfiles, optarg);
1868                         if (ret)
1869                                 goto out_free_base_wimfiles;
1870                         write_flags |= WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
1871                         break;
1872                 default:
1873                         goto out_usage;
1874                 }
1875         }
1876         argc -= optind;
1877         argv += optind;
1878
1879         if (argc < 2 || argc > 4)
1880                 goto out_usage;
1881
1882         source = argv[0];
1883         wimfile = argv[1];
1884
1885         /* Set default compression type.  */
1886         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID) {
1887                 struct wimlib_lzx_compressor_params params;
1888                 memset(&params, 0, sizeof(params));
1889                 params.hdr.size = sizeof(params);
1890                 params.algorithm = WIMLIB_LZX_ALGORITHM_FAST;
1891                 params.use_defaults = 1;
1892
1893                 wimlib_set_default_compressor_params(WIMLIB_COMPRESSION_TYPE_LZX,
1894                                                      &params.hdr);
1895                 compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
1896         }
1897
1898         if (!tstrcmp(wimfile, T("-"))) {
1899                 /* Writing captured WIM to standard output.  */
1900         #if 0
1901                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
1902                         imagex_error("Can't write a non-pipable WIM to "
1903                                      "standard output!  Specify --pipable\n"
1904                                      "       if you want to create a pipable WIM "
1905                                      "(but read the docs first).");
1906                         goto out_err;
1907                 }
1908         #else
1909                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1910         #endif
1911                 if (cmd == CMD_APPEND) {
1912                         imagex_error(T("Using standard output for append does "
1913                                        "not make sense."));
1914                         goto out_err;
1915                 }
1916                 wim_fd = STDOUT_FILENO;
1917                 wimfile = NULL;
1918                 imagex_info_file = stderr;
1919                 set_fd_to_binary_mode(wim_fd);
1920         }
1921
1922         /* If template image was specified using --update-of=IMAGE rather
1923          * than --update-of=WIMFILE:IMAGE, set the default WIMFILE.  */
1924         if (template_image_name_or_num && !template_wimfile) {
1925                 if (base_wimfiles.num_strings == 1) {
1926                         /* Capturing delta WIM based on single WIM:  default to
1927                          * base WIM.  */
1928                         template_wimfile = base_wimfiles.strings[0];
1929                 } else if (cmd == CMD_APPEND) {
1930                         /* Appending to WIM:  default to WIM being appended to.
1931                          */
1932                         template_wimfile = wimfile;
1933                 } else {
1934                         /* Capturing a normal (non-delta) WIM, so the WIM file
1935                          * *must* be explicitly specified.  */
1936                         if (base_wimfiles.num_strings > 1) {
1937                                 imagex_error(T("For capture of delta WIM "
1938                                                "based on multiple existing "
1939                                                "WIMs,\n"
1940                                                "      '--update-of' must "
1941                                                "specify WIMFILE:IMAGE!"));
1942                         } else {
1943                                 imagex_error(T("For capture of non-delta WIM, "
1944                                                "'--update-of' must specify "
1945                                                "WIMFILE:IMAGE!"));
1946                         }
1947                         goto out_usage;
1948                 }
1949         }
1950
1951         if (argc >= 3) {
1952                 name = argv[2];
1953                 name_defaulted = false;
1954         } else {
1955                 /* Set default name to SOURCE argument, omitting any directory
1956                  * prefixes and trailing slashes.  This requires making a copy
1957                  * of @source.  Leave some free characters at the end in case we
1958                  * append a number to keep the name unique. */
1959                 size_t source_name_len;
1960
1961                 source_name_len = tstrlen(source);
1962                 source_copy = alloca((source_name_len + 1 + 25) * sizeof(tchar));
1963                 name = tbasename(tstrcpy(source_copy, source));
1964                 name_defaulted = true;
1965         }
1966         /* Image description defaults to NULL if not given. */
1967         if (argc >= 4)
1968                 desc = argv[3];
1969         else
1970                 desc = NULL;
1971
1972         if (source_list) {
1973                 /* Set up capture sources in source list mode */
1974                 if (source[0] == T('-') && source[1] == T('\0')) {
1975                         source_list_contents = stdin_get_text_contents(&source_list_nchars);
1976                 } else {
1977                         source_list_contents = file_get_text_contents(source,
1978                                                                       &source_list_nchars);
1979                 }
1980                 if (!source_list_contents)
1981                         goto out_err;
1982
1983                 capture_sources = parse_source_list(&source_list_contents,
1984                                                     source_list_nchars,
1985                                                     &num_sources);
1986                 if (!capture_sources) {
1987                         ret = -1;
1988                         goto out_free_source_list_contents;
1989                 }
1990                 capture_sources_malloced = true;
1991         } else {
1992                 /* Set up capture source in non-source-list mode.  */
1993                 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1994                 capture_sources[0].fs_source_path = source;
1995                 capture_sources[0].wim_target_path = NULL;
1996                 capture_sources[0].reserved = 0;
1997                 num_sources = 1;
1998                 capture_sources_malloced = false;
1999                 source_list_contents = NULL;
2000         }
2001
2002         if (config_file) {
2003                 /* Read and parse capture configuration file.  */
2004                 size_t config_len;
2005
2006                 config_str = file_get_text_contents(config_file, &config_len);
2007                 if (!config_str) {
2008                         ret = -1;
2009                         goto out_free_capture_sources;
2010                 }
2011
2012                 config = alloca(sizeof(*config));
2013                 ret = parse_capture_config(&config_str, config_len, config);
2014                 if (ret)
2015                         goto out_free_config;
2016         } else {
2017                 /* No capture configuration file specified; use default
2018                  * configuration for capturing Windows operating systems.  */
2019                 config = NULL;
2020                 add_image_flags |= WIMLIB_ADD_FLAG_WINCONFIG;
2021         }
2022
2023         /* Open the existing WIM, or create a new one.  */
2024         if (cmd == CMD_APPEND)
2025                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
2026                                       imagex_progress_func);
2027         else
2028                 ret = wimlib_create_new_wim(compression_type, &wim);
2029         if (ret)
2030                 goto out_free_config;
2031
2032         /* Set chunk size if non-default.  */
2033         if (chunk_size != UINT32_MAX) {
2034                 ret = wimlib_set_output_chunk_size(wim, chunk_size);
2035                 if (ret)
2036                         goto out_free_wim;
2037         }
2038
2039 #ifndef __WIN32__
2040         /* Detect if source is regular file or block device and set NTFS volume
2041          * capture mode.  */
2042         if (!source_list) {
2043                 struct stat stbuf;
2044
2045                 if (tstat(source, &stbuf) == 0) {
2046                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
2047                                 imagex_printf(T("Capturing WIM image from NTFS "
2048                                           "filesystem on \"%"TS"\"\n"), source);
2049                                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
2050                         }
2051                 } else {
2052                         if (errno != ENOENT) {
2053                                 imagex_error_with_errno(T("Failed to stat "
2054                                                           "\"%"TS"\""), source);
2055                                 ret = -1;
2056                                 goto out_free_wim;
2057                         }
2058                 }
2059         }
2060 #endif
2061
2062         /* If the user did not specify an image name, and the basename of the
2063          * source already exists as an image name in the WIM file, append a
2064          * suffix to make it unique. */
2065         if (cmd == CMD_APPEND && name_defaulted) {
2066                 unsigned long conflict_idx;
2067                 tchar *name_end = tstrchr(name, T('\0'));
2068                 for (conflict_idx = 1;
2069                      wimlib_image_name_in_use(wim, name);
2070                      conflict_idx++)
2071                 {
2072                         tsprintf(name_end, T(" (%lu)"), conflict_idx);
2073                 }
2074         }
2075
2076         /* If capturing a delta WIM, reference resources from the base WIMs
2077          * before adding the new image.  */
2078         if (base_wimfiles.num_strings) {
2079                 base_wims = calloc(base_wimfiles.num_strings,
2080                                    sizeof(base_wims[0]));
2081                 if (base_wims == NULL) {
2082                         imagex_error(T("Out of memory!"));
2083                         ret = -1;
2084                         goto out_free_wim;
2085                 }
2086
2087                 for (size_t i = 0; i < base_wimfiles.num_strings; i++) {
2088                         ret = wimlib_open_wim(base_wimfiles.strings[i],
2089                                               open_flags, &base_wims[i],
2090                                               imagex_progress_func);
2091                         if (ret)
2092                                 goto out_free_base_wims;
2093
2094                 }
2095
2096                 ret = wimlib_reference_resources(wim, base_wims,
2097                                                  base_wimfiles.num_strings, 0);
2098                 if (ret)
2099                         goto out_free_base_wims;
2100
2101                 if (base_wimfiles.num_strings == 1) {
2102                         imagex_printf(T("Capturing delta WIM based on \"%"TS"\"\n"),
2103                                       base_wimfiles.strings[0]);
2104                 } else {
2105                         imagex_printf(T("Capturing delta WIM based on %u WIMs\n"),
2106                                       base_wimfiles.num_strings);
2107                 }
2108
2109         } else {
2110                 base_wims = NULL;
2111         }
2112
2113         /* If capturing or appending as an update of an existing (template) image,
2114          * open the WIM if needed and parse the image index.  */
2115         if (template_image_name_or_num) {
2116
2117
2118                 if (base_wimfiles.num_strings == 1 &&
2119                     template_wimfile == base_wimfiles.strings[0]) {
2120                         template_wim = base_wims[0];
2121                 } else if (template_wimfile == wimfile) {
2122                         template_wim = wim;
2123                 } else {
2124                         ret = wimlib_open_wim(template_wimfile, open_flags,
2125                                               &template_wim, imagex_progress_func);
2126                         if (ret)
2127                                 goto out_free_base_wims;
2128                 }
2129
2130                 template_image = wimlib_resolve_image(template_wim,
2131                                                       template_image_name_or_num);
2132
2133                 if (template_image_name_or_num[0] == T('-')) {
2134                         tchar *tmp;
2135                         unsigned long n;
2136                         struct wimlib_wim_info info;
2137
2138                         wimlib_get_wim_info(template_wim, &info);
2139                         n = tstrtoul(template_image_name_or_num + 1, &tmp, 10);
2140                         if (n >= 1 && n <= info.image_count &&
2141                             *tmp == T('\0') &&
2142                             tmp != template_image_name_or_num + 1)
2143                         {
2144                                 template_image = info.image_count - (n - 1);
2145                         }
2146                 }
2147                 ret = verify_image_exists_and_is_single(template_image,
2148                                                         template_image_name_or_num,
2149                                                         template_wimfile);
2150                 if (ret)
2151                         goto out_free_template_wim;
2152         } else {
2153                 template_wim = NULL;
2154         }
2155
2156         ret = wimlib_add_image_multisource(wim,
2157                                            capture_sources,
2158                                            num_sources,
2159                                            name,
2160                                            config,
2161                                            add_image_flags,
2162                                            imagex_progress_func);
2163         if (ret)
2164                 goto out_free_template_wim;
2165
2166         if (desc || flags_element || template_image_name_or_num) {
2167                 /* User provided <DESCRIPTION> or <FLAGS> element, or an image
2168                  * on which the added one is to be based has been specified with
2169                  * --update-of.  Get the index of the image we just
2170                  *  added, then use it to call the appropriate functions.  */
2171                 struct wimlib_wim_info info;
2172
2173                 wimlib_get_wim_info(wim, &info);
2174
2175                 if (desc) {
2176                         ret = wimlib_set_image_descripton(wim,
2177                                                           info.image_count,
2178                                                           desc);
2179                         if (ret)
2180                                 goto out_free_template_wim;
2181                 }
2182
2183                 if (flags_element) {
2184                         ret = wimlib_set_image_flags(wim, info.image_count,
2185                                                      flags_element);
2186                         if (ret)
2187                                 goto out_free_template_wim;
2188                 }
2189
2190                 /* Reference template image if the user provided one.  */
2191                 if (template_image_name_or_num) {
2192                         imagex_printf(T("Using image %d "
2193                                         "from \"%"TS"\" as template\n"),
2194                                         template_image, template_wimfile);
2195                         ret = wimlib_reference_template_image(wim,
2196                                                               info.image_count,
2197                                                               template_wim,
2198                                                               template_image,
2199                                                               0, NULL);
2200                         if (ret)
2201                                 goto out_free_template_wim;
2202                 }
2203         }
2204
2205         /* Write the new WIM or overwrite the existing WIM with the new image
2206          * appended.  */
2207         if (cmd == CMD_APPEND) {
2208                 ret = wimlib_overwrite(wim, write_flags, num_threads,
2209                                        imagex_progress_func);
2210         } else if (wimfile) {
2211                 ret = wimlib_write(wim, wimfile, WIMLIB_ALL_IMAGES,
2212                                    write_flags, num_threads,
2213                                    imagex_progress_func);
2214         } else {
2215                 ret = wimlib_write_to_fd(wim, wim_fd, WIMLIB_ALL_IMAGES,
2216                                          write_flags, num_threads,
2217                                          imagex_progress_func);
2218         }
2219 out_free_template_wim:
2220         /* template_wim may alias base_wims[0] or wim.  */
2221         if ((base_wimfiles.num_strings != 1 || template_wim != base_wims[0]) &&
2222             template_wim != wim)
2223                 wimlib_free(template_wim);
2224 out_free_base_wims:
2225         for (size_t i = 0; i < base_wimfiles.num_strings; i++)
2226                 wimlib_free(base_wims[i]);
2227         free(base_wims);
2228 out_free_wim:
2229         wimlib_free(wim);
2230 out_free_config:
2231         if (config) {
2232                 free(config->exclusion_pats.pats);
2233                 free(config->exclusion_exception_pats.pats);
2234                 free(config_str);
2235         }
2236 out_free_capture_sources:
2237         if (capture_sources_malloced)
2238                 free(capture_sources);
2239 out_free_source_list_contents:
2240         free(source_list_contents);
2241 out_free_base_wimfiles:
2242         string_set_destroy(&base_wimfiles);
2243         return ret;
2244
2245 out_usage:
2246         usage(cmd, stderr);
2247 out_err:
2248         ret = -1;
2249         goto out_free_base_wimfiles;
2250 }
2251
2252 /* Remove image(s) from a WIM. */
2253 static int
2254 imagex_delete(int argc, tchar **argv, int cmd)
2255 {
2256         int c;
2257         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
2258         int write_flags = 0;
2259         const tchar *wimfile;
2260         const tchar *image_num_or_name;
2261         WIMStruct *wim;
2262         int image;
2263         int ret;
2264
2265         for_opt(c, delete_options) {
2266                 switch (c) {
2267                 case IMAGEX_CHECK_OPTION:
2268                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2269                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2270                         break;
2271                 case IMAGEX_SOFT_OPTION:
2272                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
2273                         break;
2274                 default:
2275                         goto out_usage;
2276                 }
2277         }
2278         argc -= optind;
2279         argv += optind;
2280
2281         if (argc != 2) {
2282                 if (argc < 1)
2283                         imagex_error(T("Must specify a WIM file"));
2284                 if (argc < 2)
2285                         imagex_error(T("Must specify an image"));
2286                 goto out_usage;
2287         }
2288         wimfile = argv[0];
2289         image_num_or_name = argv[1];
2290
2291         ret = wimlib_open_wim(wimfile, open_flags, &wim,
2292                               imagex_progress_func);
2293         if (ret)
2294                 goto out;
2295
2296         image = wimlib_resolve_image(wim, image_num_or_name);
2297
2298         ret = verify_image_exists(image, image_num_or_name, wimfile);
2299         if (ret)
2300                 goto out_wimlib_free;
2301
2302         ret = wimlib_delete_image(wim, image);
2303         if (ret) {
2304                 imagex_error(T("Failed to delete image from \"%"TS"\""),
2305                              wimfile);
2306                 goto out_wimlib_free;
2307         }
2308
2309         ret = wimlib_overwrite(wim, write_flags, 0, imagex_progress_func);
2310         if (ret) {
2311                 imagex_error(T("Failed to write the file \"%"TS"\" with image "
2312                                "deleted"), wimfile);
2313         }
2314 out_wimlib_free:
2315         wimlib_free(wim);
2316 out:
2317         return ret;
2318
2319 out_usage:
2320         usage(CMD_DELETE, stderr);
2321         ret = -1;
2322         goto out;
2323 }
2324
2325 static int
2326 print_full_path(const struct wimlib_dir_entry *wdentry, void *_ignore)
2327 {
2328         int ret = tprintf(T("%"TS"\n"), wdentry->full_path);
2329         return (ret >= 0) ? 0 : -1;
2330 }
2331
2332 /* Print the files contained in an image(s) in a WIM file. */
2333 static int
2334 imagex_dir(int argc, tchar **argv, int cmd)
2335 {
2336         const tchar *wimfile;
2337         WIMStruct *wim = NULL;
2338         int image;
2339         int ret;
2340         const tchar *path = T("");
2341         int c;
2342
2343         for_opt(c, dir_options) {
2344                 switch (c) {
2345                 case IMAGEX_PATH_OPTION:
2346                         path = optarg;
2347                         break;
2348                 default:
2349                         goto out_usage;
2350                 }
2351         }
2352         argc -= optind;
2353         argv += optind;
2354
2355         if (argc < 1) {
2356                 imagex_error(T("Must specify a WIM file"));
2357                 goto out_usage;
2358         }
2359         if (argc > 2) {
2360                 imagex_error(T("Too many arguments"));
2361                 goto out_usage;
2362         }
2363
2364         wimfile = argv[0];
2365         ret = wimlib_open_wim(wimfile, 0, &wim, imagex_progress_func);
2366         if (ret)
2367                 goto out;
2368
2369         if (argc >= 2) {
2370                 image = wimlib_resolve_image(wim, argv[1]);
2371                 ret = verify_image_exists(image, argv[1], wimfile);
2372                 if (ret)
2373                         goto out_wimlib_free;
2374         } else {
2375                 /* No image specified; default to image 1, but only if the WIM
2376                  * contains exactly one image.  */
2377
2378                 struct wimlib_wim_info info;
2379
2380                 wimlib_get_wim_info(wim, &info);
2381                 if (info.image_count != 1) {
2382                         imagex_error(T("\"%"TS"\" contains %d images; Please "
2383                                        "select one (or all)."),
2384                                      wimfile, info.image_count);
2385                         wimlib_free(wim);
2386                         goto out_usage;
2387                 }
2388                 image = 1;
2389         }
2390
2391         ret = wimlib_iterate_dir_tree(wim, image, path,
2392                                       WIMLIB_ITERATE_DIR_TREE_FLAG_RECURSIVE,
2393                                       print_full_path, NULL);
2394 out_wimlib_free:
2395         wimlib_free(wim);
2396 out:
2397         return ret;
2398
2399 out_usage:
2400         usage(CMD_DIR, stderr);
2401         ret = -1;
2402         goto out;
2403 }
2404
2405 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
2406  * WIM file. */
2407 static int
2408 imagex_export(int argc, tchar **argv, int cmd)
2409 {
2410         int c;
2411         int open_flags = 0;
2412         int export_flags = 0;
2413         int write_flags = 0;
2414         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
2415         const tchar *src_wimfile;
2416         const tchar *src_image_num_or_name;
2417         const tchar *dest_wimfile;
2418         int dest_wim_fd;
2419         const tchar *dest_name;
2420         const tchar *dest_desc;
2421         WIMStruct *src_wim;
2422         struct wimlib_wim_info src_info;
2423         WIMStruct *dest_wim;
2424         int ret;
2425         int image;
2426         struct stat stbuf;
2427         bool wim_is_new;
2428         STRING_SET(refglobs);
2429         unsigned num_threads = 0;
2430         uint32_t chunk_size = UINT32_MAX;
2431
2432         for_opt(c, export_options) {
2433                 switch (c) {
2434                 case IMAGEX_BOOT_OPTION:
2435                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
2436                         break;
2437                 case IMAGEX_CHECK_OPTION:
2438                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2439                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2440                         break;
2441                 case IMAGEX_NOCHECK_OPTION:
2442                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
2443                         break;
2444                 case IMAGEX_COMPRESS_OPTION:
2445                         compression_type = get_compression_type(optarg);
2446                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
2447                                 goto out_err;
2448                         break;
2449                 case IMAGEX_PACK_STREAMS_OPTION:
2450                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2451                         break;
2452                 case IMAGEX_CHUNK_SIZE_OPTION:
2453                         chunk_size = parse_chunk_size(optarg);
2454                         if (chunk_size == UINT32_MAX)
2455                                 goto out_err;
2456                         break;
2457                 case IMAGEX_REF_OPTION:
2458                         ret = string_set_append(&refglobs, optarg);
2459                         if (ret)
2460                                 goto out_free_refglobs;
2461                         break;
2462                 case IMAGEX_THREADS_OPTION:
2463                         num_threads = parse_num_threads(optarg);
2464                         if (num_threads == UINT_MAX)
2465                                 goto out_err;
2466                         break;
2467                 case IMAGEX_REBUILD_OPTION:
2468                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
2469                         break;
2470                 case IMAGEX_PIPABLE_OPTION:
2471                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2472                         break;
2473                 case IMAGEX_NOT_PIPABLE_OPTION:
2474                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
2475                         break;
2476                 default:
2477                         goto out_usage;
2478                 }
2479         }
2480         argc -= optind;
2481         argv += optind;
2482         if (argc < 3 || argc > 5)
2483                 goto out_usage;
2484         src_wimfile           = argv[0];
2485         src_image_num_or_name = argv[1];
2486         dest_wimfile          = argv[2];
2487         dest_name             = (argc >= 4) ? argv[3] : NULL;
2488         dest_desc             = (argc >= 5) ? argv[4] : NULL;
2489         ret = wimlib_open_wim(src_wimfile, open_flags, &src_wim,
2490                               imagex_progress_func);
2491         if (ret)
2492                 goto out_free_refglobs;
2493
2494         wimlib_get_wim_info(src_wim, &src_info);
2495
2496         /* Determine if the destination is an existing file or not.  If so, we
2497          * try to append the exported image(s) to it; otherwise, we create a new
2498          * WIM containing the exported image(s).  Furthermore, determine if we
2499          * need to write a pipable WIM directly to standard output.  */
2500
2501         if (tstrcmp(dest_wimfile, T("-")) == 0) {
2502         #if 0
2503                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2504                         imagex_error("Can't write a non-pipable WIM to "
2505                                      "standard output!  Specify --pipable\n"
2506                                      "       if you want to create a pipable WIM "
2507                                      "(but read the docs first).");
2508                         ret = -1;
2509                         goto out_free_src_wim;
2510                 }
2511         #else
2512                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2513         #endif
2514                 dest_wimfile = NULL;
2515                 dest_wim_fd = STDOUT_FILENO;
2516                 imagex_info_file = stderr;
2517                 set_fd_to_binary_mode(dest_wim_fd);
2518         }
2519         errno = ENOENT;
2520         if (dest_wimfile != NULL && tstat(dest_wimfile, &stbuf) == 0) {
2521                 wim_is_new = false;
2522                 /* Destination file exists. */
2523
2524                 if (!S_ISREG(stbuf.st_mode)) {
2525                         imagex_error(T("\"%"TS"\" is not a regular file"),
2526                                      dest_wimfile);
2527                         ret = -1;
2528                         goto out_free_src_wim;
2529                 }
2530                 ret = wimlib_open_wim(dest_wimfile,
2531                                       open_flags | WIMLIB_OPEN_FLAG_WRITE_ACCESS,
2532                                       &dest_wim, imagex_progress_func);
2533                 if (ret)
2534                         goto out_free_src_wim;
2535
2536                 if (compression_type != WIMLIB_COMPRESSION_TYPE_INVALID) {
2537                         /* The user specified a compression type, but we're
2538                          * exporting to an existing WIM.  Make sure the
2539                          * specified compression type is the same as the
2540                          * compression type of the existing destination WIM. */
2541                         struct wimlib_wim_info dest_info;
2542
2543                         wimlib_get_wim_info(dest_wim, &dest_info);
2544                         if (compression_type != dest_info.compression_type) {
2545                                 imagex_error(T("Cannot specify a compression type that is "
2546                                                "not the same as that used in the "
2547                                                "destination WIM"));
2548                                 ret = -1;
2549                                 goto out_free_dest_wim;
2550                         }
2551                 }
2552         } else {
2553                 wim_is_new = true;
2554
2555                 if (errno != ENOENT) {
2556                         imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
2557                                                 dest_wimfile);
2558                         ret = -1;
2559                         goto out_free_src_wim;
2560                 }
2561
2562                 /* dest_wimfile is not an existing file, so create a new WIM. */
2563
2564                 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID) {
2565                         /* The user did not specify a compression type; default
2566                          * to that of the source WIM.  */
2567
2568                         compression_type = src_info.compression_type;
2569                 }
2570                 ret = wimlib_create_new_wim(compression_type, &dest_wim);
2571                 if (ret)
2572                         goto out_free_src_wim;
2573
2574                 /* Use same chunk size if compression type is the same.  */
2575                 if (compression_type == src_info.compression_type &&
2576                     chunk_size == UINT32_MAX)
2577                         wimlib_set_output_chunk_size(dest_wim, src_info.chunk_size);
2578         }
2579
2580         if (chunk_size != UINT32_MAX) {
2581                 /* Set destination chunk size.  */
2582                 ret = wimlib_set_output_chunk_size(dest_wim, chunk_size);
2583                 if (ret)
2584                         goto out_free_dest_wim;
2585         }
2586
2587         image = wimlib_resolve_image(src_wim, src_image_num_or_name);
2588         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
2589         if (ret)
2590                 goto out_free_dest_wim;
2591
2592         if (refglobs.num_strings) {
2593                 ret = wim_reference_globs(src_wim, &refglobs, open_flags);
2594                 if (ret)
2595                         goto out_free_dest_wim;
2596         }
2597
2598         if ((export_flags & WIMLIB_EXPORT_FLAG_BOOT) &&
2599             image == WIMLIB_ALL_IMAGES && src_info.boot_index == 0)
2600         {
2601                 imagex_error(T("--boot specified for all-images export, but source WIM "
2602                                "has no bootable image."));
2603                 ret = -1;
2604                 goto out_free_dest_wim;
2605         }
2606
2607         ret = wimlib_export_image(src_wim, image, dest_wim, dest_name,
2608                                   dest_desc, export_flags, imagex_progress_func);
2609         if (ret) {
2610                 if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
2611                         do_resource_not_found_warning(src_wimfile,
2612                                                       &src_info, &refglobs);
2613                 }
2614                 goto out_free_dest_wim;
2615         }
2616
2617         if (!wim_is_new)
2618                 ret = wimlib_overwrite(dest_wim, write_flags, num_threads,
2619                                        imagex_progress_func);
2620         else if (dest_wimfile)
2621                 ret = wimlib_write(dest_wim, dest_wimfile, WIMLIB_ALL_IMAGES,
2622                                    write_flags, num_threads,
2623                                    imagex_progress_func);
2624         else
2625                 ret = wimlib_write_to_fd(dest_wim, dest_wim_fd,
2626                                          WIMLIB_ALL_IMAGES, write_flags,
2627                                          num_threads, imagex_progress_func);
2628 out_free_dest_wim:
2629         wimlib_free(dest_wim);
2630 out_free_src_wim:
2631         wimlib_free(src_wim);
2632 out_free_refglobs:
2633         string_set_destroy(&refglobs);
2634         return ret;
2635
2636 out_usage:
2637         usage(CMD_EXPORT, stderr);
2638 out_err:
2639         ret = -1;
2640         goto out_free_refglobs;
2641 }
2642
2643 static bool
2644 is_root_wim_path(const tchar *path)
2645 {
2646         const tchar *p;
2647         for (p = path; *p; p++)
2648                 if (*p != T('\\') && *p != T('/'))
2649                         return false;
2650         return true;
2651 }
2652
2653 static void
2654 free_extract_commands(struct wimlib_extract_command *cmds, size_t num_cmds,
2655                       const tchar *dest_dir)
2656 {
2657         for (size_t i = 0; i < num_cmds; i++)
2658                 if (cmds[i].fs_dest_path != dest_dir)
2659                         free(cmds[i].fs_dest_path);
2660         free(cmds);
2661 }
2662
2663 static struct wimlib_extract_command *
2664 prepare_extract_commands(tchar **paths, unsigned num_paths,
2665                          int extract_flags, tchar *dest_dir,
2666                          size_t *num_cmds_ret)
2667 {
2668         struct wimlib_extract_command *cmds;
2669         size_t num_cmds;
2670         tchar *emptystr = T("");
2671
2672         if (num_paths == 0) {
2673                 num_paths = 1;
2674                 paths = &emptystr;
2675         }
2676         num_cmds = num_paths;
2677         cmds = calloc(num_cmds, sizeof(cmds[0]));
2678         if (!cmds) {
2679                 imagex_error(T("Out of memory!"));
2680                 return NULL;
2681         }
2682
2683         for (size_t i = 0; i < num_cmds; i++) {
2684                 cmds[i].extract_flags = extract_flags;
2685                 cmds[i].wim_source_path = paths[i];
2686                 if (is_root_wim_path(paths[i])) {
2687                         cmds[i].fs_dest_path = dest_dir;
2688                 } else {
2689                         size_t len = tstrlen(dest_dir) + 1 + tstrlen(paths[i]);
2690                         cmds[i].fs_dest_path = malloc((len + 1) * sizeof(tchar));
2691                         if (!cmds[i].fs_dest_path) {
2692                                 free_extract_commands(cmds, num_cmds, dest_dir);
2693                                 return NULL;
2694                         }
2695                         tsprintf(cmds[i].fs_dest_path,
2696                                  T("%"TS""OS_PREFERRED_PATH_SEPARATOR_STRING"%"TS),
2697                                  dest_dir, tbasename(paths[i]));
2698                 }
2699         }
2700         *num_cmds_ret = num_cmds;
2701         return cmds;
2702 }
2703
2704 /* Extract files or directories from a WIM image */
2705 static int
2706 imagex_extract(int argc, tchar **argv, int cmd)
2707 {
2708         int c;
2709         int open_flags = 0;
2710         int image;
2711         WIMStruct *wim;
2712         int ret;
2713         const tchar *wimfile;
2714         const tchar *image_num_or_name;
2715         const tchar *pathlist;
2716         tchar *dest_dir = T(".");
2717         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL | WIMLIB_EXTRACT_FLAG_NORPFIX;
2718         int listfile_extract_flags = WIMLIB_EXTRACT_FLAG_GLOB_PATHS;
2719
2720         STRING_SET(refglobs);
2721
2722         struct wimlib_extract_command *cmds;
2723         size_t num_cmds;
2724
2725         for_opt(c, extract_options) {
2726                 switch (c) {
2727                 case IMAGEX_CHECK_OPTION:
2728                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2729                         break;
2730                 case IMAGEX_VERBOSE_OPTION:
2731                         /* No longer does anything.  */
2732                         break;
2733                 case IMAGEX_REF_OPTION:
2734                         ret = string_set_append(&refglobs, optarg);
2735                         if (ret)
2736                                 goto out_free_refglobs;
2737                         break;
2738                 case IMAGEX_UNIX_DATA_OPTION:
2739                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
2740                         break;
2741                 case IMAGEX_NO_ACLS_OPTION:
2742                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
2743                         break;
2744                 case IMAGEX_STRICT_ACLS_OPTION:
2745                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
2746                         break;
2747                 case IMAGEX_DEST_DIR_OPTION:
2748                         dest_dir = optarg;
2749                         break;
2750                 case IMAGEX_TO_STDOUT_OPTION:
2751                         extract_flags |= WIMLIB_EXTRACT_FLAG_TO_STDOUT;
2752                         imagex_info_file = stderr;
2753                         imagex_be_quiet = true;
2754                         break;
2755                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
2756                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
2757                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
2758                         break;
2759                 case IMAGEX_NO_WILDCARDS_OPTION:
2760                         listfile_extract_flags &= ~WIMLIB_EXTRACT_FLAG_GLOB_PATHS;
2761                         break;
2762                 case IMAGEX_STRICT_WILDCARDS_OPTION:
2763                         listfile_extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_GLOB;
2764                         break;
2765                 default:
2766                         goto out_usage;
2767                 }
2768         }
2769         argc -= optind;
2770         argv += optind;
2771
2772         if (argc < 2)
2773                 goto out_usage;
2774
2775         wimfile = argv[0];
2776         image_num_or_name = argv[1];
2777
2778         argc -= 2;
2779         argv += 2;
2780
2781         if (argc == 1 && argv[0][0] == T('@')) {
2782                 pathlist = argv[0] + 1;
2783                 cmds = NULL;
2784                 num_cmds = 0;
2785         } else {
2786                 cmds = prepare_extract_commands(argv, argc, extract_flags, dest_dir,
2787                                                 &num_cmds);
2788                 if (cmds == NULL)
2789                         goto out_err;
2790                 pathlist = NULL;
2791         }
2792
2793         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2794         if (ret)
2795                 goto out_free_cmds;
2796
2797         image = wimlib_resolve_image(wim, image_num_or_name);
2798         ret = verify_image_exists_and_is_single(image,
2799                                                 image_num_or_name,
2800                                                 wimfile);
2801         if (ret)
2802                 goto out_wimlib_free;
2803
2804         if (refglobs.num_strings) {
2805                 ret = wim_reference_globs(wim, &refglobs, open_flags);
2806                 if (ret)
2807                         goto out_wimlib_free;
2808         }
2809
2810         ret = 0;
2811         if (ret == 0 && cmds != NULL) {
2812                 ret = wimlib_extract_files(wim, image, cmds, num_cmds, 0,
2813                                            imagex_progress_func);
2814         }
2815         if (ret == 0 && pathlist != NULL) {
2816                 ret = wimlib_extract_pathlist(wim, image, dest_dir,
2817                                               pathlist,
2818                                               extract_flags | listfile_extract_flags,
2819                                               imagex_progress_func);
2820         }
2821         if (ret == 0) {
2822                 if (!imagex_be_quiet)
2823                         imagex_printf(T("Done extracting files.\n"));
2824         } else if (ret == WIMLIB_ERR_PATH_DOES_NOT_EXIST) {
2825                 tfprintf(stderr, T("Note: You can use `%"TS"' to see what "
2826                                    "files and directories\n"
2827                                    "      are in the WIM image.\n"),
2828                                 get_cmd_string(CMD_DIR, false));
2829         } else if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
2830                 struct wimlib_wim_info info;
2831
2832                 wimlib_get_wim_info(wim, &info);
2833                 do_resource_not_found_warning(wimfile, &info, &refglobs);
2834         }
2835 out_wimlib_free:
2836         wimlib_free(wim);
2837 out_free_cmds:
2838         free_extract_commands(cmds, num_cmds, dest_dir);
2839 out_free_refglobs:
2840         string_set_destroy(&refglobs);
2841         return ret;
2842
2843 out_usage:
2844         usage(CMD_EXTRACT, stderr);
2845 out_err:
2846         ret = -1;
2847         goto out_free_refglobs;
2848 }
2849
2850 static void print_byte_field(const uint8_t field[], size_t len)
2851 {
2852         while (len--)
2853                 tprintf(T("%02hhx"), *field++);
2854 }
2855
2856 static void
2857 print_wim_information(const tchar *wimfile, const struct wimlib_wim_info *info)
2858 {
2859         tputs(T("WIM Information:"));
2860         tputs(T("----------------"));
2861         tprintf(T("Path:           %"TS"\n"), wimfile);
2862         tprintf(T("GUID:           0x"));
2863         print_byte_field(info->guid, sizeof(info->guid));
2864         tputchar(T('\n'));
2865         tprintf(T("Version:        %u\n"), info->wim_version);
2866         tprintf(T("Image Count:    %d\n"), info->image_count);
2867         tprintf(T("Compression:    %"TS"\n"),
2868                 wimlib_get_compression_type_string(info->compression_type));
2869         tprintf(T("Chunk Size:     %"PRIu32" bytes\n"),
2870                 info->chunk_size);
2871         tprintf(T("Part Number:    %d/%d\n"), info->part_number, info->total_parts);
2872         tprintf(T("Boot Index:     %d\n"), info->boot_index);
2873         tprintf(T("Size:           %"PRIu64" bytes\n"), info->total_bytes);
2874         tprintf(T("Integrity Info: %"TS"\n"),
2875                 info->has_integrity_table ? T("yes") : T("no"));
2876         tprintf(T("Relative path junction: %"TS"\n"),
2877                 info->has_rpfix ? T("yes") : T("no"));
2878         tprintf(T("Pipable:        %"TS"\n"),
2879                 info->pipable ? T("yes") : T("no"));
2880         tputchar(T('\n'));
2881 }
2882
2883 static int
2884 print_resource(const struct wimlib_resource_entry *resource,
2885                void *_ignore)
2886 {
2887         tprintf(T("Uncompressed size     = %"PRIu64" bytes\n"),
2888                 resource->uncompressed_size);
2889         if (resource->packed) {
2890                 tprintf(T("Raw compressed size   = %"PRIu64" bytes\n"),
2891                         resource->raw_resource_compressed_size);
2892
2893                 tprintf(T("Raw offset in WIM     = %"PRIu64" bytes\n"),
2894                         resource->raw_resource_offset_in_wim);
2895
2896                 tprintf(T("Offset in raw         = %"PRIu64" bytes\n"),
2897                         resource->offset);
2898         } else {
2899                 tprintf(T("Compressed size       = %"PRIu64" bytes\n"),
2900                         resource->compressed_size);
2901
2902                 tprintf(T("Offset in WIM         = %"PRIu64" bytes\n"),
2903                         resource->offset);
2904         }
2905
2906         tprintf(T("Part Number           = %u\n"), resource->part_number);
2907         tprintf(T("Reference Count       = %u\n"), resource->reference_count);
2908
2909         tprintf(T("Hash                  = 0x"));
2910         print_byte_field(resource->sha1_hash, sizeof(resource->sha1_hash));
2911         tputchar(T('\n'));
2912
2913         tprintf(T("Flags                 = "));
2914         if (resource->is_compressed)
2915                 tprintf(T("WIM_RESHDR_FLAG_COMPRESSED  "));
2916         if (resource->is_metadata)
2917                 tprintf(T("WIM_RESHDR_FLAG_METADATA  "));
2918         if (resource->is_free)
2919                 tprintf(T("WIM_RESHDR_FLAG_FREE  "));
2920         if (resource->is_spanned)
2921                 tprintf(T("WIM_RESHDR_FLAG_SPANNED  "));
2922         if (resource->packed)
2923                 tprintf(T("WIM_RESHDR_FLAG_PACKED_STREAMS  "));
2924         tputchar(T('\n'));
2925         tputchar(T('\n'));
2926         return 0;
2927 }
2928
2929 static void
2930 print_lookup_table(WIMStruct *wim)
2931 {
2932         wimlib_iterate_lookup_table(wim, 0, print_resource, NULL);
2933 }
2934
2935 /* Prints information about a WIM file; also can mark an image as bootable,
2936  * change the name of an image, or change the description of an image. */
2937 static int
2938 imagex_info(int argc, tchar **argv, int cmd)
2939 {
2940         int c;
2941         bool boot         = false;
2942         bool check        = false;
2943         bool nocheck      = false;
2944         bool header       = false;
2945         bool lookup_table = false;
2946         bool xml          = false;
2947         bool metadata     = false;
2948         bool short_header = true;
2949         const tchar *xml_out_file = NULL;
2950         const tchar *wimfile;
2951         const tchar *image_num_or_name;
2952         const tchar *new_name;
2953         const tchar *new_desc;
2954         WIMStruct *wim;
2955         int image;
2956         int ret;
2957         int open_flags = 0;
2958         struct wimlib_wim_info info;
2959
2960         for_opt(c, info_options) {
2961                 switch (c) {
2962                 case IMAGEX_BOOT_OPTION:
2963                         boot = true;
2964                         break;
2965                 case IMAGEX_CHECK_OPTION:
2966                         check = true;
2967                         break;
2968                 case IMAGEX_NOCHECK_OPTION:
2969                         nocheck = true;
2970                         break;
2971                 case IMAGEX_HEADER_OPTION:
2972                         header = true;
2973                         short_header = false;
2974                         break;
2975                 case IMAGEX_LOOKUP_TABLE_OPTION:
2976                         lookup_table = true;
2977                         short_header = false;
2978                         break;
2979                 case IMAGEX_XML_OPTION:
2980                         xml = true;
2981                         short_header = false;
2982                         break;
2983                 case IMAGEX_EXTRACT_XML_OPTION:
2984                         xml_out_file = optarg;
2985                         short_header = false;
2986                         break;
2987                 case IMAGEX_METADATA_OPTION:
2988                         metadata = true;
2989                         short_header = false;
2990                         break;
2991                 default:
2992                         goto out_usage;
2993                 }
2994         }
2995
2996         argc -= optind;
2997         argv += optind;
2998         if (argc < 1 || argc > 4)
2999                 goto out_usage;
3000
3001         wimfile           = argv[0];
3002         image_num_or_name = (argc >= 2) ? argv[1] : T("all");
3003         new_name          = (argc >= 3) ? argv[2] : NULL;
3004         new_desc          = (argc >= 4) ? argv[3] : NULL;
3005
3006         if (check && nocheck) {
3007                 imagex_error(T("Can't specify both --check and --nocheck"));
3008                 goto out_err;
3009         }
3010
3011         if (check)
3012                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3013
3014         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3015         if (ret)
3016                 goto out;
3017
3018         wimlib_get_wim_info(wim, &info);
3019
3020         image = wimlib_resolve_image(wim, image_num_or_name);
3021         ret = WIMLIB_ERR_INVALID_IMAGE;
3022         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
3023                 verify_image_exists(image, image_num_or_name, wimfile);
3024                 if (boot) {
3025                         imagex_error(T("If you would like to set the boot "
3026                                        "index to 0, specify image \"0\" with "
3027                                        "the --boot flag."));
3028                 }
3029                 goto out_wimlib_free;
3030         }
3031
3032         if (boot && info.image_count == 0) {
3033                 imagex_error(T("--boot is meaningless on a WIM with no images"));
3034                 goto out_wimlib_free;
3035         }
3036
3037         if (image == WIMLIB_ALL_IMAGES && info.image_count > 1) {
3038                 if (boot) {
3039                         imagex_error(T("Cannot specify the --boot flag "
3040                                        "without specifying a specific "
3041                                        "image in a multi-image WIM"));
3042                         goto out_wimlib_free;
3043                 }
3044                 if (new_name) {
3045                         imagex_error(T("Cannot specify the NEW_NAME "
3046                                        "without specifying a specific "
3047                                        "image in a multi-image WIM"));
3048                         goto out_wimlib_free;
3049                 }
3050         }
3051
3052         /* Operations that print information are separated from operations that
3053          * recreate the WIM file. */
3054         if (!new_name && !boot) {
3055
3056                 /* Read-only operations */
3057
3058                 if (image == WIMLIB_NO_IMAGE) {
3059                         imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\""),
3060                                      image_num_or_name, wimfile);
3061                         goto out_wimlib_free;
3062                 }
3063
3064                 if (image == WIMLIB_ALL_IMAGES && short_header)
3065                         print_wim_information(wimfile, &info);
3066
3067                 if (header)
3068                         wimlib_print_header(wim);
3069
3070                 if (lookup_table) {
3071                         if (info.total_parts != 1) {
3072                                 tfprintf(stderr, T("Warning: Only showing the lookup table "
3073                                                    "for part %d of a %d-part WIM.\n"),
3074                                          info.part_number, info.total_parts);
3075                         }
3076                         print_lookup_table(wim);
3077                 }
3078
3079                 if (xml) {
3080                         ret = wimlib_extract_xml_data(wim, stdout);
3081                         if (ret)
3082                                 goto out_wimlib_free;
3083                 }
3084
3085                 if (xml_out_file) {
3086                         FILE *fp;
3087
3088                         fp = tfopen(xml_out_file, T("wb"));
3089                         if (!fp) {
3090                                 imagex_error_with_errno(T("Failed to open the "
3091                                                           "file \"%"TS"\" for "
3092                                                           "writing"),
3093                                                         xml_out_file);
3094                                 ret = -1;
3095                                 goto out_wimlib_free;
3096                         }
3097                         ret = wimlib_extract_xml_data(wim, fp);
3098                         if (fclose(fp)) {
3099                                 imagex_error(T("Failed to close the file "
3100                                                "\"%"TS"\""),
3101                                              xml_out_file);
3102                                 ret = -1;
3103                         }
3104                         if (ret)
3105                                 goto out_wimlib_free;
3106                 }
3107
3108                 if (short_header)
3109                         wimlib_print_available_images(wim, image);
3110
3111                 if (metadata) {
3112                         ret = wimlib_print_metadata(wim, image);
3113                         if (ret)
3114                                 goto out_wimlib_free;
3115                 }
3116                 ret = 0;
3117         } else {
3118
3119                 /* Modification operations */
3120
3121                 if (image == WIMLIB_ALL_IMAGES)
3122                         image = 1;
3123
3124                 if (image == WIMLIB_NO_IMAGE && new_name) {
3125                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
3126                                        "when using image 0"), new_name);
3127                         ret = -1;
3128                         goto out_wimlib_free;
3129                 }
3130
3131                 if (boot) {
3132                         if (image == info.boot_index) {
3133                                 imagex_printf(T("Image %d is already marked as "
3134                                           "bootable.\n"), image);
3135                                 boot = false;
3136                         } else {
3137                                 imagex_printf(T("Marking image %d as bootable.\n"),
3138                                         image);
3139                                 info.boot_index = image;
3140                                 ret = wimlib_set_wim_info(wim, &info,
3141                                                           WIMLIB_CHANGE_BOOT_INDEX);
3142                                 if (ret)
3143                                         goto out_wimlib_free;
3144                         }
3145                 }
3146                 if (new_name) {
3147                         if (!tstrcmp(wimlib_get_image_name(wim, image), new_name))
3148                         {
3149                                 imagex_printf(T("Image %d is already named \"%"TS"\".\n"),
3150                                         image, new_name);
3151                                 new_name = NULL;
3152                         } else {
3153                                 imagex_printf(T("Changing the name of image %d to "
3154                                           "\"%"TS"\".\n"), image, new_name);
3155                                 ret = wimlib_set_image_name(wim, image, new_name);
3156                                 if (ret)
3157                                         goto out_wimlib_free;
3158                         }
3159                 }
3160                 if (new_desc) {
3161                         const tchar *old_desc;
3162                         old_desc = wimlib_get_image_description(wim, image);
3163                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
3164                                 imagex_printf(T("The description of image %d is already "
3165                                           "\"%"TS"\".\n"), image, new_desc);
3166                                 new_desc = NULL;
3167                         } else {
3168                                 imagex_printf(T("Changing the description of image %d "
3169                                           "to \"%"TS"\".\n"), image, new_desc);
3170                                 ret = wimlib_set_image_descripton(wim, image,
3171                                                                   new_desc);
3172                                 if (ret)
3173                                         goto out_wimlib_free;
3174                         }
3175                 }
3176
3177                 /* Only call wimlib_overwrite() if something actually needs to
3178                  * be changed.  */
3179                 if (boot || new_name || new_desc ||
3180                     (check && !info.has_integrity_table) ||
3181                     (nocheck && info.has_integrity_table))
3182                 {
3183                         int write_flags = 0;
3184
3185                         if (check)
3186                                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3187                         if (nocheck)
3188                                 write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3189                         ret = wimlib_overwrite(wim, write_flags, 1,
3190                                                imagex_progress_func);
3191                 } else {
3192                         imagex_printf(T("The file \"%"TS"\" was not modified "
3193                                         "because nothing needed to be done.\n"),
3194                                       wimfile);
3195                         ret = 0;
3196                 }
3197         }
3198 out_wimlib_free:
3199         wimlib_free(wim);
3200 out:
3201         return ret;
3202
3203 out_usage:
3204         usage(CMD_INFO, stderr);
3205 out_err:
3206         ret = -1;
3207         goto out;
3208 }
3209
3210 /* Join split WIMs into one part WIM */
3211 static int
3212 imagex_join(int argc, tchar **argv, int cmd)
3213 {
3214         int c;
3215         int swm_open_flags = 0;
3216         int wim_write_flags = 0;
3217         const tchar *output_path;
3218         int ret;
3219
3220         for_opt(c, join_options) {
3221                 switch (c) {
3222                 case IMAGEX_CHECK_OPTION:
3223                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3224                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3225                         break;
3226                 default:
3227                         goto out_usage;
3228                 }
3229         }
3230         argc -= optind;
3231         argv += optind;
3232
3233         if (argc < 2) {
3234                 imagex_error(T("Must specify one or more split WIM (.swm) "
3235                                "parts to join"));
3236                 goto out_usage;
3237         }
3238         output_path = argv[0];
3239         ret = wimlib_join((const tchar * const *)++argv,
3240                           --argc,
3241                           output_path,
3242                           swm_open_flags,
3243                           wim_write_flags,
3244                           imagex_progress_func);
3245 out:
3246         return ret;
3247
3248 out_usage:
3249         usage(CMD_JOIN, stderr);
3250         ret = -1;
3251         goto out;
3252 }
3253
3254 #if WIM_MOUNTING_SUPPORTED
3255
3256 /* Mounts a WIM image.  */
3257 static int
3258 imagex_mount_rw_or_ro(int argc, tchar **argv, int cmd)
3259 {
3260         int c;
3261         int mount_flags = 0;
3262         int open_flags = 0;
3263         const tchar *staging_dir = NULL;
3264         const tchar *wimfile;
3265         const tchar *dir;
3266         WIMStruct *wim;
3267         struct wimlib_wim_info info;
3268         int image;
3269         int ret;
3270
3271         STRING_SET(refglobs);
3272
3273         if (cmd == CMD_MOUNTRW) {
3274                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
3275                 open_flags |= WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3276         }
3277
3278         for_opt(c, mount_options) {
3279                 switch (c) {
3280                 case IMAGEX_ALLOW_OTHER_OPTION:
3281                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
3282                         break;
3283                 case IMAGEX_CHECK_OPTION:
3284                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3285                         break;
3286                 case IMAGEX_DEBUG_OPTION:
3287                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
3288                         break;
3289                 case IMAGEX_STREAMS_INTERFACE_OPTION:
3290                         if (!tstrcasecmp(optarg, T("none")))
3291                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
3292                         else if (!tstrcasecmp(optarg, T("xattr")))
3293                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
3294                         else if (!tstrcasecmp(optarg, T("windows")))
3295                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
3296                         else {
3297                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
3298                                              optarg);
3299                                 goto out_usage;
3300                         }
3301                         break;
3302                 case IMAGEX_REF_OPTION:
3303                         ret = string_set_append(&refglobs, optarg);
3304                         if (ret)
3305                                 goto out_free_refglobs;
3306                         break;
3307                 case IMAGEX_STAGING_DIR_OPTION:
3308                         staging_dir = optarg;
3309                         break;
3310                 case IMAGEX_UNIX_DATA_OPTION:
3311                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
3312                         break;
3313                 default:
3314                         goto out_usage;
3315                 }
3316         }
3317         argc -= optind;
3318         argv += optind;
3319         if (argc != 2 && argc != 3)
3320                 goto out_usage;
3321
3322         wimfile = argv[0];
3323
3324         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3325         if (ret)
3326                 goto out_free_refglobs;
3327
3328         wimlib_get_wim_info(wim, &info);
3329
3330         if (argc >= 3) {
3331                 /* Image explicitly specified.  */
3332                 image = wimlib_resolve_image(wim, argv[1]);
3333                 dir = argv[2];
3334                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
3335                 if (ret)
3336                         goto out_free_wim;
3337         } else {
3338                 /* No image specified; default to image 1, but only if the WIM
3339                  * contains exactly one image.  */
3340
3341                 if (info.image_count != 1) {
3342                         imagex_error(T("\"%"TS"\" contains %d images; Please "
3343                                        "select one."), wimfile, info.image_count);
3344                         wimlib_free(wim);
3345                         goto out_usage;
3346                 }
3347                 image = 1;
3348                 dir = argv[1];
3349         }
3350
3351         if (refglobs.num_strings) {
3352                 ret = wim_reference_globs(wim, &refglobs, open_flags);
3353                 if (ret)
3354                         goto out_free_wim;
3355         }
3356
3357         ret = wimlib_mount_image(wim, image, dir, mount_flags, staging_dir);
3358         if (ret) {
3359                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
3360                                "on \"%"TS"\""),
3361                              image, wimfile, dir);
3362         }
3363 out_free_wim:
3364         wimlib_free(wim);
3365 out_free_refglobs:
3366         string_set_destroy(&refglobs);
3367         return ret;
3368
3369 out_usage:
3370         usage(cmd, stderr);
3371         ret = -1;
3372         goto out_free_refglobs;
3373 }
3374 #endif /* WIM_MOUNTING_SUPPORTED */
3375
3376 /* Rebuild a WIM file */
3377 static int
3378 imagex_optimize(int argc, tchar **argv, int cmd)
3379 {
3380         int c;
3381         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3382         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
3383         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
3384         uint32_t chunk_size = UINT32_MAX;
3385         int ret;
3386         WIMStruct *wim;
3387         const tchar *wimfile;
3388         off_t old_size;
3389         off_t new_size;
3390         unsigned num_threads = 0;
3391
3392         for_opt(c, optimize_options) {
3393                 switch (c) {
3394                 case IMAGEX_CHECK_OPTION:
3395                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3396                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3397                         break;
3398                 case IMAGEX_NOCHECK_OPTION:
3399                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3400                         break;
3401                 case IMAGEX_COMPRESS_OPTION:
3402                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3403                         compression_type = get_compression_type(optarg);
3404                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
3405                                 goto out_err;
3406                         break;
3407                 case IMAGEX_RECOMPRESS_OPTION:
3408                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3409                         break;
3410                 case IMAGEX_COMPRESS_SLOW_OPTION:
3411                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3412                         compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
3413                         ret = set_compress_slow();
3414                         if (ret)
3415                                 goto out_err;
3416                         break;
3417                 case IMAGEX_CHUNK_SIZE_OPTION:
3418                         chunk_size = parse_chunk_size(optarg);
3419                         if (chunk_size == UINT32_MAX)
3420                                 goto out_err;
3421                         break;
3422                 case IMAGEX_PACK_STREAMS_OPTION:
3423                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
3424                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3425                         break;
3426                 case IMAGEX_THREADS_OPTION:
3427                         num_threads = parse_num_threads(optarg);
3428                         if (num_threads == UINT_MAX)
3429                                 goto out_err;
3430                         break;
3431                 case IMAGEX_PIPABLE_OPTION:
3432                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
3433                         break;
3434                 case IMAGEX_NOT_PIPABLE_OPTION:
3435                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
3436                         break;
3437                 default:
3438                         goto out_usage;
3439                 }
3440         }
3441         argc -= optind;
3442         argv += optind;
3443
3444         if (argc != 1)
3445                 goto out_usage;
3446
3447         wimfile = argv[0];
3448
3449         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3450         if (ret)
3451                 goto out;
3452
3453         if (compression_type != WIMLIB_COMPRESSION_TYPE_INVALID) {
3454                 /* Change compression type.  */
3455                 ret = wimlib_set_output_compression_type(wim, compression_type);
3456                 if (ret)
3457                         goto out_wimlib_free;
3458         }
3459
3460         if (chunk_size != UINT32_MAX) {
3461                 /* Change chunk size.  */
3462                 ret = wimlib_set_output_chunk_size(wim, chunk_size);
3463                 if (ret)
3464                         goto out_wimlib_free;
3465         }
3466
3467         old_size = file_get_size(wimfile);
3468         tprintf(T("\"%"TS"\" original size: "), wimfile);
3469         if (old_size == -1)
3470                 tputs(T("Unknown"));
3471         else
3472                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
3473
3474         ret = wimlib_overwrite(wim, write_flags, num_threads,
3475                                imagex_progress_func);
3476         if (ret) {
3477                 imagex_error(T("Optimization of \"%"TS"\" failed."), wimfile);
3478                 goto out_wimlib_free;
3479         }
3480
3481         new_size = file_get_size(wimfile);
3482         tprintf(T("\"%"TS"\" optimized size: "), wimfile);
3483         if (new_size == -1)
3484                 tputs(T("Unknown"));
3485         else
3486                 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
3487
3488         tfputs(T("Space saved: "), stdout);
3489         if (new_size != -1 && old_size != -1) {
3490                 tprintf(T("%lld KiB\n"),
3491                        ((long long)old_size - (long long)new_size) >> 10);
3492         } else {
3493                 tputs(T("Unknown"));
3494         }
3495         ret = 0;
3496 out_wimlib_free:
3497         wimlib_free(wim);
3498 out:
3499         return ret;
3500
3501 out_usage:
3502         usage(CMD_OPTIMIZE, stderr);
3503 out_err:
3504         ret = -1;
3505         goto out;
3506 }
3507
3508 /* Split a WIM into a spanned set */
3509 static int
3510 imagex_split(int argc, tchar **argv, int cmd)
3511 {
3512         int c;
3513         int open_flags = 0;
3514         int write_flags = 0;
3515         unsigned long part_size;
3516         tchar *tmp;
3517         int ret;
3518         WIMStruct *wim;
3519
3520         for_opt(c, split_options) {
3521                 switch (c) {
3522                 case IMAGEX_CHECK_OPTION:
3523                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3524                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3525                         break;
3526                 default:
3527                         goto out_usage;
3528                 }
3529         }
3530         argc -= optind;
3531         argv += optind;
3532
3533         if (argc != 3)
3534                 goto out_usage;
3535
3536         part_size = tstrtod(argv[2], &tmp) * (1 << 20);
3537         if (tmp == argv[2] || *tmp) {
3538                 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
3539                 imagex_error(T("The part size must be an integer or "
3540                                "floating-point number of megabytes."));
3541                 goto out_err;
3542         }
3543         ret = wimlib_open_wim(argv[0], open_flags, &wim, imagex_progress_func);
3544         if (ret)
3545                 goto out;
3546
3547         ret = wimlib_split(wim, argv[1], part_size, write_flags, imagex_progress_func);
3548         wimlib_free(wim);
3549 out:
3550         return ret;
3551
3552 out_usage:
3553         usage(CMD_SPLIT, stderr);
3554 out_err:
3555         ret = -1;
3556         goto out;
3557 }
3558
3559 #if WIM_MOUNTING_SUPPORTED
3560 /* Unmounts a mounted WIM image. */
3561 static int
3562 imagex_unmount(int argc, tchar **argv, int cmd)
3563 {
3564         int c;
3565         int unmount_flags = 0;
3566         int ret;
3567
3568         for_opt(c, unmount_options) {
3569                 switch (c) {
3570                 case IMAGEX_COMMIT_OPTION:
3571                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
3572                         break;
3573                 case IMAGEX_CHECK_OPTION:
3574                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
3575                         break;
3576                 case IMAGEX_REBUILD_OPTION:
3577                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
3578                         break;
3579                 case IMAGEX_LAZY_OPTION:
3580                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_LAZY;
3581                         break;
3582                 default:
3583                         goto out_usage;
3584                 }
3585         }
3586         argc -= optind;
3587         argv += optind;
3588         if (argc != 1)
3589                 goto out_usage;
3590
3591         ret = wimlib_unmount_image(argv[0], unmount_flags,
3592                                    imagex_progress_func);
3593         if (ret)
3594                 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
3595 out:
3596         return ret;
3597
3598 out_usage:
3599         usage(CMD_UNMOUNT, stderr);
3600         ret = -1;
3601         goto out;
3602 }
3603 #endif /* WIM_MOUNTING_SUPPORTED */
3604
3605 /*
3606  * Add, delete, or rename files in a WIM image.
3607  */
3608 static int
3609 imagex_update(int argc, tchar **argv, int cmd)
3610 {
3611         const tchar *wimfile;
3612         int image;
3613         WIMStruct *wim;
3614         int ret;
3615         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3616         int write_flags = 0;
3617         int update_flags = WIMLIB_UPDATE_FLAG_SEND_PROGRESS;
3618         int default_add_flags = WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE |
3619                                 WIMLIB_ADD_FLAG_VERBOSE;
3620         int default_delete_flags = 0;
3621         unsigned num_threads = 0;
3622         int c;
3623         tchar *cmd_file_contents;
3624         size_t cmd_file_nchars;
3625         struct wimlib_update_command *cmds;
3626         size_t num_cmds;
3627         tchar *command_str = NULL;
3628
3629         const tchar *config_file = NULL;
3630         tchar *config_str;
3631         struct wimlib_capture_config *config;
3632
3633         for_opt(c, update_options) {
3634                 switch (c) {
3635                 /* Generic or write options */
3636                 case IMAGEX_THREADS_OPTION:
3637                         num_threads = parse_num_threads(optarg);
3638                         if (num_threads == UINT_MAX)
3639                                 goto out_err;
3640                         break;
3641                 case IMAGEX_CHECK_OPTION:
3642                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3643                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3644                         break;
3645                 case IMAGEX_REBUILD_OPTION:
3646                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
3647                         break;
3648                 case IMAGEX_COMMAND_OPTION:
3649                         if (command_str) {
3650                                 imagex_error(T("--command may only be specified "
3651                                                "one time.  Please provide\n"
3652                                                "       the update commands "
3653                                                "on standard input instead."));
3654                                 goto out_err;
3655                         }
3656                         command_str = tstrdup(optarg);
3657                         if (!command_str) {
3658                                 imagex_error(T("Out of memory!"));
3659                                 goto out_err;
3660                         }
3661                         break;
3662                 /* Default delete options */
3663                 case IMAGEX_FORCE_OPTION:
3664                         default_delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
3665                         break;
3666                 case IMAGEX_RECURSIVE_OPTION:
3667                         default_delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
3668                         break;
3669
3670                 /* Global add option */
3671                 case IMAGEX_CONFIG_OPTION:
3672                         default_add_flags &= ~WIMLIB_ADD_FLAG_WINCONFIG;
3673                         config_file = optarg;
3674                         break;
3675
3676                 /* Default add options */
3677                 case IMAGEX_VERBOSE_OPTION:
3678                         /* No longer does anything.  */
3679                         break;
3680                 case IMAGEX_DEREFERENCE_OPTION:
3681                         default_add_flags |= WIMLIB_ADD_FLAG_DEREFERENCE;
3682                         break;
3683                 case IMAGEX_UNIX_DATA_OPTION:
3684                         default_add_flags |= WIMLIB_ADD_FLAG_UNIX_DATA;
3685                         break;
3686                 case IMAGEX_NO_ACLS_OPTION:
3687                         default_add_flags |= WIMLIB_ADD_FLAG_NO_ACLS;
3688                         break;
3689                 case IMAGEX_STRICT_ACLS_OPTION:
3690                         default_add_flags |= WIMLIB_ADD_FLAG_STRICT_ACLS;
3691                         break;
3692                 default:
3693                         goto out_usage;
3694                 }
3695         }
3696         argv += optind;
3697         argc -= optind;
3698
3699         if (argc != 1 && argc != 2)
3700                 goto out_usage;
3701         wimfile = argv[0];
3702
3703         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3704         if (ret)
3705                 goto out_free_command_str;
3706
3707         if (argc >= 2) {
3708                 /* Image explicitly specified.  */
3709                 image = wimlib_resolve_image(wim, argv[1]);
3710                 ret = verify_image_exists_and_is_single(image, argv[1],
3711                                                         wimfile);
3712                 if (ret)
3713                         goto out_wimlib_free;
3714         } else {
3715                 /* No image specified; default to image 1, but only if the WIM
3716                  * contains exactly one image.  */
3717                 struct wimlib_wim_info info;
3718
3719                 wimlib_get_wim_info(wim, &info);
3720                 if (info.image_count != 1) {
3721                         imagex_error(T("\"%"TS"\" contains %d images; Please select one."),
3722                                      wimfile, info.image_count);
3723                         wimlib_free(wim);
3724                         goto out_usage;
3725                 }
3726                 image = 1;
3727         }
3728
3729         /* Parse capture configuration file if specified */
3730         if (config_file) {
3731                 size_t config_len;
3732
3733                 config_str = file_get_text_contents(config_file, &config_len);
3734                 if (!config_str) {
3735                         ret = -1;
3736                         goto out_wimlib_free;
3737                 }
3738
3739                 config = alloca(sizeof(*config));
3740                 ret = parse_capture_config(&config_str, config_len, config);
3741                 if (ret)
3742                         goto out_free_config;
3743         } else {
3744                 config = NULL;
3745                 default_add_flags |= WIMLIB_ADD_FLAG_WINCONFIG;
3746         }
3747
3748         /* Read update commands from standard input, or the command string if
3749          * specified.  */
3750         if (command_str) {
3751                 cmd_file_contents = NULL;
3752                 cmds = parse_update_command_file(&command_str, tstrlen(command_str),
3753                                                  &num_cmds);
3754         } else {
3755                 if (isatty(STDIN_FILENO)) {
3756                         tputs(T("Reading update commands from standard input..."));
3757                         recommend_man_page(CMD_UPDATE, stdout);
3758                 }
3759                 cmd_file_contents = stdin_get_text_contents(&cmd_file_nchars);
3760                 if (!cmd_file_contents) {
3761                         ret = -1;
3762                         goto out_free_config;
3763                 }
3764
3765                 /* Parse the update commands */
3766                 cmds = parse_update_command_file(&cmd_file_contents, cmd_file_nchars,
3767                                                  &num_cmds);
3768         }
3769         if (!cmds) {
3770                 ret = -1;
3771                 goto out_free_cmd_file_contents;
3772         }
3773
3774         /* Set default flags and capture config on the update commands */
3775         for (size_t i = 0; i < num_cmds; i++) {
3776                 switch (cmds[i].op) {
3777                 case WIMLIB_UPDATE_OP_ADD:
3778                         cmds[i].add.add_flags |= default_add_flags;
3779                         cmds[i].add.config = config;
3780                         break;
3781                 case WIMLIB_UPDATE_OP_DELETE:
3782                         cmds[i].delete_.delete_flags |= default_delete_flags;
3783                         break;
3784                 default:
3785                         break;
3786                 }
3787         }
3788
3789         /* Execute the update commands */
3790         ret = wimlib_update_image(wim, image, cmds, num_cmds, update_flags,
3791                                   imagex_progress_func);
3792         if (ret)
3793                 goto out_free_cmds;
3794
3795         /* Overwrite the updated WIM */
3796         ret = wimlib_overwrite(wim, write_flags, num_threads,
3797                                imagex_progress_func);
3798 out_free_cmds:
3799         free(cmds);
3800 out_free_cmd_file_contents:
3801         free(cmd_file_contents);
3802 out_free_config:
3803         if (config) {
3804                 free(config->exclusion_pats.pats);
3805                 free(config->exclusion_exception_pats.pats);
3806                 free(config_str);
3807         }
3808 out_wimlib_free:
3809         wimlib_free(wim);
3810 out_free_command_str:
3811         free(command_str);
3812         return ret;
3813
3814 out_usage:
3815         usage(CMD_UPDATE, stderr);
3816 out_err:
3817         ret = -1;
3818         goto out_free_command_str;
3819 }
3820
3821
3822
3823 struct imagex_command {
3824         const tchar *name;
3825         int (*func)(int argc, tchar **argv, int cmd);
3826 };
3827
3828 static const struct imagex_command imagex_commands[] = {
3829         [CMD_APPEND]   = {T("append"),   imagex_capture_or_append},
3830         [CMD_APPLY]    = {T("apply"),    imagex_apply},
3831         [CMD_CAPTURE]  = {T("capture"),  imagex_capture_or_append},
3832         [CMD_DELETE]   = {T("delete"),   imagex_delete},
3833         [CMD_DIR ]     = {T("dir"),      imagex_dir},
3834         [CMD_EXPORT]   = {T("export"),   imagex_export},
3835         [CMD_EXTRACT]  = {T("extract"),  imagex_extract},
3836         [CMD_INFO]     = {T("info"),     imagex_info},
3837         [CMD_JOIN]     = {T("join"),     imagex_join},
3838 #if WIM_MOUNTING_SUPPORTED
3839         [CMD_MOUNT]    = {T("mount"),    imagex_mount_rw_or_ro},
3840         [CMD_MOUNTRW]  = {T("mountrw"),  imagex_mount_rw_or_ro},
3841 #endif
3842         [CMD_OPTIMIZE] = {T("optimize"), imagex_optimize},
3843         [CMD_SPLIT]    = {T("split"),    imagex_split},
3844 #if WIM_MOUNTING_SUPPORTED
3845         [CMD_UNMOUNT]  = {T("unmount"),  imagex_unmount},
3846 #endif
3847         [CMD_UPDATE]   = {T("update"),   imagex_update},
3848 };
3849
3850 static const tchar *usage_strings[] = {
3851 [CMD_APPEND] =
3852 T(
3853 "    %"TS" (DIRECTORY | NTFS_VOLUME) WIMFILE\n"
3854 "                    [IMAGE_NAME [IMAGE_DESCRIPTION]] [--boot] [--check]\n"
3855 "                    [--nocheck] [--flags EDITION_ID] [--dereference]\n"
3856 "                    [--config=FILE] [--threads=NUM_THREADS] [--source-list]\n"
3857 "                    [--no-acls] [--strict-acls] [--rpfix] [--norpfix]\n"
3858 "                    [--update-of=[WIMFILE:]IMAGE]\n"
3859 ),
3860 [CMD_APPLY] =
3861 T(
3862 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME | all)]\n"
3863 "                    (DIRECTORY | NTFS_VOLUME) [--check] [--ref=\"GLOB\"]\n"
3864 "                    [--no-acls] [--strict-acls] [--rpfix] [--norpfix]\n"
3865 "                    [--hardlink] [--symlink] [--include-invalid-names]\n"
3866 ),
3867 [CMD_CAPTURE] =
3868 T(
3869 "    %"TS" (DIRECTORY | NTFS_VOLUME) WIMFILE\n"
3870 "                    [IMAGE_NAME [IMAGE_DESCRIPTION]] [--boot] [--check]\n"
3871 "                    [--nocheck] [--compress=TYPE] [--flags EDITION_ID]\n"
3872 "                    [--dereference] [--config=FILE] [--threads=NUM_THREADS]\n"
3873 "                    [--source-list] [--no-acls] [--strict-acls] [--rpfix]\n"
3874 "                    [--norpfix] [--update-of=[WIMFILE:]IMAGE]\n"
3875 "                    [--delta-from=WIMFILE]\n"
3876 ),
3877 [CMD_DELETE] =
3878 T(
3879 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME | all)\n"
3880 "                    [--check] [--soft]\n"
3881 ),
3882 [CMD_DIR] =
3883 T(
3884 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--path=PATH]\n"
3885 ),
3886 [CMD_EXPORT] =
3887 T(
3888 "    %"TS" SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
3889 "                    DEST_WIMFILE [DEST_IMAGE_NAME [DEST_IMAGE_DESCRIPTION]]\n"
3890 "                    [--boot] [--check] [--nocheck] [--compress=TYPE]\n"
3891 "                    [--ref=\"GLOB\"] [--threads=NUM_THREADS] [--rebuild]\n"
3892 ),
3893 [CMD_EXTRACT] =
3894 T(
3895 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME) ([PATH...] | @LISTFILE)\n"
3896 "                    [--check] [--ref=\"GLOB\"] [--no-acls] [--strict-acls]\n"
3897 "                    [--to-stdout] [--dest-dir=CMD_DIR]\n"
3898 "                    [--include-invalid-names]\n"
3899 ),
3900 [CMD_INFO] =
3901 T(
3902 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME) [NEW_NAME\n"
3903 "                    [NEW_DESC]]] [--boot] [--check] [--nocheck] [--xml]\n"
3904 "                    [--extract-xml FILE] [--header] [--lookup-table]\n"
3905 ),
3906 [CMD_JOIN] =
3907 T(
3908 "    %"TS" OUT_WIMFILE SPLIT_WIM_PART... [--check]\n"
3909 ),
3910 #if WIM_MOUNTING_SUPPORTED
3911 [CMD_MOUNT] =
3912 T(
3913 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME)] DIRECTORY\n"
3914 "                    [--check] [--streams-interface=INTERFACE]\n"
3915 "                    [--ref=\"GLOB\"] [--allow-other]\n"
3916 ),
3917 [CMD_MOUNTRW] =
3918 T(
3919 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME)] DIRECTORY\n"
3920 "                    [--check] [--streams-interface=INTERFACE]\n"
3921 "                    [--staging-dir=CMD_DIR] [--allow-other]\n"
3922 ),
3923 #endif
3924 [CMD_OPTIMIZE] =
3925 T(
3926 "    %"TS" WIMFILE [--check] [--nocheck] [--recompress]\n"
3927 "                    [--recompress-slow] [--compress=TYPE]\n"
3928 "                    [--threads=NUM_THREADS]\n"
3929 ),
3930 [CMD_SPLIT] =
3931 T(
3932 "    %"TS" WIMFILE SPLIT_WIM_PART_1 PART_SIZE_MB [--check]\n"
3933 ),
3934 #if WIM_MOUNTING_SUPPORTED
3935 [CMD_UNMOUNT] =
3936 T(
3937 "    %"TS" DIRECTORY [--commit] [--check] [--rebuild] [--lazy]\n"
3938 ),
3939 #endif
3940 [CMD_UPDATE] =
3941 T(
3942 "    %"TS" WIMFILE [IMAGE_NUM | IMAGE_NAME] [--check] [--rebuild]\n"
3943 "                    [--threads=NUM_THREADS] [DEFAULT_ADD_OPTIONS]\n"
3944 "                    [DEFAULT_DELETE_OPTIONS] [--command=STRING] [< CMDFILE]\n"
3945 ),
3946 };
3947
3948 static const tchar *invocation_name;
3949 static int invocation_cmd = CMD_NONE;
3950
3951 static const tchar *get_cmd_string(int cmd, bool nospace)
3952 {
3953         static tchar buf[50];
3954         if (cmd == CMD_NONE) {
3955                 tsprintf(buf, T("%"TS), T(IMAGEX_PROGNAME));
3956         } else if (invocation_cmd != CMD_NONE) {
3957                 tsprintf(buf, T("wim%"TS), imagex_commands[cmd].name);
3958         } else {
3959                 const tchar *format;
3960
3961                 if (nospace)
3962                         format = T("%"TS"-%"TS"");
3963                 else
3964                         format = T("%"TS" %"TS"");
3965                 tsprintf(buf, format, invocation_name, imagex_commands[cmd].name);
3966         }
3967         return buf;
3968 }
3969
3970 static void
3971 version(void)
3972 {
3973         static const tchar *s =
3974         T(
3975 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
3976 "Copyright (C) 2012, 2013 Eric Biggers\n"
3977 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
3978 "This is free software: you are free to change and redistribute it.\n"
3979 "There is NO WARRANTY, to the extent permitted by law.\n"
3980 "\n"
3981 "Report bugs to "PACKAGE_BUGREPORT".\n"
3982         );
3983         tfputs(s, stdout);
3984 }
3985
3986
3987 static void
3988 help_or_version(int argc, tchar **argv, int cmd)
3989 {
3990         int i;
3991         const tchar *p;
3992
3993         for (i = 1; i < argc; i++) {
3994                 p = argv[i];
3995                 if (p[0] == T('-') && p[1] == T('-')) {
3996                         p += 2;
3997                         if (!tstrcmp(p, T("help"))) {
3998                                 if (cmd == CMD_NONE)
3999                                         usage_all(stdout);
4000                                 else
4001                                         usage(cmd, stdout);
4002                                 exit(0);
4003                         } else if (!tstrcmp(p, T("version"))) {
4004                                 version();
4005                                 exit(0);
4006                         }
4007                 }
4008         }
4009 }
4010
4011 static void
4012 print_usage_string(int cmd, FILE *fp)
4013 {
4014         tfprintf(fp, usage_strings[cmd], get_cmd_string(cmd, false));
4015 }
4016
4017 static void
4018 recommend_man_page(int cmd, FILE *fp)
4019 {
4020         const tchar *format_str;
4021 #ifdef __WIN32__
4022         format_str = T("Uncommon options are not listed;\n"
4023                        "See %"TS".pdf in the doc directory for more details.\n");
4024 #else
4025         format_str = T("Uncommon options are not listed;\n"
4026                        "Try `man %"TS"' for more details.\n");
4027 #endif
4028         tfprintf(fp, format_str, get_cmd_string(cmd, true));
4029 }
4030
4031 static void
4032 usage(int cmd, FILE *fp)
4033 {
4034         tfprintf(fp, T("Usage:\n"));
4035         print_usage_string(cmd, fp);
4036         tfprintf(fp, T("\n"));
4037         recommend_man_page(cmd, fp);
4038 }
4039
4040 static void
4041 usage_all(FILE *fp)
4042 {
4043         tfprintf(fp, T("Usage:\n"));
4044         for (int cmd = 0; cmd < CMD_MAX; cmd++) {
4045                 print_usage_string(cmd, fp);
4046                 tfprintf(fp, T("\n"));
4047         }
4048         static const tchar *extra =
4049         T(
4050 "    %"TS" --help\n"
4051 "    %"TS" --version\n"
4052 "\n"
4053 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
4054 "\n"
4055         );
4056         tfprintf(fp, extra, invocation_name, invocation_name);
4057         recommend_man_page(CMD_NONE, fp);
4058 }
4059
4060 /* Entry point for wimlib's ImageX implementation.  On UNIX the command
4061  * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
4062  * something else), while an Windows the command arguments will be UTF-16LE
4063  * encoded 'wchar_t' strings. */
4064 int
4065 #ifdef __WIN32__
4066 wmain(int argc, wchar_t **argv, wchar_t **envp)
4067 #else
4068 main(int argc, char **argv)
4069 #endif
4070 {
4071         int ret;
4072         int init_flags = 0;
4073         int cmd;
4074
4075         imagex_info_file = stdout;
4076         invocation_name = tbasename(argv[0]);
4077
4078 #ifndef __WIN32__
4079         if (getenv("WIMLIB_IMAGEX_USE_UTF8")) {
4080                 init_flags |= WIMLIB_INIT_FLAG_ASSUME_UTF8;
4081         } else {
4082                 char *codeset;
4083
4084                 setlocale(LC_ALL, "");
4085                 codeset = nl_langinfo(CODESET);
4086                 if (!strstr(codeset, "UTF-8") &&
4087                     !strstr(codeset, "UTF8") &&
4088                     !strstr(codeset, "utf-8") &&
4089                     !strstr(codeset, "utf8"))
4090                 {
4091                         fprintf(stderr,
4092 "WARNING: Running %"TS" in a UTF-8 locale is recommended!\n"
4093 "         Maybe try: `export LANG=en_US.UTF-8'?\n"
4094 "         Alternatively, set the environmental variable WIMLIB_IMAGEX_USE_UTF8\n"
4095 "         to any value to force wimlib to use UTF-8.\n",
4096                         invocation_name);
4097
4098                 }
4099         }
4100
4101 #endif /* !__WIN32__ */
4102
4103         {
4104                 tchar *igcase = tgetenv(T("WIMLIB_IMAGEX_IGNORE_CASE"));
4105                 if (igcase != NULL) {
4106                         if (!tstrcmp(igcase, T("no")) ||
4107                             !tstrcmp(igcase, T("0")))
4108                                 init_flags |= WIMLIB_INIT_FLAG_DEFAULT_CASE_SENSITIVE;
4109                         else if (!tstrcmp(igcase, T("yes")) ||
4110                                  !tstrcmp(igcase, T("1")))
4111                                 init_flags |= WIMLIB_INIT_FLAG_DEFAULT_CASE_INSENSITIVE;
4112                         else {
4113                                 fprintf(stderr,
4114                                         "WARNING: Ignoring unknown setting of "
4115                                         "WIMLIB_IMAGEX_IGNORE_CASE\n");
4116                         }
4117                 }
4118         }
4119
4120         /* Allow being invoked as wimCOMMAND (e.g. wimapply).  */
4121         cmd = CMD_NONE;
4122         if (!tstrncmp(invocation_name, T("wim"), 3) &&
4123             tstrcmp(invocation_name, T(IMAGEX_PROGNAME))) {
4124                 for (int i = 0; i < CMD_MAX; i++) {
4125                         if (!tstrcmp(invocation_name + 3,
4126                                      imagex_commands[i].name))
4127                         {
4128                                 invocation_cmd = i;
4129                                 cmd = i;
4130                                 break;
4131                         }
4132                 }
4133         }
4134
4135         /* Unless already known from the invocation name, determine which
4136          * command was specified.  */
4137         if (cmd == CMD_NONE) {
4138                 if (argc < 2) {
4139                         imagex_error(T("No command specified!\n"));
4140                         usage_all(stderr);
4141                         exit(2);
4142                 }
4143                 for (int i = 0; i < CMD_MAX; i++) {
4144                         if (!tstrcmp(argv[1], imagex_commands[i].name)) {
4145                                 cmd = i;
4146                                 break;
4147                         }
4148                 }
4149                 if (cmd != CMD_NONE) {
4150                         argc--;
4151                         argv++;
4152                 }
4153         }
4154
4155         /* Handle --help and --version.  --help can be either for the program as
4156          * a whole (cmd == CMD_NONE) or just for a specific command (cmd !=
4157          * CMD_NONE).  Note: help_or_version() will not return if a --help or
4158          * --version argument was found.  */
4159         help_or_version(argc, argv, cmd);
4160
4161         /* Bail if a valid command was not specified.  */
4162         if (cmd == CMD_NONE) {
4163                 imagex_error(T("Unrecognized command: `%"TS"'\n"), argv[1]);
4164                 usage_all(stderr);
4165                 exit(2);
4166         }
4167
4168         /* Enable warning and error messages in wimlib be more user-friendly.
4169          * */
4170         wimlib_set_print_errors(true);
4171
4172         /* Initialize wimlib.  */
4173         ret = wimlib_global_init(init_flags);
4174         if (ret)
4175                 goto out_check_status;
4176
4177         /* Call the command handler function.  */
4178         ret = imagex_commands[cmd].func(argc, argv, cmd);
4179
4180         /* Check for error writing to standard output, especially since for some
4181          * commands, writing to standard output is part of the program's actual
4182          * behavior and not just for informational purposes.  */
4183         if (ferror(stdout) || fclose(stdout)) {
4184                 imagex_error_with_errno(T("error writing to standard output"));
4185                 if (ret == 0)
4186                         ret = -1;
4187         }
4188 out_check_status:
4189         /* Exit status (ret):  -1 indicates an error found by 'wimlib-imagex'
4190          * itself (not by wimlib).  0 indicates success.  > 0 indicates a wimlib
4191          * error code from which an error message can be printed.  */
4192         if (ret > 0) {
4193                 imagex_error(T("Exiting with error code %d:\n"
4194                                "       %"TS"."), ret,
4195                              wimlib_get_error_string(ret));
4196                 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
4197                         imagex_error_with_errno(T("errno"));
4198         }
4199         /* Make wimlib free any resources it's holding (although this is not
4200          * strictly necessary because the process is ending anyway).  */
4201         wimlib_global_cleanup();
4202         return ret;
4203 }