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