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