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