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