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