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