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