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