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