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