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