]> wimlib.net Git - wimlib/blob - programs/imagex.c
wimexport: Only keep chunk size if compression type unchanged
[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                 /* Use same chunk size if compression type is the same.  */
2551                 if (compression_type == src_info.compression_type)
2552                         wimlib_set_output_chunk_size(dest_wim, src_info.chunk_size);
2553         }
2554
2555         image = wimlib_resolve_image(src_wim, src_image_num_or_name);
2556         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
2557         if (ret)
2558                 goto out_free_dest_wim;
2559
2560         if (refglobs.num_strings) {
2561                 ret = wim_reference_globs(src_wim, &refglobs, open_flags);
2562                 if (ret)
2563                         goto out_free_dest_wim;
2564         }
2565
2566         if ((export_flags & WIMLIB_EXPORT_FLAG_BOOT) &&
2567             image == WIMLIB_ALL_IMAGES && src_info.boot_index == 0)
2568         {
2569                 imagex_error(T("--boot specified for all-images export, but source WIM "
2570                                "has no bootable image."));
2571                 ret = -1;
2572                 goto out_free_dest_wim;
2573         }
2574
2575         ret = wimlib_export_image(src_wim, image, dest_wim, dest_name,
2576                                   dest_desc, export_flags, imagex_progress_func);
2577         if (ret) {
2578                 if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
2579                         do_resource_not_found_warning(src_wimfile,
2580                                                       &src_info, &refglobs);
2581                 }
2582                 goto out_free_dest_wim;
2583         }
2584
2585         if (!wim_is_new)
2586                 ret = wimlib_overwrite(dest_wim, write_flags, num_threads,
2587                                        imagex_progress_func);
2588         else if (dest_wimfile)
2589                 ret = wimlib_write(dest_wim, dest_wimfile, WIMLIB_ALL_IMAGES,
2590                                    write_flags, num_threads,
2591                                    imagex_progress_func);
2592         else
2593                 ret = wimlib_write_to_fd(dest_wim, dest_wim_fd,
2594                                          WIMLIB_ALL_IMAGES, write_flags,
2595                                          num_threads, imagex_progress_func);
2596 out_free_dest_wim:
2597         wimlib_free(dest_wim);
2598 out_free_src_wim:
2599         wimlib_free(src_wim);
2600 out_free_refglobs:
2601         string_set_destroy(&refglobs);
2602         return ret;
2603
2604 out_usage:
2605         usage(CMD_EXPORT, stderr);
2606 out_err:
2607         ret = -1;
2608         goto out_free_refglobs;
2609 }
2610
2611 static bool
2612 is_root_wim_path(const tchar *path)
2613 {
2614         const tchar *p;
2615         for (p = path; *p; p++)
2616                 if (*p != T('\\') && *p != T('/'))
2617                         return false;
2618         return true;
2619 }
2620
2621 static void
2622 free_extract_commands(struct wimlib_extract_command *cmds, size_t num_cmds,
2623                       const tchar *dest_dir)
2624 {
2625         for (size_t i = 0; i < num_cmds; i++)
2626                 if (cmds[i].fs_dest_path != dest_dir)
2627                         free(cmds[i].fs_dest_path);
2628         free(cmds);
2629 }
2630
2631 static struct wimlib_extract_command *
2632 prepare_extract_commands(tchar **paths, unsigned num_paths,
2633                          int extract_flags, tchar *dest_dir,
2634                          size_t *num_cmds_ret)
2635 {
2636         struct wimlib_extract_command *cmds;
2637         size_t num_cmds;
2638         tchar *emptystr = T("");
2639
2640         if (num_paths == 0) {
2641                 num_paths = 1;
2642                 paths = &emptystr;
2643         }
2644         num_cmds = num_paths;
2645         cmds = calloc(num_cmds, sizeof(cmds[0]));
2646         if (!cmds) {
2647                 imagex_error(T("Out of memory!"));
2648                 return NULL;
2649         }
2650
2651         for (size_t i = 0; i < num_cmds; i++) {
2652                 cmds[i].extract_flags = extract_flags;
2653                 cmds[i].wim_source_path = paths[i];
2654                 if (is_root_wim_path(paths[i])) {
2655                         cmds[i].fs_dest_path = dest_dir;
2656                 } else {
2657                         size_t len = tstrlen(dest_dir) + 1 + tstrlen(paths[i]);
2658                         cmds[i].fs_dest_path = malloc((len + 1) * sizeof(tchar));
2659                         if (!cmds[i].fs_dest_path) {
2660                                 free_extract_commands(cmds, num_cmds, dest_dir);
2661                                 return NULL;
2662                         }
2663                         tsprintf(cmds[i].fs_dest_path,
2664                                  T("%"TS""OS_PREFERRED_PATH_SEPARATOR_STRING"%"TS),
2665                                  dest_dir, tbasename(paths[i]));
2666                 }
2667         }
2668         *num_cmds_ret = num_cmds;
2669         return cmds;
2670 }
2671
2672 /* Extract files or directories from a WIM image */
2673 static int
2674 imagex_extract(int argc, tchar **argv, int cmd)
2675 {
2676         int c;
2677         int open_flags = 0;
2678         int image;
2679         WIMStruct *wim;
2680         int ret;
2681         const tchar *wimfile;
2682         const tchar *image_num_or_name;
2683         tchar *dest_dir = T(".");
2684         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL | WIMLIB_EXTRACT_FLAG_NORPFIX;
2685
2686         STRING_SET(refglobs);
2687
2688         struct wimlib_extract_command *cmds;
2689         size_t num_cmds;
2690
2691         for_opt(c, extract_options) {
2692                 switch (c) {
2693                 case IMAGEX_CHECK_OPTION:
2694                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2695                         break;
2696                 case IMAGEX_VERBOSE_OPTION:
2697                         /* No longer does anything.  */
2698                         break;
2699                 case IMAGEX_REF_OPTION:
2700                         ret = string_set_append(&refglobs, optarg);
2701                         if (ret)
2702                                 goto out_free_refglobs;
2703                         break;
2704                 case IMAGEX_UNIX_DATA_OPTION:
2705                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
2706                         break;
2707                 case IMAGEX_NO_ACLS_OPTION:
2708                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
2709                         break;
2710                 case IMAGEX_STRICT_ACLS_OPTION:
2711                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
2712                         break;
2713                 case IMAGEX_DEST_DIR_OPTION:
2714                         dest_dir = optarg;
2715                         break;
2716                 case IMAGEX_TO_STDOUT_OPTION:
2717                         extract_flags |= WIMLIB_EXTRACT_FLAG_TO_STDOUT;
2718                         imagex_info_file = stderr;
2719                         imagex_be_quiet = true;
2720                         break;
2721                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
2722                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
2723                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
2724                         break;
2725                 default:
2726                         goto out_usage;
2727                 }
2728         }
2729         argc -= optind;
2730         argv += optind;
2731
2732         if (argc < 2)
2733                 goto out_usage;
2734
2735         wimfile = argv[0];
2736         image_num_or_name = argv[1];
2737
2738         argc -= 2;
2739         argv += 2;
2740
2741         cmds = prepare_extract_commands(argv, argc, extract_flags, dest_dir,
2742                                         &num_cmds);
2743         if (!cmds)
2744                 goto out_err;
2745
2746         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2747         if (ret)
2748                 goto out_free_cmds;
2749
2750         image = wimlib_resolve_image(wim, image_num_or_name);
2751         ret = verify_image_exists_and_is_single(image,
2752                                                 image_num_or_name,
2753                                                 wimfile);
2754         if (ret)
2755                 goto out_wimlib_free;
2756
2757         if (refglobs.num_strings) {
2758                 ret = wim_reference_globs(wim, &refglobs, open_flags);
2759                 if (ret)
2760                         goto out_wimlib_free;
2761         }
2762
2763         ret = wimlib_extract_files(wim, image, cmds, num_cmds, 0,
2764                                    imagex_progress_func);
2765         if (ret == 0) {
2766                 if (!imagex_be_quiet)
2767                         imagex_printf(T("Done extracting files.\n"));
2768         } else if (ret == WIMLIB_ERR_PATH_DOES_NOT_EXIST) {
2769                 tfprintf(stderr, T("Note: You can use `%"TS"' to see what "
2770                                    "files and directories\n"
2771                                    "      are in the WIM image.\n"),
2772                                 get_cmd_string(CMD_INFO, false));
2773         } else if (ret == WIMLIB_ERR_RESOURCE_NOT_FOUND) {
2774                 struct wimlib_wim_info info;
2775
2776                 wimlib_get_wim_info(wim, &info);
2777                 do_resource_not_found_warning(wimfile, &info, &refglobs);
2778         }
2779 out_wimlib_free:
2780         wimlib_free(wim);
2781 out_free_cmds:
2782         free_extract_commands(cmds, num_cmds, dest_dir);
2783 out_free_refglobs:
2784         string_set_destroy(&refglobs);
2785         return ret;
2786
2787 out_usage:
2788         usage(CMD_EXTRACT, stderr);
2789 out_err:
2790         ret = -1;
2791         goto out_free_refglobs;
2792 }
2793
2794 static void print_byte_field(const uint8_t field[], size_t len)
2795 {
2796         while (len--)
2797                 tprintf(T("%02hhx"), *field++);
2798 }
2799
2800 static void
2801 print_wim_information(const tchar *wimfile, const struct wimlib_wim_info *info)
2802 {
2803         tputs(T("WIM Information:"));
2804         tputs(T("----------------"));
2805         tprintf(T("Path:           %"TS"\n"), wimfile);
2806         tprintf(T("GUID:           0x"));
2807         print_byte_field(info->guid, sizeof(info->guid));
2808         tputchar(T('\n'));
2809         tprintf(T("Version:        %u\n"), info->wim_version);
2810         tprintf(T("Image Count:    %d\n"), info->image_count);
2811         tprintf(T("Compression:    %"TS"\n"),
2812                 wimlib_get_compression_type_string(info->compression_type));
2813         tprintf(T("Chunk Size:     %"PRIu32" bytes\n"),
2814                 info->chunk_size);
2815         tprintf(T("Part Number:    %d/%d\n"), info->part_number, info->total_parts);
2816         tprintf(T("Boot Index:     %d\n"), info->boot_index);
2817         tprintf(T("Size:           %"PRIu64" bytes\n"), info->total_bytes);
2818         tprintf(T("Integrity Info: %"TS"\n"),
2819                 info->has_integrity_table ? T("yes") : T("no"));
2820         tprintf(T("Relative path junction: %"TS"\n"),
2821                 info->has_rpfix ? T("yes") : T("no"));
2822         tprintf(T("Pipable:        %"TS"\n"),
2823                 info->pipable ? T("yes") : T("no"));
2824         tputchar(T('\n'));
2825 }
2826
2827 static int
2828 print_resource(const struct wimlib_resource_entry *resource,
2829                void *_ignore)
2830 {
2831         tprintf(T("Uncompressed size     = %"PRIu64" bytes\n"),
2832                 resource->uncompressed_size);
2833         if (resource->packed) {
2834                 tprintf(T("Raw compressed size   = %"PRIu64" bytes\n"),
2835                         resource->raw_resource_compressed_size);
2836
2837                 tprintf(T("Raw offset in WIM     = %"PRIu64" bytes\n"),
2838                         resource->raw_resource_offset_in_wim);
2839
2840                 tprintf(T("Offset in raw         = %"PRIu64" bytes\n"),
2841                         resource->offset);
2842         } else {
2843                 tprintf(T("Compressed size       = %"PRIu64" bytes\n"),
2844                         resource->compressed_size);
2845
2846                 tprintf(T("Offset in WIM         = %"PRIu64" bytes\n"),
2847                         resource->offset);
2848         }
2849
2850         tprintf(T("Part Number           = %u\n"), resource->part_number);
2851         tprintf(T("Reference Count       = %u\n"), resource->reference_count);
2852
2853         tprintf(T("Hash                  = 0x"));
2854         print_byte_field(resource->sha1_hash, sizeof(resource->sha1_hash));
2855         tputchar(T('\n'));
2856
2857         tprintf(T("Flags                 = "));
2858         if (resource->is_compressed)
2859                 tprintf(T("WIM_RESHDR_FLAG_COMPRESSED  "));
2860         if (resource->is_metadata)
2861                 tprintf(T("WIM_RESHDR_FLAG_METADATA  "));
2862         if (resource->is_free)
2863                 tprintf(T("WIM_RESHDR_FLAG_FREE  "));
2864         if (resource->is_spanned)
2865                 tprintf(T("WIM_RESHDR_FLAG_SPANNED  "));
2866         if (resource->packed)
2867                 tprintf(T("WIM_RESHDR_FLAG_PACKED_STREAMS  "));
2868         tputchar(T('\n'));
2869         tputchar(T('\n'));
2870         return 0;
2871 }
2872
2873 static void
2874 print_lookup_table(WIMStruct *wim)
2875 {
2876         wimlib_iterate_lookup_table(wim, 0, print_resource, NULL);
2877 }
2878
2879 /* Prints information about a WIM file; also can mark an image as bootable,
2880  * change the name of an image, or change the description of an image. */
2881 static int
2882 imagex_info(int argc, tchar **argv, int cmd)
2883 {
2884         int c;
2885         bool boot         = false;
2886         bool check        = false;
2887         bool nocheck      = false;
2888         bool header       = false;
2889         bool lookup_table = false;
2890         bool xml          = false;
2891         bool metadata     = false;
2892         bool short_header = true;
2893         const tchar *xml_out_file = NULL;
2894         const tchar *wimfile;
2895         const tchar *image_num_or_name;
2896         const tchar *new_name;
2897         const tchar *new_desc;
2898         WIMStruct *wim;
2899         int image;
2900         int ret;
2901         int open_flags = 0;
2902         struct wimlib_wim_info info;
2903
2904         for_opt(c, info_options) {
2905                 switch (c) {
2906                 case IMAGEX_BOOT_OPTION:
2907                         boot = true;
2908                         break;
2909                 case IMAGEX_CHECK_OPTION:
2910                         check = true;
2911                         break;
2912                 case IMAGEX_NOCHECK_OPTION:
2913                         nocheck = true;
2914                         break;
2915                 case IMAGEX_HEADER_OPTION:
2916                         header = true;
2917                         short_header = false;
2918                         break;
2919                 case IMAGEX_LOOKUP_TABLE_OPTION:
2920                         lookup_table = true;
2921                         short_header = false;
2922                         break;
2923                 case IMAGEX_XML_OPTION:
2924                         xml = true;
2925                         short_header = false;
2926                         break;
2927                 case IMAGEX_EXTRACT_XML_OPTION:
2928                         xml_out_file = optarg;
2929                         short_header = false;
2930                         break;
2931                 case IMAGEX_METADATA_OPTION:
2932                         metadata = true;
2933                         short_header = false;
2934                         break;
2935                 default:
2936                         goto out_usage;
2937                 }
2938         }
2939
2940         argc -= optind;
2941         argv += optind;
2942         if (argc < 1 || argc > 4)
2943                 goto out_usage;
2944
2945         wimfile           = argv[0];
2946         image_num_or_name = (argc >= 2) ? argv[1] : T("all");
2947         new_name          = (argc >= 3) ? argv[2] : NULL;
2948         new_desc          = (argc >= 4) ? argv[3] : NULL;
2949
2950         if (check && nocheck) {
2951                 imagex_error(T("Can't specify both --check and --nocheck"));
2952                 goto out_err;
2953         }
2954
2955         if (check)
2956                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2957
2958         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2959         if (ret)
2960                 goto out;
2961
2962         wimlib_get_wim_info(wim, &info);
2963
2964         image = wimlib_resolve_image(wim, image_num_or_name);
2965         ret = WIMLIB_ERR_INVALID_IMAGE;
2966         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
2967                 verify_image_exists(image, image_num_or_name, wimfile);
2968                 if (boot) {
2969                         imagex_error(T("If you would like to set the boot "
2970                                        "index to 0, specify image \"0\" with "
2971                                        "the --boot flag."));
2972                 }
2973                 goto out_wimlib_free;
2974         }
2975
2976         if (boot && info.image_count == 0) {
2977                 imagex_error(T("--boot is meaningless on a WIM with no images"));
2978                 goto out_wimlib_free;
2979         }
2980
2981         if (image == WIMLIB_ALL_IMAGES && info.image_count > 1) {
2982                 if (boot) {
2983                         imagex_error(T("Cannot specify the --boot flag "
2984                                        "without specifying a specific "
2985                                        "image in a multi-image WIM"));
2986                         goto out_wimlib_free;
2987                 }
2988                 if (new_name) {
2989                         imagex_error(T("Cannot specify the NEW_NAME "
2990                                        "without specifying a specific "
2991                                        "image in a multi-image WIM"));
2992                         goto out_wimlib_free;
2993                 }
2994         }
2995
2996         /* Operations that print information are separated from operations that
2997          * recreate the WIM file. */
2998         if (!new_name && !boot) {
2999
3000                 /* Read-only operations */
3001
3002                 if (image == WIMLIB_NO_IMAGE) {
3003                         imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\""),
3004                                      image_num_or_name, wimfile);
3005                         goto out_wimlib_free;
3006                 }
3007
3008                 if (image == WIMLIB_ALL_IMAGES && short_header)
3009                         print_wim_information(wimfile, &info);
3010
3011                 if (header)
3012                         wimlib_print_header(wim);
3013
3014                 if (lookup_table) {
3015                         if (info.total_parts != 1) {
3016                                 tfprintf(stderr, T("Warning: Only showing the lookup table "
3017                                                    "for part %d of a %d-part WIM.\n"),
3018                                          info.part_number, info.total_parts);
3019                         }
3020                         print_lookup_table(wim);
3021                 }
3022
3023                 if (xml) {
3024                         ret = wimlib_extract_xml_data(wim, stdout);
3025                         if (ret)
3026                                 goto out_wimlib_free;
3027                 }
3028
3029                 if (xml_out_file) {
3030                         FILE *fp;
3031
3032                         fp = tfopen(xml_out_file, T("wb"));
3033                         if (!fp) {
3034                                 imagex_error_with_errno(T("Failed to open the "
3035                                                           "file \"%"TS"\" for "
3036                                                           "writing"),
3037                                                         xml_out_file);
3038                                 ret = -1;
3039                                 goto out_wimlib_free;
3040                         }
3041                         ret = wimlib_extract_xml_data(wim, fp);
3042                         if (fclose(fp)) {
3043                                 imagex_error(T("Failed to close the file "
3044                                                "\"%"TS"\""),
3045                                              xml_out_file);
3046                                 ret = -1;
3047                         }
3048                         if (ret)
3049                                 goto out_wimlib_free;
3050                 }
3051
3052                 if (short_header)
3053                         wimlib_print_available_images(wim, image);
3054
3055                 if (metadata) {
3056                         ret = wimlib_print_metadata(wim, image);
3057                         if (ret)
3058                                 goto out_wimlib_free;
3059                 }
3060                 ret = 0;
3061         } else {
3062
3063                 /* Modification operations */
3064
3065                 if (image == WIMLIB_ALL_IMAGES)
3066                         image = 1;
3067
3068                 if (image == WIMLIB_NO_IMAGE && new_name) {
3069                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
3070                                        "when using image 0"), new_name);
3071                         ret = -1;
3072                         goto out_wimlib_free;
3073                 }
3074
3075                 if (boot) {
3076                         if (image == info.boot_index) {
3077                                 imagex_printf(T("Image %d is already marked as "
3078                                           "bootable.\n"), image);
3079                                 boot = false;
3080                         } else {
3081                                 imagex_printf(T("Marking image %d as bootable.\n"),
3082                                         image);
3083                                 info.boot_index = image;
3084                                 ret = wimlib_set_wim_info(wim, &info,
3085                                                           WIMLIB_CHANGE_BOOT_INDEX);
3086                                 if (ret)
3087                                         goto out_wimlib_free;
3088                         }
3089                 }
3090                 if (new_name) {
3091                         if (!tstrcmp(wimlib_get_image_name(wim, image), new_name))
3092                         {
3093                                 imagex_printf(T("Image %d is already named \"%"TS"\".\n"),
3094                                         image, new_name);
3095                                 new_name = NULL;
3096                         } else {
3097                                 imagex_printf(T("Changing the name of image %d to "
3098                                           "\"%"TS"\".\n"), image, new_name);
3099                                 ret = wimlib_set_image_name(wim, image, new_name);
3100                                 if (ret)
3101                                         goto out_wimlib_free;
3102                         }
3103                 }
3104                 if (new_desc) {
3105                         const tchar *old_desc;
3106                         old_desc = wimlib_get_image_description(wim, image);
3107                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
3108                                 imagex_printf(T("The description of image %d is already "
3109                                           "\"%"TS"\".\n"), image, new_desc);
3110                                 new_desc = NULL;
3111                         } else {
3112                                 imagex_printf(T("Changing the description of image %d "
3113                                           "to \"%"TS"\".\n"), image, new_desc);
3114                                 ret = wimlib_set_image_descripton(wim, image,
3115                                                                   new_desc);
3116                                 if (ret)
3117                                         goto out_wimlib_free;
3118                         }
3119                 }
3120
3121                 /* Only call wimlib_overwrite() if something actually needs to
3122                  * be changed.  */
3123                 if (boot || new_name || new_desc ||
3124                     (check && !info.has_integrity_table) ||
3125                     (nocheck && info.has_integrity_table))
3126                 {
3127                         int write_flags = 0;
3128
3129                         if (check)
3130                                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3131                         if (nocheck)
3132                                 write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3133                         ret = wimlib_overwrite(wim, write_flags, 1,
3134                                                imagex_progress_func);
3135                 } else {
3136                         imagex_printf(T("The file \"%"TS"\" was not modified "
3137                                         "because nothing needed to be done.\n"),
3138                                       wimfile);
3139                         ret = 0;
3140                 }
3141         }
3142 out_wimlib_free:
3143         wimlib_free(wim);
3144 out:
3145         return ret;
3146
3147 out_usage:
3148         usage(CMD_INFO, stderr);
3149 out_err:
3150         ret = -1;
3151         goto out;
3152 }
3153
3154 /* Join split WIMs into one part WIM */
3155 static int
3156 imagex_join(int argc, tchar **argv, int cmd)
3157 {
3158         int c;
3159         int swm_open_flags = 0;
3160         int wim_write_flags = 0;
3161         const tchar *output_path;
3162         int ret;
3163
3164         for_opt(c, join_options) {
3165                 switch (c) {
3166                 case IMAGEX_CHECK_OPTION:
3167                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3168                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3169                         break;
3170                 default:
3171                         goto out_usage;
3172                 }
3173         }
3174         argc -= optind;
3175         argv += optind;
3176
3177         if (argc < 2) {
3178                 imagex_error(T("Must specify one or more split WIM (.swm) "
3179                                "parts to join"));
3180                 goto out_usage;
3181         }
3182         output_path = argv[0];
3183         ret = wimlib_join((const tchar * const *)++argv,
3184                           --argc,
3185                           output_path,
3186                           swm_open_flags,
3187                           wim_write_flags,
3188                           imagex_progress_func);
3189 out:
3190         return ret;
3191
3192 out_usage:
3193         usage(CMD_JOIN, stderr);
3194         ret = -1;
3195         goto out;
3196 }
3197
3198 #if WIM_MOUNTING_SUPPORTED
3199
3200 /* Mounts a WIM image.  */
3201 static int
3202 imagex_mount_rw_or_ro(int argc, tchar **argv, int cmd)
3203 {
3204         int c;
3205         int mount_flags = 0;
3206         int open_flags = 0;
3207         const tchar *staging_dir = NULL;
3208         const tchar *wimfile;
3209         const tchar *dir;
3210         WIMStruct *wim;
3211         struct wimlib_wim_info info;
3212         int image;
3213         int ret;
3214
3215         STRING_SET(refglobs);
3216
3217         if (cmd == CMD_MOUNTRW) {
3218                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
3219                 open_flags |= WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3220         }
3221
3222         for_opt(c, mount_options) {
3223                 switch (c) {
3224                 case IMAGEX_ALLOW_OTHER_OPTION:
3225                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
3226                         break;
3227                 case IMAGEX_CHECK_OPTION:
3228                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3229                         break;
3230                 case IMAGEX_DEBUG_OPTION:
3231                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
3232                         break;
3233                 case IMAGEX_STREAMS_INTERFACE_OPTION:
3234                         if (!tstrcasecmp(optarg, T("none")))
3235                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
3236                         else if (!tstrcasecmp(optarg, T("xattr")))
3237                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
3238                         else if (!tstrcasecmp(optarg, T("windows")))
3239                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
3240                         else {
3241                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
3242                                              optarg);
3243                                 goto out_usage;
3244                         }
3245                         break;
3246                 case IMAGEX_REF_OPTION:
3247                         ret = string_set_append(&refglobs, optarg);
3248                         if (ret)
3249                                 goto out_free_refglobs;
3250                         break;
3251                 case IMAGEX_STAGING_DIR_OPTION:
3252                         staging_dir = optarg;
3253                         break;
3254                 case IMAGEX_UNIX_DATA_OPTION:
3255                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
3256                         break;
3257                 default:
3258                         goto out_usage;
3259                 }
3260         }
3261         argc -= optind;
3262         argv += optind;
3263         if (argc != 2 && argc != 3)
3264                 goto out_usage;
3265
3266         wimfile = argv[0];
3267
3268         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3269         if (ret)
3270                 goto out_free_refglobs;
3271
3272         wimlib_get_wim_info(wim, &info);
3273
3274         if (argc >= 3) {
3275                 /* Image explicitly specified.  */
3276                 image = wimlib_resolve_image(wim, argv[1]);
3277                 dir = argv[2];
3278                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
3279                 if (ret)
3280                         goto out_free_wim;
3281         } else {
3282                 /* No image specified; default to image 1, but only if the WIM
3283                  * contains exactly one image.  */
3284
3285                 if (info.image_count != 1) {
3286                         imagex_error(T("\"%"TS"\" contains %d images; Please "
3287                                        "select one."), wimfile, info.image_count);
3288                         wimlib_free(wim);
3289                         goto out_usage;
3290                 }
3291                 image = 1;
3292                 dir = argv[1];
3293         }
3294
3295         if (refglobs.num_strings) {
3296                 ret = wim_reference_globs(wim, &refglobs, open_flags);
3297                 if (ret)
3298                         goto out_free_wim;
3299         }
3300
3301         ret = wimlib_mount_image(wim, image, dir, mount_flags, staging_dir);
3302         if (ret) {
3303                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
3304                                "on \"%"TS"\""),
3305                              image, wimfile, dir);
3306         }
3307 out_free_wim:
3308         wimlib_free(wim);
3309 out_free_refglobs:
3310         string_set_destroy(&refglobs);
3311         return ret;
3312
3313 out_usage:
3314         usage(cmd, stderr);
3315         ret = -1;
3316         goto out_free_refglobs;
3317 }
3318 #endif /* WIM_MOUNTING_SUPPORTED */
3319
3320 /* Rebuild a WIM file */
3321 static int
3322 imagex_optimize(int argc, tchar **argv, int cmd)
3323 {
3324         int c;
3325         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3326         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
3327         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
3328         uint32_t chunk_size = UINT32_MAX;
3329         int ret;
3330         WIMStruct *wim;
3331         const tchar *wimfile;
3332         off_t old_size;
3333         off_t new_size;
3334         unsigned num_threads = 0;
3335
3336         for_opt(c, optimize_options) {
3337                 switch (c) {
3338                 case IMAGEX_CHECK_OPTION:
3339                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3340                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3341                         break;
3342                 case IMAGEX_NOCHECK_OPTION:
3343                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3344                         break;
3345                 case IMAGEX_COMPRESS_OPTION:
3346                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3347                         compression_type = get_compression_type(optarg);
3348                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
3349                                 goto out_err;
3350                         break;
3351                 case IMAGEX_RECOMPRESS_OPTION:
3352                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3353                         break;
3354                 case IMAGEX_COMPRESS_SLOW_OPTION:
3355                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3356                         compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
3357                         ret = set_compress_slow();
3358                         if (ret)
3359                                 goto out_err;
3360                         break;
3361                 case IMAGEX_CHUNK_SIZE_OPTION:
3362                         chunk_size = parse_chunk_size(optarg);
3363                         if (chunk_size == UINT32_MAX)
3364                                 goto out_err;
3365                         break;
3366                 case IMAGEX_PACK_STREAMS_OPTION:
3367                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
3368                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3369                         break;
3370                 case IMAGEX_NO_PACK_STREAMS_OPTION:
3371                         write_flags |= WIMLIB_WRITE_FLAG_NO_PACK_STREAMS;
3372                         break;
3373                 case IMAGEX_THREADS_OPTION:
3374                         num_threads = parse_num_threads(optarg);
3375                         if (num_threads == UINT_MAX)
3376                                 goto out_err;
3377                         break;
3378                 case IMAGEX_PIPABLE_OPTION:
3379                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
3380                         break;
3381                 case IMAGEX_NOT_PIPABLE_OPTION:
3382                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
3383                         break;
3384                 default:
3385                         goto out_usage;
3386                 }
3387         }
3388         argc -= optind;
3389         argv += optind;
3390
3391         if (argc != 1)
3392                 goto out_usage;
3393
3394         wimfile = argv[0];
3395
3396         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3397         if (ret)
3398                 goto out;
3399
3400         if (compression_type != WIMLIB_COMPRESSION_TYPE_INVALID) {
3401                 /* Change compression type.  */
3402                 ret = wimlib_set_output_compression_type(wim, compression_type);
3403                 if (ret)
3404                         goto out_wimlib_free;
3405         }
3406
3407         if (chunk_size != UINT32_MAX) {
3408                 /* Change chunk size.  */
3409                 ret = wimlib_set_output_chunk_size(wim, chunk_size);
3410                 if (ret)
3411                         goto out_wimlib_free;
3412         }
3413
3414         old_size = file_get_size(wimfile);
3415         tprintf(T("\"%"TS"\" original size: "), wimfile);
3416         if (old_size == -1)
3417                 tputs(T("Unknown"));
3418         else
3419                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
3420
3421         ret = wimlib_overwrite(wim, write_flags, num_threads,
3422                                imagex_progress_func);
3423         if (ret) {
3424                 imagex_error(T("Optimization of \"%"TS"\" failed."), wimfile);
3425                 goto out_wimlib_free;
3426         }
3427
3428         new_size = file_get_size(wimfile);
3429         tprintf(T("\"%"TS"\" optimized size: "), wimfile);
3430         if (new_size == -1)
3431                 tputs(T("Unknown"));
3432         else
3433                 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
3434
3435         tfputs(T("Space saved: "), stdout);
3436         if (new_size != -1 && old_size != -1) {
3437                 tprintf(T("%lld KiB\n"),
3438                        ((long long)old_size - (long long)new_size) >> 10);
3439         } else {
3440                 tputs(T("Unknown"));
3441         }
3442         ret = 0;
3443 out_wimlib_free:
3444         wimlib_free(wim);
3445 out:
3446         return ret;
3447
3448 out_usage:
3449         usage(CMD_OPTIMIZE, stderr);
3450 out_err:
3451         ret = -1;
3452         goto out;
3453 }
3454
3455 /* Split a WIM into a spanned set */
3456 static int
3457 imagex_split(int argc, tchar **argv, int cmd)
3458 {
3459         int c;
3460         int open_flags = 0;
3461         int write_flags = 0;
3462         unsigned long part_size;
3463         tchar *tmp;
3464         int ret;
3465         WIMStruct *wim;
3466
3467         for_opt(c, split_options) {
3468                 switch (c) {
3469                 case IMAGEX_CHECK_OPTION:
3470                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3471                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3472                         break;
3473                 default:
3474                         goto out_usage;
3475                 }
3476         }
3477         argc -= optind;
3478         argv += optind;
3479
3480         if (argc != 3)
3481                 goto out_usage;
3482
3483         part_size = tstrtod(argv[2], &tmp) * (1 << 20);
3484         if (tmp == argv[2] || *tmp) {
3485                 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
3486                 imagex_error(T("The part size must be an integer or "
3487                                "floating-point number of megabytes."));
3488                 goto out_err;
3489         }
3490         ret = wimlib_open_wim(argv[0], open_flags, &wim, imagex_progress_func);
3491         if (ret)
3492                 goto out;
3493
3494         ret = wimlib_split(wim, argv[1], part_size, write_flags, imagex_progress_func);
3495         wimlib_free(wim);
3496 out:
3497         return ret;
3498
3499 out_usage:
3500         usage(CMD_SPLIT, stderr);
3501 out_err:
3502         ret = -1;
3503         goto out;
3504 }
3505
3506 #if WIM_MOUNTING_SUPPORTED
3507 /* Unmounts a mounted WIM image. */
3508 static int
3509 imagex_unmount(int argc, tchar **argv, int cmd)
3510 {
3511         int c;
3512         int unmount_flags = 0;
3513         int ret;
3514
3515         for_opt(c, unmount_options) {
3516                 switch (c) {
3517                 case IMAGEX_COMMIT_OPTION:
3518                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
3519                         break;
3520                 case IMAGEX_CHECK_OPTION:
3521                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
3522                         break;
3523                 case IMAGEX_REBUILD_OPTION:
3524                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
3525                         break;
3526                 case IMAGEX_LAZY_OPTION:
3527                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_LAZY;
3528                         break;
3529                 default:
3530                         goto out_usage;
3531                 }
3532         }
3533         argc -= optind;
3534         argv += optind;
3535         if (argc != 1)
3536                 goto out_usage;
3537
3538         ret = wimlib_unmount_image(argv[0], unmount_flags,
3539                                    imagex_progress_func);
3540         if (ret)
3541                 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
3542 out:
3543         return ret;
3544
3545 out_usage:
3546         usage(CMD_UNMOUNT, stderr);
3547         ret = -1;
3548         goto out;
3549 }
3550 #endif /* WIM_MOUNTING_SUPPORTED */
3551
3552 /*
3553  * Add, delete, or rename files in a WIM image.
3554  */
3555 static int
3556 imagex_update(int argc, tchar **argv, int cmd)
3557 {
3558         const tchar *wimfile;
3559         int image;
3560         WIMStruct *wim;
3561         int ret;
3562         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3563         int write_flags = 0;
3564         int update_flags = WIMLIB_UPDATE_FLAG_SEND_PROGRESS;
3565         int default_add_flags = WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE |
3566                                 WIMLIB_ADD_FLAG_VERBOSE;
3567         int default_delete_flags = 0;
3568         unsigned num_threads = 0;
3569         int c;
3570         tchar *cmd_file_contents;
3571         size_t cmd_file_nchars;
3572         struct wimlib_update_command *cmds;
3573         size_t num_cmds;
3574         tchar *command_str = NULL;
3575
3576         const tchar *config_file = NULL;
3577         tchar *config_str;
3578         struct wimlib_capture_config *config;
3579
3580         for_opt(c, update_options) {
3581                 switch (c) {
3582                 /* Generic or write options */
3583                 case IMAGEX_THREADS_OPTION:
3584                         num_threads = parse_num_threads(optarg);
3585                         if (num_threads == UINT_MAX)
3586                                 goto out_err;
3587                         break;
3588                 case IMAGEX_CHECK_OPTION:
3589                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3590                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3591                         break;
3592                 case IMAGEX_REBUILD_OPTION:
3593                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
3594                         break;
3595                 case IMAGEX_COMMAND_OPTION:
3596                         if (command_str) {
3597                                 imagex_error(T("--command may only be specified "
3598                                                "one time.  Please provide\n"
3599                                                "       the update commands "
3600                                                "on standard input instead."));
3601                                 goto out_err;
3602                         }
3603                         command_str = tstrdup(optarg);
3604                         if (!command_str) {
3605                                 imagex_error(T("Out of memory!"));
3606                                 goto out_err;
3607                         }
3608                         break;
3609                 /* Default delete options */
3610                 case IMAGEX_FORCE_OPTION:
3611                         default_delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
3612                         break;
3613                 case IMAGEX_RECURSIVE_OPTION:
3614                         default_delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
3615                         break;
3616
3617                 /* Global add option */
3618                 case IMAGEX_CONFIG_OPTION:
3619                         default_add_flags &= ~WIMLIB_ADD_FLAG_WINCONFIG;
3620                         config_file = optarg;
3621                         break;
3622
3623                 /* Default add options */
3624                 case IMAGEX_VERBOSE_OPTION:
3625                         /* No longer does anything.  */
3626                         break;
3627                 case IMAGEX_DEREFERENCE_OPTION:
3628                         default_add_flags |= WIMLIB_ADD_FLAG_DEREFERENCE;
3629                         break;
3630                 case IMAGEX_UNIX_DATA_OPTION:
3631                         default_add_flags |= WIMLIB_ADD_FLAG_UNIX_DATA;
3632                         break;
3633                 case IMAGEX_NO_ACLS_OPTION:
3634                         default_add_flags |= WIMLIB_ADD_FLAG_NO_ACLS;
3635                         break;
3636                 case IMAGEX_STRICT_ACLS_OPTION:
3637                         default_add_flags |= WIMLIB_ADD_FLAG_STRICT_ACLS;
3638                         break;
3639                 default:
3640                         goto out_usage;
3641                 }
3642         }
3643         argv += optind;
3644         argc -= optind;
3645
3646         if (argc != 1 && argc != 2)
3647                 goto out_usage;
3648         wimfile = argv[0];
3649
3650         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3651         if (ret)
3652                 goto out_free_command_str;
3653
3654         if (argc >= 2) {
3655                 /* Image explicitly specified.  */
3656                 image = wimlib_resolve_image(wim, argv[1]);
3657                 ret = verify_image_exists_and_is_single(image, argv[1],
3658                                                         wimfile);
3659                 if (ret)
3660                         goto out_wimlib_free;
3661         } else {
3662                 /* No image specified; default to image 1, but only if the WIM
3663                  * contains exactly one image.  */
3664                 struct wimlib_wim_info info;
3665
3666                 wimlib_get_wim_info(wim, &info);
3667                 if (info.image_count != 1) {
3668                         imagex_error(T("\"%"TS"\" contains %d images; Please select one."),
3669                                      wimfile, info.image_count);
3670                         wimlib_free(wim);
3671                         goto out_usage;
3672                 }
3673                 image = 1;
3674         }
3675
3676         /* Parse capture configuration file if specified */
3677         if (config_file) {
3678                 size_t config_len;
3679
3680                 config_str = file_get_text_contents(config_file, &config_len);
3681                 if (!config_str) {
3682                         ret = -1;
3683                         goto out_wimlib_free;
3684                 }
3685
3686                 config = alloca(sizeof(*config));
3687                 ret = parse_capture_config(&config_str, config_len, config);
3688                 if (ret)
3689                         goto out_free_config;
3690         } else {
3691                 config = NULL;
3692                 default_add_flags |= WIMLIB_ADD_FLAG_WINCONFIG;
3693         }
3694
3695         /* Read update commands from standard input, or the command string if
3696          * specified.  */
3697         if (command_str) {
3698                 cmd_file_contents = NULL;
3699                 cmds = parse_update_command_file(&command_str, tstrlen(command_str),
3700                                                  &num_cmds);
3701         } else {
3702                 if (isatty(STDIN_FILENO)) {
3703                         tputs(T("Reading update commands from standard input..."));
3704                         recommend_man_page(CMD_UPDATE, stdout);
3705                 }
3706                 cmd_file_contents = stdin_get_text_contents(&cmd_file_nchars);
3707                 if (!cmd_file_contents) {
3708                         ret = -1;
3709                         goto out_free_config;
3710                 }
3711
3712                 /* Parse the update commands */
3713                 cmds = parse_update_command_file(&cmd_file_contents, cmd_file_nchars,
3714                                                  &num_cmds);
3715         }
3716         if (!cmds) {
3717                 ret = -1;
3718                 goto out_free_cmd_file_contents;
3719         }
3720
3721         /* Set default flags and capture config on the update commands */
3722         for (size_t i = 0; i < num_cmds; i++) {
3723                 switch (cmds[i].op) {
3724                 case WIMLIB_UPDATE_OP_ADD:
3725                         cmds[i].add.add_flags |= default_add_flags;
3726                         cmds[i].add.config = config;
3727                         break;
3728                 case WIMLIB_UPDATE_OP_DELETE:
3729                         cmds[i].delete_.delete_flags |= default_delete_flags;
3730                         break;
3731                 default:
3732                         break;
3733                 }
3734         }
3735
3736         /* Execute the update commands */
3737         ret = wimlib_update_image(wim, image, cmds, num_cmds, update_flags,
3738                                   imagex_progress_func);
3739         if (ret)
3740                 goto out_free_cmds;
3741
3742         /* Overwrite the updated WIM */
3743         ret = wimlib_overwrite(wim, write_flags, num_threads,
3744                                imagex_progress_func);
3745 out_free_cmds:
3746         free(cmds);
3747 out_free_cmd_file_contents:
3748         free(cmd_file_contents);
3749 out_free_config:
3750         if (config) {
3751                 free(config->exclusion_pats.pats);
3752                 free(config->exclusion_exception_pats.pats);
3753                 free(config_str);
3754         }
3755 out_wimlib_free:
3756         wimlib_free(wim);
3757 out_free_command_str:
3758         free(command_str);
3759         return ret;
3760
3761 out_usage:
3762         usage(CMD_UPDATE, stderr);
3763 out_err:
3764         ret = -1;
3765         goto out_free_command_str;
3766 }
3767
3768
3769
3770 struct imagex_command {
3771         const tchar *name;
3772         int (*func)(int argc, tchar **argv, int cmd);
3773 };
3774
3775 static const struct imagex_command imagex_commands[] = {
3776         [CMD_APPEND]   = {T("append"),   imagex_capture_or_append},
3777         [CMD_APPLY]    = {T("apply"),    imagex_apply},
3778         [CMD_CAPTURE]  = {T("capture"),  imagex_capture_or_append},
3779         [CMD_DELETE]   = {T("delete"),   imagex_delete},
3780         [CMD_DIR ]     = {T("dir"),      imagex_dir},
3781         [CMD_EXPORT]   = {T("export"),   imagex_export},
3782         [CMD_EXTRACT]  = {T("extract"),  imagex_extract},
3783         [CMD_INFO]     = {T("info"),     imagex_info},
3784         [CMD_JOIN]     = {T("join"),     imagex_join},
3785 #if WIM_MOUNTING_SUPPORTED
3786         [CMD_MOUNT]    = {T("mount"),    imagex_mount_rw_or_ro},
3787         [CMD_MOUNTRW]  = {T("mountrw"),  imagex_mount_rw_or_ro},
3788 #endif
3789         [CMD_OPTIMIZE] = {T("optimize"), imagex_optimize},
3790         [CMD_SPLIT]    = {T("split"),    imagex_split},
3791 #if WIM_MOUNTING_SUPPORTED
3792         [CMD_UNMOUNT]  = {T("unmount"),  imagex_unmount},
3793 #endif
3794         [CMD_UPDATE]   = {T("update"),   imagex_update},
3795 };
3796
3797 static const tchar *usage_strings[] = {
3798 [CMD_APPEND] =
3799 T(
3800 "    %"TS" (DIRECTORY | NTFS_VOLUME) WIMFILE\n"
3801 "                    [IMAGE_NAME [IMAGE_DESCRIPTION]] [--boot]\n"
3802 "                    [--check] [--nocheck] [--flags EDITION_ID]\n"
3803 "                    [--dereference] [--config=FILE] [--threads=NUM_THREADS]\n"
3804 "                    [--source-list] [--no-acls] [--strict-acls] [--rpfix]\n"
3805 "                    [--norpfix] [--unix-data] [--pipable]\n"
3806 "                    [--update-of=[WIMFILE:]IMAGE]\n"
3807 ),
3808 [CMD_APPLY] =
3809 T(
3810 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME | all)]\n"
3811 "                    (DIRECTORY | NTFS_VOLUME) [--check] [--hardlink]\n"
3812 "                    [--symlink] [--ref=\"GLOB\"] [--unix-data]\n"
3813 "                    [--no-acls] [--strict-acls] [--rpfix] [--norpfix]\n"
3814 "                    [--include-invalid-names]\n"
3815 ),
3816 [CMD_CAPTURE] =
3817 T(
3818 "    %"TS" (DIRECTORY | NTFS_VOLUME) WIMFILE\n"
3819 "                    [IMAGE_NAME [IMAGE_DESCRIPTION]] [--boot]\n"
3820 "                    [--check] [--nocheck] [--compress=TYPE]\n"
3821 "                    [--flags EDITION_ID] [--dereference]\n"
3822 "                    [--config=FILE] [--threads=NUM_THREADS] [--source-list]\n"
3823 "                    [--no-acls] [--strict-acls] [--rpfix] [--norpfix]\n"
3824 "                    [--unix-data] [--pipable] [--update-of=[WIMFILE:]IMAGE]\n"
3825 "                    [--delta-from=WIMFILE]\n"
3826 ),
3827 [CMD_DELETE] =
3828 T(
3829 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check]\n"
3830 "                    [--soft]\n"
3831 ),
3832 [CMD_DIR] =
3833 T(
3834 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--path=PATH]\n"
3835 ),
3836 [CMD_EXPORT] =
3837 T(
3838 "    %"TS" SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
3839 "                    DEST_WIMFILE [DEST_IMAGE_NAME [DEST_IMAGE_DESCRIPTION]]\n"
3840 "                    [--boot] [--check] [--nocheck] [--compress=TYPE]\n"
3841 "                    [--ref=\"GLOB\"] [--threads=NUM_THREADS] [--rebuild]\n"
3842 "                    [--pipable] [--not-pipable]\n"
3843 ),
3844 [CMD_EXTRACT] =
3845 T(
3846 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME) [PATH...]\n"
3847 "                    [--check] [--ref=\"GLOB\"] [--unix-data]\n"
3848 "                    [--no-acls] [--strict-acls] [--to-stdout]\n"
3849 "                    [--dest-dir=CMD_DIR] [--include-invalid-names]\n"
3850 ),
3851 [CMD_INFO] =
3852 T(
3853 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME) [NEW_NAME\n"
3854 "                    [NEW_DESC]]] [--boot] [--check] [--nocheck] [--header]\n"
3855 "                    [--lookup-table] [--xml] [--extract-xml FILE]\n"
3856 "                    [--metadata]\n"
3857 ),
3858 [CMD_JOIN] =
3859 T(
3860 "    %"TS" OUT_WIMFILE SPLIT_WIM_PART... [--check]\n"
3861 ),
3862 #if WIM_MOUNTING_SUPPORTED
3863 [CMD_MOUNT] =
3864 T(
3865 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME)] DIRECTORY\n"
3866 "                    [--check] [--debug] [--streams-interface=INTERFACE]\n"
3867 "                    [--ref=\"GLOB\"] [--unix-data] [--allow-other]\n"
3868 ),
3869 [CMD_MOUNTRW] =
3870 T(
3871 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME)] DIRECTORY\n"
3872 "                    [--check] [--debug] [--streams-interface=INTERFACE]\n"
3873 "                    [--staging-dir=CMD_DIR] [--unix-data] [--allow-other]\n"
3874 ),
3875 #endif
3876 [CMD_OPTIMIZE] =
3877 T(
3878 "    %"TS" WIMFILE [--check] [--nocheck] [--recompress]\n"
3879 "                    [--recompress-slow] [--compress=TYPE]\n"
3880 "                    [--threads=NUM_THREADS] [--pipable] [--not-pipable]\n"
3881 ),
3882 [CMD_SPLIT] =
3883 T(
3884 "    %"TS" WIMFILE SPLIT_WIM_PART_1 PART_SIZE_MB [--check]\n"
3885 ),
3886 #if WIM_MOUNTING_SUPPORTED
3887 [CMD_UNMOUNT] =
3888 T(
3889 "    %"TS" DIRECTORY [--commit] [--check] [--rebuild] [--lazy]\n"
3890 ),
3891 #endif
3892 [CMD_UPDATE] =
3893 T(
3894 "    %"TS" WIMFILE [IMAGE_NUM | IMAGE_NAME] [--check] [--rebuild]\n"
3895 "                    [--threads=NUM_THREADS] [DEFAULT_ADD_OPTIONS]\n"
3896 "                    [DEFAULT_DELETE_OPTIONS] [--command=STRING] [< CMDFILE]\n"
3897 ),
3898 };
3899
3900 static const tchar *invocation_name;
3901 static int invocation_cmd = CMD_NONE;
3902
3903 static const tchar *get_cmd_string(int cmd, bool nospace)
3904 {
3905         static tchar buf[50];
3906         if (cmd == CMD_NONE) {
3907                 tsprintf(buf, T("%"TS), T(IMAGEX_PROGNAME));
3908         } else if (invocation_cmd != CMD_NONE) {
3909                 tsprintf(buf, T("wim%"TS), imagex_commands[cmd].name);
3910         } else {
3911                 const tchar *format;
3912
3913                 if (nospace)
3914                         format = T("%"TS"-%"TS"");
3915                 else
3916                         format = T("%"TS" %"TS"");
3917                 tsprintf(buf, format, invocation_name, imagex_commands[cmd].name);
3918         }
3919         return buf;
3920 }
3921
3922 static void
3923 version(void)
3924 {
3925         static const tchar *s =
3926         T(
3927 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
3928 "Copyright (C) 2012, 2013 Eric Biggers\n"
3929 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
3930 "This is free software: you are free to change and redistribute it.\n"
3931 "There is NO WARRANTY, to the extent permitted by law.\n"
3932 "\n"
3933 "Report bugs to "PACKAGE_BUGREPORT".\n"
3934         );
3935         tfputs(s, stdout);
3936 }
3937
3938
3939 static void
3940 help_or_version(int argc, tchar **argv, int cmd)
3941 {
3942         int i;
3943         const tchar *p;
3944
3945         for (i = 1; i < argc; i++) {
3946                 p = argv[i];
3947                 if (p[0] == T('-') && p[1] == T('-')) {
3948                         p += 2;
3949                         if (!tstrcmp(p, T("help"))) {
3950                                 if (cmd == CMD_NONE)
3951                                         usage_all(stdout);
3952                                 else
3953                                         usage(cmd, stdout);
3954                                 exit(0);
3955                         } else if (!tstrcmp(p, T("version"))) {
3956                                 version();
3957                                 exit(0);
3958                         }
3959                 }
3960         }
3961 }
3962
3963 static void
3964 print_usage_string(int cmd, FILE *fp)
3965 {
3966         tfprintf(fp, usage_strings[cmd], get_cmd_string(cmd, false));
3967 }
3968
3969 static void
3970 recommend_man_page(int cmd, FILE *fp)
3971 {
3972         const tchar *format_str;
3973 #ifdef __WIN32__
3974         format_str = T("See %"TS".pdf in the doc directory for more details.\n");
3975 #else
3976         format_str = T("Try `man %"TS"' for more details.\n");
3977 #endif
3978         tfprintf(fp, format_str, get_cmd_string(cmd, true));
3979 }
3980
3981 static void
3982 usage(int cmd, FILE *fp)
3983 {
3984         tfprintf(fp, T("Usage:\n"));
3985         print_usage_string(cmd, fp);
3986         tfprintf(fp, T("\n"));
3987         recommend_man_page(cmd, fp);
3988 }
3989
3990 static void
3991 usage_all(FILE *fp)
3992 {
3993         tfprintf(fp, T("Usage:\n"));
3994         for (int cmd = 0; cmd < CMD_MAX; cmd++) {
3995                 print_usage_string(cmd, fp);
3996                 tfprintf(fp, T("\n"));
3997         }
3998         static const tchar *extra =
3999         T(
4000 "    %"TS" --help\n"
4001 "    %"TS" --version\n"
4002 "\n"
4003 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
4004 "\n"
4005         );
4006         tfprintf(fp, extra, invocation_name, invocation_name);
4007         recommend_man_page(CMD_NONE, fp);
4008 }
4009
4010 /* Entry point for wimlib's ImageX implementation.  On UNIX the command
4011  * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
4012  * something else), while an Windows the command arguments will be UTF-16LE
4013  * encoded 'wchar_t' strings. */
4014 int
4015 #ifdef __WIN32__
4016 wmain(int argc, wchar_t **argv, wchar_t **envp)
4017 #else
4018 main(int argc, char **argv)
4019 #endif
4020 {
4021         int ret;
4022         int init_flags = 0;
4023         int cmd;
4024
4025         imagex_info_file = stdout;
4026         invocation_name = tbasename(argv[0]);
4027
4028 #ifndef __WIN32__
4029         if (getenv("WIMLIB_IMAGEX_USE_UTF8")) {
4030                 init_flags |= WIMLIB_INIT_FLAG_ASSUME_UTF8;
4031         } else {
4032                 char *codeset;
4033
4034                 setlocale(LC_ALL, "");
4035                 codeset = nl_langinfo(CODESET);
4036                 if (!strstr(codeset, "UTF-8") &&
4037                     !strstr(codeset, "UTF8") &&
4038                     !strstr(codeset, "utf-8") &&
4039                     !strstr(codeset, "utf8"))
4040                 {
4041                         fprintf(stderr,
4042 "WARNING: Running %"TS" in a UTF-8 locale is recommended!\n"
4043 "         Maybe try: `export LANG=en_US.UTF-8'?\n"
4044 "         Alternatively, set the environmental variable WIMLIB_IMAGEX_USE_UTF8\n"
4045 "         to any value to force wimlib to use UTF-8.\n",
4046                         invocation_name);
4047
4048                 }
4049         }
4050 #endif /* !__WIN32__ */
4051
4052         /* Allow being invoked as wimCOMMAND (e.g. wimapply).  */
4053         cmd = CMD_NONE;
4054         if (!tstrncmp(invocation_name, T("wim"), 3) &&
4055             tstrcmp(invocation_name, T(IMAGEX_PROGNAME))) {
4056                 for (int i = 0; i < CMD_MAX; i++) {
4057                         if (!tstrcmp(invocation_name + 3,
4058                                      imagex_commands[i].name))
4059                         {
4060                                 invocation_cmd = i;
4061                                 cmd = i;
4062                                 break;
4063                         }
4064                 }
4065         }
4066
4067         /* Unless already known from the invocation name, determine which
4068          * command was specified.  */
4069         if (cmd == CMD_NONE) {
4070                 if (argc < 2) {
4071                         imagex_error(T("No command specified!\n"));
4072                         usage_all(stderr);
4073                         exit(2);
4074                 }
4075                 for (int i = 0; i < CMD_MAX; i++) {
4076                         if (!tstrcmp(argv[1], imagex_commands[i].name)) {
4077                                 cmd = i;
4078                                 break;
4079                         }
4080                 }
4081                 if (cmd != CMD_NONE) {
4082                         argc--;
4083                         argv++;
4084                 }
4085         }
4086
4087         /* Handle --help and --version.  --help can be either for the program as
4088          * a whole (cmd == CMD_NONE) or just for a specific command (cmd !=
4089          * CMD_NONE).  Note: help_or_version() will not return if a --help or
4090          * --version argument was found.  */
4091         help_or_version(argc, argv, cmd);
4092
4093         /* Bail if a valid command was not specified.  */
4094         if (cmd == CMD_NONE) {
4095                 imagex_error(T("Unrecognized command: `%"TS"'\n"), argv[1]);
4096                 usage_all(stderr);
4097                 exit(2);
4098         }
4099
4100         /* Enable warning and error messages in wimlib be more user-friendly.
4101          * */
4102         wimlib_set_print_errors(true);
4103
4104         /* Initialize wimlib.  */
4105         ret = wimlib_global_init(init_flags);
4106         if (ret)
4107                 goto out_check_status;
4108
4109         /* Call the command handler function.  */
4110         ret = imagex_commands[cmd].func(argc, argv, cmd);
4111
4112         /* Check for error writing to standard output, especially since for some
4113          * commands, writing to standard output is part of the program's actual
4114          * behavior and not just for informational purposes.  */
4115         if (ferror(stdout) || fclose(stdout)) {
4116                 imagex_error_with_errno(T("error writing to standard output"));
4117                 if (ret == 0)
4118                         ret = -1;
4119         }
4120 out_check_status:
4121         /* Exit status (ret):  -1 indicates an error found by 'wimlib-imagex'
4122          * itself (not by wimlib).  0 indicates success.  > 0 indicates a wimlib
4123          * error code from which an error message can be printed.  */
4124         if (ret > 0) {
4125                 imagex_error(T("Exiting with error code %d:\n"
4126                                "       %"TS"."), ret,
4127                              wimlib_get_error_string(ret));
4128                 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
4129                         imagex_error_with_errno(T("errno"));
4130         }
4131         /* Make wimlib free any resources it's holding (although this is not
4132          * strictly necessary because the process is ending anyway).  */
4133         wimlib_global_cleanup();
4134         return ret;
4135 }