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