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