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