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