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