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