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