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