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