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