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