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