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