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