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