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