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