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