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