]> wimlib.net Git - wimlib/blob - programs/imagex.c
print_lookup_table(): Print metadata entries
[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 #define GIBIBYTE_MIN_NBYTES 10000000000ULL
1003 #define MEBIBYTE_MIN_NBYTES 10000000ULL
1004 #define KIBIBYTE_MIN_NBYTES 10000ULL
1005
1006 static unsigned
1007 get_unit(uint64_t total_bytes, const tchar **name_ret)
1008 {
1009         if (total_bytes >= GIBIBYTE_MIN_NBYTES) {
1010                 *name_ret = T("GiB");
1011                 return 30;
1012         } else if (total_bytes >= MEBIBYTE_MIN_NBYTES) {
1013                 *name_ret = T("MiB");
1014                 return 20;
1015         } else if (total_bytes >= KIBIBYTE_MIN_NBYTES) {
1016                 *name_ret = T("KiB");
1017                 return 10;
1018         } else {
1019                 *name_ret = T("bytes");
1020                 return 0;
1021         }
1022 }
1023
1024 /* Progress callback function passed to various wimlib functions. */
1025 static int
1026 imagex_progress_func(enum wimlib_progress_msg msg,
1027                      const union wimlib_progress_info *info)
1028 {
1029         unsigned percent_done;
1030         unsigned unit_shift;
1031         const tchar *unit_name;
1032         if (imagex_be_quiet)
1033                 return 0;
1034         switch (msg) {
1035         case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
1036                 unit_shift = get_unit(info->write_streams.total_bytes, &unit_name);
1037                 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
1038                                           info->write_streams.total_bytes);
1039                 if (info->write_streams.completed_streams == 0) {
1040                         const tchar *data_type;
1041
1042                         data_type = get_data_type(info->write_streams.compression_type);
1043                         tprintf(T("Writing %"TS" data using %u thread%"TS"\n"),
1044                                 data_type, info->write_streams.num_threads,
1045                                 (info->write_streams.num_threads == 1) ? T("") : T("s"));
1046                 }
1047                 tprintf(T("\r%"PRIu64" %"TS" of %"PRIu64" %"TS" (uncompressed) "
1048                         "written (%u%% done)"),
1049                         info->write_streams.completed_bytes >> unit_shift,
1050                         unit_name,
1051                         info->write_streams.total_bytes >> unit_shift,
1052                         unit_name,
1053                         percent_done);
1054                 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
1055                         tputchar(T('\n'));
1056                 break;
1057         case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
1058                 tprintf(T("Scanning \"%"TS"\""), info->scan.source);
1059                 if (*info->scan.wim_target_path) {
1060                         tprintf(T(" (loading as WIM path: \"/%"TS"\")...\n"),
1061                                info->scan.wim_target_path);
1062                 } else {
1063                         tprintf(T(" (loading as root of WIM image)...\n"));
1064                 }
1065                 break;
1066         case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
1067                 if (info->scan.excluded)
1068                         tprintf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
1069                 else
1070                         tprintf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
1071                 break;
1072         /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
1073                 /*break;*/
1074         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
1075                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1076                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1077                                           info->integrity.total_bytes);
1078                 tprintf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" "TS" "
1079                         "of %"PRIu64" "TS" (%u%%) done"),
1080                         info->integrity.filename,
1081                         info->integrity.completed_bytes >> unit_shift,
1082                         unit_name,
1083                         info->integrity.total_bytes >> unit_shift,
1084                         unit_name,
1085                         percent_done);
1086                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1087                         tputchar(T('\n'));
1088                 break;
1089         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
1090                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1091                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1092                                           info->integrity.total_bytes);
1093                 tprintf(T("\rCalculating integrity table for WIM: %"PRIu64" %"TS" "
1094                           "of %"PRIu64" %"TS" (%u%%) done"),
1095                         info->integrity.completed_bytes >> unit_shift,
1096                         unit_name,
1097                         info->integrity.total_bytes >> unit_shift,
1098                         unit_name,
1099                         percent_done);
1100                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1101                         tputchar(T('\n'));
1102                 break;
1103         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
1104                 tprintf(T("Applying image %d (\"%"TS"\") from \"%"TS"\" "
1105                           "to %"TS" \"%"TS"\"\n"),
1106                         info->extract.image,
1107                         info->extract.image_name,
1108                         info->extract.wimfile_name,
1109                         ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
1110                          T("NTFS volume") : T("directory")),
1111                         info->extract.target);
1112                 break;
1113         case WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN:
1114                 tprintf(T("Extracting \"%"TS"\" from image %d (\"%"TS"\") "
1115                           "in \"%"TS"\" to \"%"TS"\"\n"),
1116                         info->extract.extract_root_wim_source_path,
1117                         info->extract.image,
1118                         info->extract.image_name,
1119                         info->extract.wimfile_name,
1120                         info->extract.target);
1121                 break;
1122         /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
1123                 /*tprintf(T("Applying directory structure to %"TS"\n"),*/
1124                         /*info->extract.target);*/
1125                 /*break;*/
1126         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1127                 percent_done = TO_PERCENT(info->extract.completed_bytes,
1128                                           info->extract.total_bytes);
1129                 unit_shift = get_unit(info->extract.total_bytes, &unit_name);
1130                 tprintf(T("\rExtracting files: "
1131                           "%"PRIu64" %"TS" of %"PRIu64" %"TS" (%u%%) done"),
1132                         info->extract.completed_bytes >> unit_shift,
1133                         unit_name,
1134                         info->extract.total_bytes >> unit_shift,
1135                         unit_name,
1136                         percent_done);
1137                 if (info->extract.completed_bytes >= info->extract.total_bytes)
1138                         tputchar(T('\n'));
1139                 break;
1140         case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
1141                 tprintf(T("%"TS"\n"), info->extract.cur_path);
1142                 break;
1143         case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1144                 if (info->extract.extract_root_wim_source_path[0] == T('\0'))
1145                         tprintf(T("Setting timestamps on all extracted files...\n"));
1146                 break;
1147         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1148                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1149                         tprintf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1150                                 info->extract.target);
1151                 }
1152                 break;
1153         case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
1154                 percent_done = TO_PERCENT(info->join.completed_bytes,
1155                                           info->join.total_bytes);
1156                 unit_shift = get_unit(info->join.total_bytes, &unit_name);
1157                 tprintf(T("Writing resources from part %u of %u: "
1158                           "%"PRIu64 " %"TS" of %"PRIu64" %"TS" (%u%%) written\n"),
1159                         (info->join.completed_parts == info->join.total_parts) ?
1160                         info->join.completed_parts : info->join.completed_parts + 1,
1161                         info->join.total_parts,
1162                         info->join.completed_bytes >> unit_shift,
1163                         unit_name,
1164                         info->join.total_bytes >> unit_shift,
1165                         unit_name,
1166                         percent_done);
1167                 break;
1168         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1169                 percent_done = TO_PERCENT(info->split.completed_bytes,
1170                                           info->split.total_bytes);
1171                 unit_shift = get_unit(info->split.total_bytes, &unit_name);
1172                 tprintf(T("Writing \"%"TS"\": %"PRIu64" %"TS" of "
1173                           "%"PRIu64" %"TS" (%u%%) written\n"),
1174                         info->split.part_name,
1175                         info->split.completed_bytes >> unit_shift,
1176                         unit_name,
1177                         info->split.total_bytes >> unit_shift,
1178                         unit_name,
1179                         percent_done);
1180                 break;
1181         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1182                 if (info->split.completed_bytes == info->split.total_bytes) {
1183                         tprintf(T("Finished writing %u split WIM parts\n"),
1184                                 info->split.cur_part_number);
1185                 }
1186                 break;
1187         default:
1188                 break;
1189         }
1190         fflush(stdout);
1191         return 0;
1192 }
1193
1194 /* Open all the split WIM parts that correspond to a file glob.
1195  *
1196  * @first_part specifies the first part of the split WIM and it may be either
1197  * included or omitted from the glob. */
1198 static int
1199 open_swms_from_glob(const tchar *swm_glob,
1200                     const tchar *first_part,
1201                     int open_flags,
1202                     WIMStruct ***additional_swms_ret,
1203                     unsigned *num_additional_swms_ret)
1204 {
1205         unsigned num_additional_swms = 0;
1206         WIMStruct **additional_swms = NULL;
1207         glob_t globbuf;
1208         int ret;
1209
1210         /* Warning: glob() is replaced in Windows native builds */
1211         ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1212         if (ret != 0) {
1213                 if (ret == GLOB_NOMATCH) {
1214                         imagex_error(T("Found no files for glob \"%"TS"\""),
1215                                      swm_glob);
1216                 } else {
1217                         imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
1218                                                 swm_glob);
1219                 }
1220                 ret = -1;
1221                 goto out;
1222         }
1223         num_additional_swms = globbuf.gl_pathc;
1224         additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
1225         if (!additional_swms) {
1226                 imagex_error(T("Out of memory"));
1227                 ret = -1;
1228                 goto out_globfree;
1229         }
1230         unsigned offset = 0;
1231         for (unsigned i = 0; i < num_additional_swms; i++) {
1232                 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
1233                         offset++;
1234                         continue;
1235                 }
1236                 ret = wimlib_open_wim(globbuf.gl_pathv[i],
1237                                       open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
1238                                       &additional_swms[i - offset],
1239                                       imagex_progress_func);
1240                 if (ret != 0)
1241                         goto out_close_swms;
1242         }
1243         *additional_swms_ret = additional_swms;
1244         *num_additional_swms_ret = num_additional_swms - offset;
1245         ret = 0;
1246         goto out_globfree;
1247 out_close_swms:
1248         for (unsigned i = 0; i < num_additional_swms; i++)
1249                 wimlib_free(additional_swms[i]);
1250         free(additional_swms);
1251 out_globfree:
1252         globfree(&globbuf);
1253 out:
1254         return ret;
1255 }
1256
1257
1258 static unsigned
1259 parse_num_threads(const tchar *optarg)
1260 {
1261         tchar *tmp;
1262         unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1263         if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1264                 imagex_error(T("Number of threads must be a non-negative integer!"));
1265                 return UINT_MAX;
1266         } else {
1267                 return ul_nthreads;
1268         }
1269 }
1270
1271 /*
1272  * Parse an option passed to an update command.
1273  *
1274  * @op:         One of WIMLIB_UPDATE_OP_* that indicates the command being
1275  *              parsed.
1276  *
1277  * @option:     Text string for the option (beginning with --)
1278  *
1279  * @cmd:        `struct wimlib_update_command' that is being constructed for
1280  *              this command.
1281  *
1282  * Returns true if the option was recognized; false if not.
1283  */
1284 static bool
1285 update_command_add_option(int op, const tchar *option,
1286                           struct wimlib_update_command *cmd)
1287 {
1288         bool recognized = true;
1289         switch (op) {
1290         case WIMLIB_UPDATE_OP_ADD:
1291                 if (!tstrcmp(option, T("--verbose")))
1292                         cmd->add.add_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1293                 else if (!tstrcmp(option, T("--unix-data")))
1294                         cmd->add.add_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1295                 else if (!tstrcmp(option, T("--no-acls")) || !tstrcmp(option, T("--noacls")))
1296                         cmd->add.add_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1297                 else if (!tstrcmp(option, T("--strict-acls")))
1298                         cmd->add.add_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1299                 else if (!tstrcmp(option, T("--dereference")))
1300                         cmd->add.add_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1301                 else
1302                         recognized = false;
1303                 break;
1304         case WIMLIB_UPDATE_OP_DELETE:
1305                 if (!tstrcmp(option, T("--force")))
1306                         cmd->delete.delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
1307                 else if (!tstrcmp(option, T("--recursive")))
1308                         cmd->delete.delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
1309                 else
1310                         recognized = false;
1311                 break;
1312         default:
1313                 recognized = false;
1314                 break;
1315         }
1316         return recognized;
1317 }
1318
1319 /* How many nonoption arguments each `imagex update' command expects */
1320 static const unsigned update_command_num_nonoptions[] = {
1321         [WIMLIB_UPDATE_OP_ADD] = 2,
1322         [WIMLIB_UPDATE_OP_DELETE] = 1,
1323         [WIMLIB_UPDATE_OP_RENAME] = 2,
1324 };
1325
1326 static void
1327 update_command_add_nonoption(int op, const tchar *nonoption,
1328                              struct wimlib_update_command *cmd,
1329                              unsigned num_nonoptions)
1330 {
1331         switch (op) {
1332         case WIMLIB_UPDATE_OP_ADD:
1333                 if (num_nonoptions == 0)
1334                         cmd->add.fs_source_path = (tchar*)nonoption;
1335                 else
1336                         cmd->add.wim_target_path = (tchar*)nonoption;
1337                 break;
1338         case WIMLIB_UPDATE_OP_DELETE:
1339                 cmd->delete.wim_path = (tchar*)nonoption;
1340                 break;
1341         case WIMLIB_UPDATE_OP_RENAME:
1342                 if (num_nonoptions == 0)
1343                         cmd->rename.wim_source_path = (tchar*)nonoption;
1344                 else
1345                         cmd->rename.wim_target_path = (tchar*)nonoption;
1346                 break;
1347         }
1348 }
1349
1350 /*
1351  * Parse a command passed on stdin to `imagex update'.
1352  *
1353  * @line:       Text of the command.
1354  * @len:        Length of the line, including a null terminator
1355  *              at line[len - 1].
1356  *
1357  * @command:    A `struct wimlib_update_command' to fill in from the parsed
1358  *              line.
1359  *
1360  * @line_number: Line number of the command, for diagnostics.
1361  *
1362  * Returns true on success; returns false on parse error.
1363  */
1364 static bool
1365 parse_update_command(tchar *line, size_t len,
1366                      struct wimlib_update_command *command,
1367                      size_t line_number)
1368 {
1369         int ret;
1370         tchar *command_name;
1371         int op;
1372         size_t num_nonoptions;
1373
1374         /* Get the command name ("add", "delete", "rename") */
1375         ret = parse_string(&line, &len, &command_name);
1376         if (ret != PARSE_STRING_SUCCESS)
1377                 return false;
1378
1379         if (!tstrcasecmp(command_name, T("add"))) {
1380                 op = WIMLIB_UPDATE_OP_ADD;
1381         } else if (!tstrcasecmp(command_name, T("delete"))) {
1382                 op = WIMLIB_UPDATE_OP_DELETE;
1383         } else if (!tstrcasecmp(command_name, T("rename"))) {
1384                 op = WIMLIB_UPDATE_OP_RENAME;
1385         } else {
1386                 imagex_error(T("Unknown update command \"%"TS"\" on line %zu"),
1387                              command_name, line_number);
1388                 return false;
1389         }
1390         command->op = op;
1391
1392         /* Parse additional options and non-options as needed */
1393         num_nonoptions = 0;
1394         for (;;) {
1395                 tchar *next_string;
1396
1397                 ret = parse_string(&line, &len, &next_string);
1398                 if (ret == PARSE_STRING_NONE) /* End of line */
1399                         break;
1400                 else if (ret != PARSE_STRING_SUCCESS) /* Parse failure */
1401                         return false;
1402                 if (next_string[0] == T('-') && next_string[1] == T('-')) {
1403                         /* Option */
1404                         if (!update_command_add_option(op, next_string, command))
1405                         {
1406                                 imagex_error(T("Unrecognized option \"%"TS"\" to "
1407                                                "update command \"%"TS"\" on line %zu"),
1408                                              next_string, command_name, line_number);
1409
1410                                 return false;
1411                         }
1412                 } else {
1413                         /* Nonoption */
1414                         if (num_nonoptions == update_command_num_nonoptions[op])
1415                         {
1416                                 imagex_error(T("Unexpected argument \"%"TS"\" in "
1417                                                "update command on line %zu\n"
1418                                                "       (The \"%"TS"\" command only "
1419                                                "takes %u nonoption arguments!)\n"),
1420                                              next_string, line_number,
1421                                              command_name, num_nonoptions);
1422                                 return false;
1423                         }
1424                         update_command_add_nonoption(op, next_string,
1425                                                      command, num_nonoptions);
1426                         num_nonoptions++;
1427                 }
1428         }
1429
1430         if (num_nonoptions != update_command_num_nonoptions[op]) {
1431                 imagex_error(T("Not enough arguments to update command "
1432                                "\"%"TS"\" on line %zu"), command_name, line_number);
1433                 return false;
1434         }
1435         return true;
1436 }
1437
1438 static struct wimlib_update_command *
1439 parse_update_command_file(tchar **cmd_file_contents_p, size_t cmd_file_nchars,
1440                           size_t *num_cmds_ret)
1441 {
1442         ssize_t nlines;
1443         tchar *p;
1444         struct wimlib_update_command *cmds;
1445         size_t i, j;
1446
1447         nlines = text_file_count_lines(cmd_file_contents_p,
1448                                        &cmd_file_nchars);
1449         if (nlines < 0)
1450                 return NULL;
1451
1452         /* Always allocate at least 1 slot, just in case the implementation of
1453          * calloc() returns NULL if 0 bytes are requested. */
1454         cmds = calloc(nlines ?: 1, sizeof(struct wimlib_update_command));
1455         if (!cmds) {
1456                 imagex_error(T("out of memory"));
1457                 return NULL;
1458         }
1459         p = *cmd_file_contents_p;
1460         j = 0;
1461         for (i = 0; i < nlines; i++) {
1462                 /* XXX: Could use rawmemchr() here instead, but it may not be
1463                  * available on all platforms. */
1464                 tchar *endp = tmemchr(p, T('\n'), cmd_file_nchars);
1465                 size_t len = endp - p + 1;
1466                 *endp = T('\0');
1467                 if (!is_comment_line(p, len)) {
1468                         if (!parse_update_command(p, len, &cmds[j++], i + 1)) {
1469                                 free(cmds);
1470                                 return NULL;
1471                         }
1472                 }
1473                 p = endp + 1;
1474         }
1475         *num_cmds_ret = j;
1476         return cmds;
1477 }
1478
1479 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1480  * one image from a WIM file to a NTFS volume. */
1481 static int
1482 imagex_apply(int argc, tchar **argv)
1483 {
1484         int c;
1485         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1486         int image;
1487         int num_images;
1488         WIMStruct *w;
1489         int ret;
1490         const tchar *wimfile;
1491         const tchar *target;
1492         const tchar *image_num_or_name;
1493         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1494
1495         const tchar *swm_glob = NULL;
1496         WIMStruct **additional_swms = NULL;
1497         unsigned num_additional_swms = 0;
1498
1499         for_opt(c, apply_options) {
1500                 switch (c) {
1501                 case IMAGEX_CHECK_OPTION:
1502                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1503                         break;
1504                 case IMAGEX_HARDLINK_OPTION:
1505                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1506                         break;
1507                 case IMAGEX_SYMLINK_OPTION:
1508                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1509                         break;
1510                 case IMAGEX_VERBOSE_OPTION:
1511                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1512                         break;
1513                 case IMAGEX_REF_OPTION:
1514                         swm_glob = optarg;
1515                         break;
1516                 case IMAGEX_UNIX_DATA_OPTION:
1517                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1518                         break;
1519                 case IMAGEX_NO_ACLS_OPTION:
1520                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1521                         break;
1522                 case IMAGEX_STRICT_ACLS_OPTION:
1523                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1524                         break;
1525                 case IMAGEX_NORPFIX_OPTION:
1526                         extract_flags |= WIMLIB_EXTRACT_FLAG_NORPFIX;
1527                         break;
1528                 case IMAGEX_RPFIX_OPTION:
1529                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1530                         break;
1531                 default:
1532                         usage(APPLY);
1533                         return -1;
1534                 }
1535         }
1536         argc -= optind;
1537         argv += optind;
1538         if (argc != 2 && argc != 3) {
1539                 usage(APPLY);
1540                 return -1;
1541         }
1542
1543         wimfile = argv[0];
1544         if (argc == 2) {
1545                 image_num_or_name = T("1");
1546                 target = argv[1];
1547         } else {
1548                 image_num_or_name = argv[1];
1549                 target = argv[2];
1550         }
1551
1552         ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
1553         if (ret != 0)
1554                 return ret;
1555
1556         image = wimlib_resolve_image(w, image_num_or_name);
1557         ret = verify_image_exists(image, image_num_or_name, wimfile);
1558         if (ret != 0)
1559                 goto out;
1560
1561         num_images = wimlib_get_num_images(w);
1562         if (argc == 2 && num_images != 1) {
1563                 imagex_error(T("\"%"TS"\" contains %d images; Please select one "
1564                                "(or all)."), wimfile, num_images);
1565                 usage(APPLY);
1566                 ret = -1;
1567                 goto out;
1568         }
1569
1570         if (swm_glob) {
1571                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1572                                           &additional_swms,
1573                                           &num_additional_swms);
1574                 if (ret != 0)
1575                         goto out;
1576         }
1577
1578         struct stat stbuf;
1579
1580         ret = tstat(target, &stbuf);
1581         if (ret == 0) {
1582                 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1583                         extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1584         } else {
1585                 if (errno != ENOENT) {
1586                         imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1587                                                 target);
1588                         ret = -1;
1589                         goto out;
1590                 }
1591         }
1592
1593 #ifdef __WIN32__
1594         win32_acquire_restore_privileges();
1595 #endif
1596         ret = wimlib_extract_image(w, image, target, extract_flags,
1597                                    additional_swms, num_additional_swms,
1598                                    imagex_progress_func);
1599         if (ret == 0)
1600                 tprintf(T("Done applying WIM image.\n"));
1601 #ifdef __WIN32__
1602         win32_release_restore_privileges();
1603 #endif
1604 out:
1605         wimlib_free(w);
1606         if (additional_swms) {
1607                 for (unsigned i = 0; i < num_additional_swms; i++)
1608                         wimlib_free(additional_swms[i]);
1609                 free(additional_swms);
1610         }
1611         return ret;
1612 }
1613
1614 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1615  * directory trees.  'wimlib-imagex capture': create a new WIM file containing
1616  * the desired image.  'wimlib-imagex append': add a new image to an existing
1617  * WIM file. */
1618 static int
1619 imagex_capture_or_append(int argc, tchar **argv)
1620 {
1621         int c;
1622         int open_flags = 0;
1623         int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
1624         int write_flags = 0;
1625         int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
1626         const tchar *wimfile;
1627         const tchar *name;
1628         const tchar *desc;
1629         const tchar *flags_element = NULL;
1630         WIMStruct *w;
1631         int ret;
1632         int cur_image;
1633         int cmd = tstrcmp(argv[0], T("append")) ? CAPTURE : APPEND;
1634         unsigned num_threads = 0;
1635
1636         tchar *source;
1637         size_t source_name_len;
1638         tchar *source_copy;
1639
1640         const tchar *config_file = NULL;
1641         tchar *config_str;
1642         struct wimlib_capture_config *config = NULL;
1643
1644         bool source_list = false;
1645         size_t source_list_nchars;
1646         tchar *source_list_contents;
1647         bool capture_sources_malloced;
1648         struct wimlib_capture_source *capture_sources;
1649         size_t num_sources;
1650
1651         for_opt(c, capture_or_append_options) {
1652                 switch (c) {
1653                 case IMAGEX_BOOT_OPTION:
1654                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1655                         break;
1656                 case IMAGEX_CHECK_OPTION:
1657                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1658                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1659                         break;
1660                 case IMAGEX_CONFIG_OPTION:
1661                         config_file = optarg;
1662                         break;
1663                 case IMAGEX_COMPRESS_OPTION:
1664                         compression_type = get_compression_type(optarg);
1665                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1666                                 return -1;
1667                         break;
1668                 case IMAGEX_FLAGS_OPTION:
1669                         flags_element = optarg;
1670                         break;
1671                 case IMAGEX_DEREFERENCE_OPTION:
1672                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1673                         break;
1674                 case IMAGEX_VERBOSE_OPTION:
1675                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1676                         break;
1677                 case IMAGEX_THREADS_OPTION:
1678                         num_threads = parse_num_threads(optarg);
1679                         if (num_threads == UINT_MAX)
1680                                 return -1;
1681                         break;
1682                 case IMAGEX_REBUILD_OPTION:
1683                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1684                         break;
1685                 case IMAGEX_UNIX_DATA_OPTION:
1686                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1687                         break;
1688                 case IMAGEX_SOURCE_LIST_OPTION:
1689                         source_list = true;
1690                         break;
1691                 case IMAGEX_NO_ACLS_OPTION:
1692                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1693                         break;
1694                 case IMAGEX_STRICT_ACLS_OPTION:
1695                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1696                         break;
1697                 case IMAGEX_RPFIX_OPTION:
1698                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
1699                         break;
1700                 case IMAGEX_NORPFIX_OPTION:
1701                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NORPFIX;
1702                         break;
1703                 default:
1704                         usage(cmd);
1705                         return -1;
1706                 }
1707         }
1708         argc -= optind;
1709         argv += optind;
1710
1711         if (argc < 2 || argc > 4) {
1712                 usage(cmd);
1713                 return -1;
1714         }
1715
1716         source = argv[0];
1717         wimfile = argv[1];
1718
1719         if (argc >= 3) {
1720                 name = argv[2];
1721         } else {
1722                 /* Set default name to SOURCE argument, omitting any directory
1723                  * prefixes and trailing slashes.  This requires making a copy
1724                  * of @source. */
1725                 source_name_len = tstrlen(source);
1726                 source_copy = alloca((source_name_len + 1) * sizeof(tchar));
1727                 name = tbasename(tstrcpy(source_copy, source));
1728         }
1729         /* Image description defaults to NULL if not given. */
1730         desc = (argc >= 4) ? argv[3] : NULL;
1731
1732         if (source_list) {
1733                 /* Set up capture sources in source list mode */
1734                 if (source[0] == T('-') && source[1] == T('\0')) {
1735                         source_list_contents = stdin_get_text_contents(&source_list_nchars);
1736                 } else {
1737                         source_list_contents = file_get_text_contents(source,
1738                                                                       &source_list_nchars);
1739                 }
1740                 if (!source_list_contents)
1741                         return -1;
1742
1743                 capture_sources = parse_source_list(&source_list_contents,
1744                                                     source_list_nchars,
1745                                                     &num_sources);
1746                 if (!capture_sources) {
1747                         ret = -1;
1748                         goto out_free_source_list_contents;
1749                 }
1750                 capture_sources_malloced = true;
1751         } else {
1752                 /* Set up capture source in non-source-list mode (could be
1753                  * either "normal" mode or "NTFS mode"--- see the man page). */
1754                 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1755                 capture_sources[0].fs_source_path = source;
1756                 capture_sources[0].wim_target_path = NULL;
1757                 capture_sources[0].reserved = 0;
1758                 num_sources = 1;
1759                 capture_sources_malloced = false;
1760                 source_list_contents = NULL;
1761         }
1762
1763         if (config_file) {
1764                 size_t config_len;
1765
1766                 config_str = file_get_text_contents(config_file, &config_len);
1767                 if (!config_str) {
1768                         ret = -1;
1769                         goto out_free_capture_sources;
1770                 }
1771
1772                 config = alloca(sizeof(*config));
1773                 ret = parse_capture_config(&config_str, config_len, config);
1774                 if (ret)
1775                         goto out_free_config;
1776         } else {
1777                 config = &default_capture_config;
1778         }
1779
1780         if (cmd == APPEND)
1781                 ret = wimlib_open_wim(wimfile, open_flags, &w,
1782                                       imagex_progress_func);
1783         else
1784                 ret = wimlib_create_new_wim(compression_type, &w);
1785         if (ret)
1786                 goto out_free_config;
1787
1788         if (!source_list) {
1789                 struct stat stbuf;
1790                 ret = tstat(source, &stbuf);
1791                 if (ret == 0) {
1792                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1793                                 tprintf(T("Capturing WIM image from NTFS "
1794                                           "filesystem on \"%"TS"\"\n"), source);
1795                                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1796                         }
1797                 } else {
1798                         if (errno != ENOENT) {
1799                                 imagex_error_with_errno(T("Failed to stat "
1800                                                           "\"%"TS"\""), source);
1801                                 ret = -1;
1802                                 goto out_wimlib_free;
1803                         }
1804                 }
1805         }
1806 #ifdef __WIN32__
1807         win32_acquire_capture_privileges();
1808 #endif
1809
1810         ret = wimlib_add_image_multisource(w,
1811                                            capture_sources,
1812                                            num_sources,
1813                                            name,
1814                                            config,
1815                                            add_image_flags,
1816                                            imagex_progress_func);
1817         if (ret != 0)
1818                 goto out_release_privs;
1819         cur_image = wimlib_get_num_images(w);
1820         if (desc) {
1821                 ret = wimlib_set_image_descripton(w, cur_image, desc);
1822                 if (ret != 0)
1823                         goto out_release_privs;
1824         }
1825         if (flags_element) {
1826                 ret = wimlib_set_image_flags(w, cur_image, flags_element);
1827                 if (ret != 0)
1828                         goto out_release_privs;
1829         }
1830         if (cmd == APPEND) {
1831                 ret = wimlib_overwrite(w, write_flags, num_threads,
1832                                        imagex_progress_func);
1833         } else {
1834                 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
1835                                    num_threads, imagex_progress_func);
1836         }
1837         if (ret == WIMLIB_ERR_REOPEN)
1838                 ret = 0;
1839         if (ret != 0)
1840                 imagex_error(T("Failed to write the WIM file \"%"TS"\""),
1841                              wimfile);
1842 out_release_privs:
1843 #ifdef __WIN32__
1844         win32_release_capture_privileges();
1845 #endif
1846 out_wimlib_free:
1847         wimlib_free(w);
1848 out_free_config:
1849         if (config != NULL && config != &default_capture_config) {
1850                 free(config->exclusion_pats.pats);
1851                 free(config->exclusion_exception_pats.pats);
1852                 free(config_str);
1853         }
1854 out_free_capture_sources:
1855         if (capture_sources_malloced)
1856                 free(capture_sources);
1857 out_free_source_list_contents:
1858         free(source_list_contents);
1859         return ret;
1860 }
1861
1862 /* Remove image(s) from a WIM. */
1863 static int
1864 imagex_delete(int argc, tchar **argv)
1865 {
1866         int c;
1867         int open_flags = 0;
1868         int write_flags = 0;
1869         const tchar *wimfile;
1870         const tchar *image_num_or_name;
1871         WIMStruct *w;
1872         int image;
1873         int ret;
1874
1875         for_opt(c, delete_options) {
1876                 switch (c) {
1877                 case IMAGEX_CHECK_OPTION:
1878                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1879                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1880                         break;
1881                 case IMAGEX_SOFT_OPTION:
1882                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1883                         break;
1884                 default:
1885                         usage(DELETE);
1886                         return -1;
1887                 }
1888         }
1889         argc -= optind;
1890         argv += optind;
1891
1892         if (argc != 2) {
1893                 if (argc < 1)
1894                         imagex_error(T("Must specify a WIM file"));
1895                 if (argc < 2)
1896                         imagex_error(T("Must specify an image"));
1897                 usage(DELETE);
1898                 return -1;
1899         }
1900         wimfile = argv[0];
1901         image_num_or_name = argv[1];
1902
1903         ret = file_writable(wimfile);
1904         if (ret != 0)
1905                 return ret;
1906
1907         ret = wimlib_open_wim(wimfile, open_flags, &w,
1908                               imagex_progress_func);
1909         if (ret != 0)
1910                 return ret;
1911
1912         image = wimlib_resolve_image(w, image_num_or_name);
1913
1914         ret = verify_image_exists(image, image_num_or_name, wimfile);
1915         if (ret != 0)
1916                 goto out;
1917
1918         ret = wimlib_delete_image(w, image);
1919         if (ret != 0) {
1920                 imagex_error(T("Failed to delete image from \"%"TS"\""), wimfile);
1921                 goto out;
1922         }
1923
1924         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1925         if (ret == WIMLIB_ERR_REOPEN)
1926                 ret = 0;
1927         if (ret != 0) {
1928                 imagex_error(T("Failed to write the file \"%"TS"\" with image "
1929                                "deleted"), wimfile);
1930         }
1931 out:
1932         wimlib_free(w);
1933         return ret;
1934 }
1935
1936 /* Print the files contained in an image(s) in a WIM file. */
1937 static int
1938 imagex_dir(int argc, tchar **argv)
1939 {
1940         const tchar *wimfile;
1941         WIMStruct *w;
1942         int image;
1943         int ret;
1944         int num_images;
1945
1946         if (argc < 2) {
1947                 imagex_error(T("Must specify a WIM file"));
1948                 usage(DIR);
1949                 return -1;
1950         }
1951         if (argc > 3) {
1952                 imagex_error(T("Too many arguments"));
1953                 usage(DIR);
1954                 return -1;
1955         }
1956
1957         wimfile = argv[1];
1958         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
1959                               imagex_progress_func);
1960         if (ret != 0)
1961                 return ret;
1962
1963         if (argc == 3) {
1964                 image = wimlib_resolve_image(w, argv[2]);
1965                 ret = verify_image_exists(image, argv[2], wimfile);
1966                 if (ret != 0)
1967                         goto out;
1968         } else {
1969                 /* Image was not specified.  If the WIM only contains one image,
1970                  * choose that one; otherwise, print an error. */
1971                 num_images = wimlib_get_num_images(w);
1972                 if (num_images != 1) {
1973                         imagex_error(T("\"%"TS"\" contains %d images; Please "
1974                                        "select one."), wimfile, num_images);
1975                         usage(DIR);
1976                         ret = -1;
1977                         goto out;
1978                 }
1979                 image = 1;
1980         }
1981
1982         ret = wimlib_print_files(w, image);
1983 out:
1984         wimlib_free(w);
1985         return ret;
1986 }
1987
1988 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
1989  * WIM file. */
1990 static int
1991 imagex_export(int argc, tchar **argv)
1992 {
1993         int c;
1994         int open_flags = 0;
1995         int export_flags = 0;
1996         int write_flags = 0;
1997         int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1998         bool compression_type_specified = false;
1999         const tchar *src_wimfile;
2000         const tchar *src_image_num_or_name;
2001         const tchar *dest_wimfile;
2002         const tchar *dest_name;
2003         const tchar *dest_desc;
2004         WIMStruct *src_w = NULL;
2005         WIMStruct *dest_w = NULL;
2006         int ret;
2007         int image;
2008         struct stat stbuf;
2009         bool wim_is_new;
2010         const tchar *swm_glob = NULL;
2011         WIMStruct **additional_swms = NULL;
2012         unsigned num_additional_swms = 0;
2013         unsigned num_threads = 0;
2014
2015         for_opt(c, export_options) {
2016                 switch (c) {
2017                 case IMAGEX_BOOT_OPTION:
2018                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
2019                         break;
2020                 case IMAGEX_CHECK_OPTION:
2021                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2022                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2023                         break;
2024                 case IMAGEX_COMPRESS_OPTION:
2025                         compression_type = get_compression_type(optarg);
2026                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
2027                                 return -1;
2028                         compression_type_specified = true;
2029                         break;
2030                 case IMAGEX_REF_OPTION:
2031                         swm_glob = optarg;
2032                         break;
2033                 case IMAGEX_THREADS_OPTION:
2034                         num_threads = parse_num_threads(optarg);
2035                         if (num_threads == UINT_MAX)
2036                                 return -1;
2037                         break;
2038                 case IMAGEX_REBUILD_OPTION:
2039                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
2040                         break;
2041                 default:
2042                         usage(EXPORT);
2043                         return -1;
2044                 }
2045         }
2046         argc -= optind;
2047         argv += optind;
2048         if (argc < 3 || argc > 5) {
2049                 usage(EXPORT);
2050                 return -1;
2051         }
2052         src_wimfile           = argv[0];
2053         src_image_num_or_name = argv[1];
2054         dest_wimfile          = argv[2];
2055         dest_name             = (argc >= 4) ? argv[3] : NULL;
2056         dest_desc             = (argc >= 5) ? argv[4] : NULL;
2057         ret = wimlib_open_wim(src_wimfile,
2058                               open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
2059                               imagex_progress_func);
2060         if (ret != 0)
2061                 return ret;
2062
2063         /* Determine if the destination is an existing file or not.
2064          * If so, we try to append the exported image(s) to it; otherwise, we
2065          * create a new WIM containing the exported image(s). */
2066         if (tstat(dest_wimfile, &stbuf) == 0) {
2067                 int dest_ctype;
2068
2069                 wim_is_new = false;
2070                 /* Destination file exists. */
2071
2072                 if (!S_ISREG(stbuf.st_mode)) {
2073                         imagex_error(T("\"%"TS"\" is not a regular file"),
2074                                      dest_wimfile);
2075                         ret = -1;
2076                         goto out;
2077                 }
2078                 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
2079                                       imagex_progress_func);
2080                 if (ret != 0)
2081                         goto out;
2082
2083                 ret = file_writable(dest_wimfile);
2084                 if (ret != 0)
2085                         goto out;
2086
2087                 dest_ctype = wimlib_get_compression_type(dest_w);
2088                 if (compression_type_specified
2089                     && compression_type != dest_ctype)
2090                 {
2091                         imagex_error(T("Cannot specify a compression type that is "
2092                                        "not the same as that used in the "
2093                                        "destination WIM"));
2094                         ret = -1;
2095                         goto out;
2096                 }
2097         } else {
2098                 wim_is_new = true;
2099                 /* dest_wimfile is not an existing file, so create a new WIM. */
2100                 if (!compression_type_specified)
2101                         compression_type = wimlib_get_compression_type(src_w);
2102                 if (errno == ENOENT) {
2103                         ret = wimlib_create_new_wim(compression_type, &dest_w);
2104                         if (ret != 0)
2105                                 goto out;
2106                 } else {
2107                         imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
2108                                                 dest_wimfile);
2109                         ret = -1;
2110                         goto out;
2111                 }
2112         }
2113
2114         image = wimlib_resolve_image(src_w, src_image_num_or_name);
2115         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
2116         if (ret != 0)
2117                 goto out;
2118
2119         if (swm_glob) {
2120                 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
2121                                           &additional_swms,
2122                                           &num_additional_swms);
2123                 if (ret != 0)
2124                         goto out;
2125         }
2126
2127         ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
2128                                   export_flags, additional_swms,
2129                                   num_additional_swms, imagex_progress_func);
2130         if (ret != 0)
2131                 goto out;
2132
2133
2134         if (wim_is_new)
2135                 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
2136                                    write_flags, num_threads,
2137                                    imagex_progress_func);
2138         else
2139                 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
2140                                        imagex_progress_func);
2141 out:
2142         if (ret == WIMLIB_ERR_REOPEN)
2143                 ret = 0;
2144         wimlib_free(src_w);
2145         wimlib_free(dest_w);
2146         if (additional_swms) {
2147                 for (unsigned i = 0; i < num_additional_swms; i++)
2148                         wimlib_free(additional_swms[i]);
2149                 free(additional_swms);
2150         }
2151         return ret;
2152 }
2153
2154 static bool
2155 is_root_wim_path(const tchar *path)
2156 {
2157         const tchar *p;
2158         for (p = path; *p; p++)
2159                 if (*p != T('\\') && *p != T('/'))
2160                         return false;
2161         return true;
2162 }
2163
2164 static void
2165 free_extract_commands(struct wimlib_extract_command *cmds, size_t num_cmds,
2166                       const tchar *dest_dir)
2167 {
2168         for (size_t i = 0; i < num_cmds; i++)
2169                 if (cmds[i].fs_dest_path != dest_dir)
2170                         free(cmds[i].fs_dest_path);
2171         free(cmds);
2172 }
2173
2174 static struct wimlib_extract_command *
2175 prepare_extract_commands(tchar **paths, unsigned num_paths,
2176                          int extract_flags, tchar *dest_dir,
2177                          size_t *num_cmds_ret)
2178 {
2179         struct wimlib_extract_command *cmds;
2180         size_t num_cmds;
2181         tchar *emptystr = T("");
2182
2183         if (num_paths == 0) {
2184                 num_paths = 1;
2185                 paths = &emptystr;
2186         }
2187         num_cmds = num_paths;
2188         cmds = calloc(num_cmds, sizeof(cmds[0]));
2189         if (!cmds) {
2190                 imagex_error(T("Out of memory!"));
2191                 return NULL;
2192         }
2193
2194         for (size_t i = 0; i < num_cmds; i++) {
2195                 cmds[i].extract_flags = extract_flags;
2196                 cmds[i].wim_source_path = paths[i];
2197                 if (is_root_wim_path(paths[i])) {
2198                         cmds[i].fs_dest_path = dest_dir;
2199                 } else {
2200                         size_t len = tstrlen(dest_dir) + 1 + tstrlen(paths[i]);
2201                         cmds[i].fs_dest_path = malloc((len + 1) * sizeof(tchar));
2202                         if (!cmds[i].fs_dest_path) {
2203                                 free_extract_commands(cmds, num_cmds, dest_dir);
2204                                 return NULL;
2205                         }
2206                         tsprintf(cmds[i].fs_dest_path, T("%"TS"/%"TS), dest_dir,
2207                                  tbasename(paths[i]));
2208                 }
2209         }
2210         *num_cmds_ret = num_cmds;
2211         return cmds;
2212 }
2213
2214 /* Extract files or directories from a WIM image */
2215 static int
2216 imagex_extract(int argc, tchar **argv)
2217 {
2218         int c;
2219         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2220         int image;
2221         WIMStruct *wim;
2222         int ret;
2223         const tchar *wimfile;
2224         const tchar *image_num_or_name;
2225         tchar *dest_dir = T(".");
2226         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL | WIMLIB_EXTRACT_FLAG_NORPFIX;
2227
2228         const tchar *swm_glob = NULL;
2229         WIMStruct **additional_swms = NULL;
2230         unsigned num_additional_swms = 0;
2231
2232         struct wimlib_extract_command *cmds;
2233         size_t num_cmds;
2234
2235         for_opt(c, extract_options) {
2236                 switch (c) {
2237                 case IMAGEX_CHECK_OPTION:
2238                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2239                         break;
2240                 case IMAGEX_VERBOSE_OPTION:
2241                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
2242                         break;
2243                 case IMAGEX_REF_OPTION:
2244                         swm_glob = optarg;
2245                         break;
2246                 case IMAGEX_UNIX_DATA_OPTION:
2247                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
2248                         break;
2249                 case IMAGEX_NO_ACLS_OPTION:
2250                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
2251                         break;
2252                 case IMAGEX_STRICT_ACLS_OPTION:
2253                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
2254                         break;
2255                 case IMAGEX_DEST_DIR_OPTION:
2256                         dest_dir = optarg;
2257                         break;
2258                 case IMAGEX_TO_STDOUT_OPTION:
2259                         extract_flags |= WIMLIB_EXTRACT_FLAG_TO_STDOUT;
2260                         imagex_be_quiet = true;
2261                         break;
2262                 default:
2263                         goto out_usage;
2264                 }
2265         }
2266         argc -= optind;
2267         argv += optind;
2268
2269         if (argc < 2)
2270                 goto out_usage;
2271
2272         wimfile = argv[0];
2273         image_num_or_name = argv[1];
2274
2275         argc -= 2;
2276         argv += 2;
2277
2278         cmds = prepare_extract_commands(argv, argc, extract_flags, dest_dir,
2279                                         &num_cmds);
2280         if (!cmds) {
2281                 ret = -1;
2282                 goto out;
2283         }
2284
2285         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2286         if (ret)
2287                 goto out_free_cmds;
2288
2289         image = wimlib_resolve_image(wim, image_num_or_name);
2290         ret = verify_image_exists_and_is_single(image,
2291                                                 image_num_or_name,
2292                                                 wimfile);
2293         if (ret)
2294                 goto out_wimlib_free;
2295
2296         if (swm_glob) {
2297                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2298                                           &additional_swms,
2299                                           &num_additional_swms);
2300                 if (ret)
2301                         goto out_wimlib_free;
2302         }
2303
2304 #ifdef __WIN32__
2305         win32_acquire_restore_privileges();
2306 #endif
2307
2308         ret = wimlib_extract_files(wim, image, cmds, num_cmds, 0,
2309                                    additional_swms, num_additional_swms,
2310                                    imagex_progress_func);
2311         if (ret == 0) {
2312                 if (!imagex_be_quiet)
2313                         tprintf(T("Done extracting files.\n"));
2314         } else if (ret == WIMLIB_ERR_PATH_DOES_NOT_EXIST) {
2315                 tfprintf(stderr, T("Note: You can use `"IMAGEX_PROGNAME" dir' to see what "
2316                                    "files and directories\n"
2317                                    "      are in the WIM image.\n"));
2318         }
2319 #ifdef __WIN32__
2320         win32_release_restore_privileges();
2321 #endif
2322         if (additional_swms) {
2323                 for (unsigned i = 0; i < num_additional_swms; i++)
2324                         wimlib_free(additional_swms[i]);
2325                 free(additional_swms);
2326         }
2327 out_wimlib_free:
2328         wimlib_free(wim);
2329 out_free_cmds:
2330         free_extract_commands(cmds, num_cmds, dest_dir);
2331 out:
2332         return ret;
2333 out_usage:
2334         usage(EXTRACT);
2335         ret = -1;
2336         goto out;
2337 }
2338
2339 /* Prints information about a WIM file; also can mark an image as bootable,
2340  * change the name of an image, or change the description of an image. */
2341 static int
2342 imagex_info(int argc, tchar **argv)
2343 {
2344         int c;
2345         bool boot         = false;
2346         bool check        = false;
2347         bool header       = false;
2348         bool lookup_table = false;
2349         bool xml          = false;
2350         bool metadata     = false;
2351         bool short_header = true;
2352         const tchar *xml_out_file = NULL;
2353         const tchar *wimfile;
2354         const tchar *image_num_or_name = T("all");
2355         const tchar *new_name = NULL;
2356         const tchar *new_desc = NULL;
2357         WIMStruct *w;
2358         FILE *fp;
2359         int image;
2360         int ret;
2361         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2362         int part_number;
2363         int total_parts;
2364         int num_images;
2365
2366         for_opt(c, info_options) {
2367                 switch (c) {
2368                 case IMAGEX_BOOT_OPTION:
2369                         boot = true;
2370                         break;
2371                 case IMAGEX_CHECK_OPTION:
2372                         check = true;
2373                         break;
2374                 case IMAGEX_HEADER_OPTION:
2375                         header = true;
2376                         short_header = false;
2377                         break;
2378                 case IMAGEX_LOOKUP_TABLE_OPTION:
2379                         lookup_table = true;
2380                         short_header = false;
2381                         break;
2382                 case IMAGEX_XML_OPTION:
2383                         xml = true;
2384                         short_header = false;
2385                         break;
2386                 case IMAGEX_EXTRACT_XML_OPTION:
2387                         xml_out_file = optarg;
2388                         short_header = false;
2389                         break;
2390                 case IMAGEX_METADATA_OPTION:
2391                         metadata = true;
2392                         short_header = false;
2393                         break;
2394                 default:
2395                         usage(INFO);
2396                         return -1;
2397                 }
2398         }
2399
2400         argc -= optind;
2401         argv += optind;
2402         if (argc == 0 || argc > 4) {
2403                 usage(INFO);
2404                 return -1;
2405         }
2406         wimfile = argv[0];
2407         if (argc > 1) {
2408                 image_num_or_name = argv[1];
2409                 if (argc > 2) {
2410                         new_name = argv[2];
2411                         if (argc > 3) {
2412                                 new_desc = argv[3];
2413                         }
2414                 }
2415         }
2416
2417         if (check)
2418                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2419
2420         ret = wimlib_open_wim(wimfile, open_flags, &w,
2421                               imagex_progress_func);
2422         if (ret != 0)
2423                 return ret;
2424
2425         part_number = wimlib_get_part_number(w, &total_parts);
2426
2427         image = wimlib_resolve_image(w, image_num_or_name);
2428         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
2429                 imagex_error(T("The image \"%"TS"\" does not exist"),
2430                              image_num_or_name);
2431                 if (boot) {
2432                         imagex_error(T("If you would like to set the boot "
2433                                        "index to 0, specify image \"0\" with "
2434                                        "the --boot flag."));
2435                 }
2436                 ret = WIMLIB_ERR_INVALID_IMAGE;
2437                 goto out;
2438         }
2439
2440         num_images = wimlib_get_num_images(w);
2441
2442         if (num_images == 0) {
2443                 if (boot) {
2444                         imagex_error(T("--boot is meaningless on a WIM with no "
2445                                        "images"));
2446                         ret = WIMLIB_ERR_INVALID_IMAGE;
2447                         goto out;
2448                 }
2449         }
2450
2451         if (image == WIMLIB_ALL_IMAGES && num_images > 1) {
2452                 if (boot) {
2453                         imagex_error(T("Cannot specify the --boot flag "
2454                                        "without specifying a specific "
2455                                        "image in a multi-image WIM"));
2456                         ret = WIMLIB_ERR_INVALID_IMAGE;
2457                         goto out;
2458                 }
2459                 if (new_name) {
2460                         imagex_error(T("Cannot specify the NEW_NAME "
2461                                        "without specifying a specific "
2462                                        "image in a multi-image WIM"));
2463                         ret = WIMLIB_ERR_INVALID_IMAGE;
2464                         goto out;
2465                 }
2466         }
2467
2468         /* Operations that print information are separated from operations that
2469          * recreate the WIM file. */
2470         if (!new_name && !boot) {
2471
2472                 /* Read-only operations */
2473
2474                 if (image == WIMLIB_NO_IMAGE) {
2475                         imagex_error(T("\"%"TS"\" is not a valid image"),
2476                                      image_num_or_name);
2477                         ret = WIMLIB_ERR_INVALID_IMAGE;
2478                         goto out;
2479                 }
2480
2481                 if (image == WIMLIB_ALL_IMAGES && short_header)
2482                         wimlib_print_wim_information(w);
2483
2484                 if (header)
2485                         wimlib_print_header(w);
2486
2487                 if (lookup_table) {
2488                         if (total_parts != 1) {
2489                                 tprintf(T("Warning: Only showing the lookup table "
2490                                           "for part %d of a %d-part WIM.\n"),
2491                                         part_number, total_parts);
2492                         }
2493                         wimlib_print_lookup_table(w);
2494                 }
2495
2496                 if (xml) {
2497                         ret = wimlib_extract_xml_data(w, stdout);
2498                         if (ret != 0)
2499                                 goto out;
2500                 }
2501
2502                 if (xml_out_file) {
2503                         fp = tfopen(xml_out_file, T("wb"));
2504                         if (!fp) {
2505                                 imagex_error_with_errno(T("Failed to open the "
2506                                                           "file \"%"TS"\" for "
2507                                                           "writing "),
2508                                                         xml_out_file);
2509                                 ret = -1;
2510                                 goto out;
2511                         }
2512                         ret = wimlib_extract_xml_data(w, fp);
2513                         if (fclose(fp) != 0) {
2514                                 imagex_error(T("Failed to close the file "
2515                                                "\"%"TS"\""),
2516                                              xml_out_file);
2517                                 ret = -1;
2518                         }
2519
2520                         if (ret != 0)
2521                                 goto out;
2522                 }
2523
2524                 if (short_header)
2525                         wimlib_print_available_images(w, image);
2526
2527                 if (metadata) {
2528                         ret = wimlib_print_metadata(w, image);
2529                         if (ret != 0)
2530                                 goto out;
2531                 }
2532         } else {
2533
2534                 /* Modification operations */
2535                 if (total_parts != 1) {
2536                         imagex_error(T("Modifying a split WIM is not supported."));
2537                         ret = -1;
2538                         goto out;
2539                 }
2540                 if (image == WIMLIB_ALL_IMAGES)
2541                         image = 1;
2542
2543                 if (image == WIMLIB_NO_IMAGE && new_name) {
2544                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2545                                        "when using image 0"), new_name);
2546                         ret = -1;
2547                         goto out;
2548                 }
2549
2550                 if (boot) {
2551                         if (image == wimlib_get_boot_idx(w)) {
2552                                 tprintf(T("Image %d is already marked as "
2553                                           "bootable.\n"), image);
2554                                 boot = false;
2555                         } else {
2556                                 tprintf(T("Marking image %d as bootable.\n"),
2557                                         image);
2558                                 wimlib_set_boot_idx(w, image);
2559                         }
2560                 }
2561                 if (new_name) {
2562                         if (!tstrcmp(wimlib_get_image_name(w, image), new_name))
2563                         {
2564                                 tprintf(T("Image %d is already named \"%"TS"\".\n"),
2565                                         image, new_name);
2566                                 new_name = NULL;
2567                         } else {
2568                                 tprintf(T("Changing the name of image %d to "
2569                                           "\"%"TS"\".\n"), image, new_name);
2570                                 ret = wimlib_set_image_name(w, image, new_name);
2571                                 if (ret != 0)
2572                                         goto out;
2573                         }
2574                 }
2575                 if (new_desc) {
2576                         const tchar *old_desc;
2577                         old_desc = wimlib_get_image_description(w, image);
2578                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
2579                                 tprintf(T("The description of image %d is already "
2580                                           "\"%"TS"\".\n"), image, new_desc);
2581                                 new_desc = NULL;
2582                         } else {
2583                                 tprintf(T("Changing the description of image %d "
2584                                           "to \"%"TS"\".\n"), image, new_desc);
2585                                 ret = wimlib_set_image_descripton(w, image,
2586                                                                   new_desc);
2587                                 if (ret != 0)
2588                                         goto out;
2589                         }
2590                 }
2591
2592                 /* Only call wimlib_overwrite() if something actually needs to
2593                  * be changed. */
2594                 if (boot || new_name || new_desc ||
2595                     (check && !wimlib_has_integrity_table(w)))
2596                 {
2597                         int write_flags;
2598
2599                         ret = file_writable(wimfile);
2600                         if (ret != 0)
2601                                 goto out;
2602
2603                         if (check)
2604                                 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2605                         else
2606                                 write_flags = 0;
2607
2608                         ret = wimlib_overwrite(w, write_flags, 1,
2609                                                imagex_progress_func);
2610                         if (ret == WIMLIB_ERR_REOPEN)
2611                                 ret = 0;
2612                 } else {
2613                         tprintf(T("The file \"%"TS"\" was not modified because nothing "
2614                                   "needed to be done.\n"), wimfile);
2615                         ret = 0;
2616                 }
2617         }
2618 out:
2619         wimlib_free(w);
2620         return ret;
2621 }
2622
2623 /* Join split WIMs into one part WIM */
2624 static int
2625 imagex_join(int argc, tchar **argv)
2626 {
2627         int c;
2628         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2629         int wim_write_flags = 0;
2630         const tchar *output_path;
2631
2632         for_opt(c, join_options) {
2633                 switch (c) {
2634                 case IMAGEX_CHECK_OPTION:
2635                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2636                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2637                         break;
2638                 default:
2639                         goto err;
2640                 }
2641         }
2642         argc -= optind;
2643         argv += optind;
2644
2645         if (argc < 2) {
2646                 imagex_error(T("Must specify one or more split WIM (.swm) "
2647                                "parts to join"));
2648                 goto err;
2649         }
2650         output_path = argv[0];
2651         return wimlib_join((const tchar * const *)++argv,
2652                            --argc,
2653                            output_path,
2654                            swm_open_flags,
2655                            wim_write_flags,
2656                            imagex_progress_func);
2657 err:
2658         usage(JOIN);
2659         return -1;
2660 }
2661
2662 /* Mounts an image using a FUSE mount. */
2663 static int
2664 imagex_mount_rw_or_ro(int argc, tchar **argv)
2665 {
2666         int c;
2667         int mount_flags = 0;
2668         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2669         const tchar *wimfile;
2670         const tchar *dir;
2671         WIMStruct *w;
2672         int image;
2673         int num_images;
2674         int ret;
2675         const tchar *swm_glob = NULL;
2676         WIMStruct **additional_swms = NULL;
2677         unsigned num_additional_swms = 0;
2678         const tchar *staging_dir = NULL;
2679
2680         if (!tstrcmp(argv[0], T("mountrw")))
2681                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
2682
2683         for_opt(c, mount_options) {
2684                 switch (c) {
2685                 case IMAGEX_ALLOW_OTHER_OPTION:
2686                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
2687                         break;
2688                 case IMAGEX_CHECK_OPTION:
2689                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2690                         break;
2691                 case IMAGEX_DEBUG_OPTION:
2692                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
2693                         break;
2694                 case IMAGEX_STREAMS_INTERFACE_OPTION:
2695                         if (!tstrcasecmp(optarg, T("none")))
2696                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
2697                         else if (!tstrcasecmp(optarg, T("xattr")))
2698                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2699                         else if (!tstrcasecmp(optarg, T("windows")))
2700                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
2701                         else {
2702                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
2703                                              optarg);
2704                                 goto mount_usage;
2705                         }
2706                         break;
2707                 case IMAGEX_REF_OPTION:
2708                         swm_glob = optarg;
2709                         break;
2710                 case IMAGEX_STAGING_DIR_OPTION:
2711                         staging_dir = optarg;
2712                         break;
2713                 case IMAGEX_UNIX_DATA_OPTION:
2714                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
2715                         break;
2716                 default:
2717                         goto mount_usage;
2718                 }
2719         }
2720         argc -= optind;
2721         argv += optind;
2722         if (argc != 2 && argc != 3)
2723                 goto mount_usage;
2724
2725         wimfile = argv[0];
2726
2727         ret = wimlib_open_wim(wimfile, open_flags, &w,
2728                               imagex_progress_func);
2729         if (ret != 0)
2730                 return ret;
2731
2732         if (swm_glob) {
2733                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2734                                           &additional_swms,
2735                                           &num_additional_swms);
2736                 if (ret != 0)
2737                         goto out;
2738         }
2739
2740         if (argc == 2) {
2741                 image = 1;
2742                 num_images = wimlib_get_num_images(w);
2743                 if (num_images != 1) {
2744                         imagex_error(T("\"%"TS"\" contains %d images; Please "
2745                                        "select one."), wimfile, num_images);
2746                         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2747                                         ? MOUNTRW : MOUNT);
2748                         ret = -1;
2749                         goto out;
2750                 }
2751                 dir = argv[1];
2752         } else {
2753                 image = wimlib_resolve_image(w, argv[1]);
2754                 dir = argv[2];
2755                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2756                 if (ret != 0)
2757                         goto out;
2758         }
2759
2760         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2761                 ret = file_writable(wimfile);
2762                 if (ret != 0)
2763                         goto out;
2764         }
2765
2766         ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
2767                                  num_additional_swms, staging_dir);
2768         if (ret != 0) {
2769                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
2770                                "on \"%"TS"\""),
2771                              image, wimfile, dir);
2772
2773         }
2774 out:
2775         wimlib_free(w);
2776         if (additional_swms) {
2777                 for (unsigned i = 0; i < num_additional_swms; i++)
2778                         wimlib_free(additional_swms[i]);
2779                 free(additional_swms);
2780         }
2781         return ret;
2782 mount_usage:
2783         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2784                         ? MOUNTRW : MOUNT);
2785         return -1;
2786 }
2787
2788 /* Rebuild a WIM file */
2789 static int
2790 imagex_optimize(int argc, tchar **argv)
2791 {
2792         int c;
2793         int open_flags = 0;
2794         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
2795         int ret;
2796         WIMStruct *w;
2797         const tchar *wimfile;
2798         off_t old_size;
2799         off_t new_size;
2800         unsigned num_threads = 0;
2801
2802         for_opt(c, optimize_options) {
2803                 switch (c) {
2804                 case IMAGEX_CHECK_OPTION:
2805                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2806                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2807                         break;
2808                 case IMAGEX_RECOMPRESS_OPTION:
2809                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
2810                         break;
2811                 case IMAGEX_THREADS_OPTION:
2812                         num_threads = parse_num_threads(optarg);
2813                         if (num_threads == UINT_MAX)
2814                                 return -1;
2815                         break;
2816                 default:
2817                         usage(OPTIMIZE);
2818                         return -1;
2819                 }
2820         }
2821         argc -= optind;
2822         argv += optind;
2823
2824         if (argc != 1) {
2825                 usage(OPTIMIZE);
2826                 return -1;
2827         }
2828
2829         wimfile = argv[0];
2830
2831         ret = file_writable(wimfile);
2832         if (ret)
2833                 return ret;
2834
2835         ret = wimlib_open_wim(wimfile, open_flags, &w,
2836                               imagex_progress_func);
2837         if (ret)
2838                 return ret;
2839
2840         old_size = file_get_size(argv[0]);
2841         tprintf(T("\"%"TS"\" original size: "), wimfile);
2842         if (old_size == -1)
2843                 tfputs(T("Unknown\n"), stdout);
2844         else
2845                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
2846
2847         ret = wimlib_overwrite(w, write_flags, num_threads,
2848                                imagex_progress_func);
2849
2850         if (ret == 0) {
2851                 new_size = file_get_size(argv[0]);
2852                 tprintf(T("\"%"TS"\" optimized size: "), wimfile);
2853                 if (new_size == -1)
2854                         tfputs(T("Unknown\n"), stdout);
2855                 else
2856                         tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
2857
2858                 tfputs(T("Space saved: "), stdout);
2859                 if (new_size != -1 && old_size != -1) {
2860                         tprintf(T("%lld KiB\n"),
2861                                ((long long)old_size - (long long)new_size) >> 10);
2862                 } else {
2863                         tfputs(T("Unknown\n"), stdout);
2864                 }
2865         }
2866
2867         wimlib_free(w);
2868         return ret;
2869 }
2870
2871 /* Split a WIM into a spanned set */
2872 static int
2873 imagex_split(int argc, tchar **argv)
2874 {
2875         int c;
2876         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2877         int write_flags = 0;
2878         unsigned long part_size;
2879         tchar *tmp;
2880         int ret;
2881         WIMStruct *w;
2882
2883         for_opt(c, split_options) {
2884                 switch (c) {
2885                 case IMAGEX_CHECK_OPTION:
2886                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2887                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2888                         break;
2889                 default:
2890                         usage(SPLIT);
2891                         return -1;
2892                 }
2893         }
2894         argc -= optind;
2895         argv += optind;
2896
2897         if (argc != 3) {
2898                 usage(SPLIT);
2899                 return -1;
2900         }
2901         part_size = tstrtod(argv[2], &tmp) * (1 << 20);
2902         if (tmp == argv[2] || *tmp) {
2903                 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
2904                 imagex_error(T("The part size must be an integer or "
2905                                "floating-point number of megabytes."));
2906                 return -1;
2907         }
2908         ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
2909         if (ret != 0)
2910                 return ret;
2911         ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
2912         wimlib_free(w);
2913         return ret;
2914 }
2915
2916 /* Unmounts a mounted WIM image. */
2917 static int
2918 imagex_unmount(int argc, tchar **argv)
2919 {
2920         int c;
2921         int unmount_flags = 0;
2922         int ret;
2923
2924         for_opt(c, unmount_options) {
2925                 switch (c) {
2926                 case IMAGEX_COMMIT_OPTION:
2927                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
2928                         break;
2929                 case IMAGEX_CHECK_OPTION:
2930                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
2931                         break;
2932                 case IMAGEX_REBUILD_OPTION:
2933                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
2934                         break;
2935                 case IMAGEX_LAZY_OPTION:
2936                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_LAZY;
2937                         break;
2938                 default:
2939                         usage(UNMOUNT);
2940                         return -1;
2941                 }
2942         }
2943         argc -= optind;
2944         argv += optind;
2945         if (argc != 1) {
2946                 usage(UNMOUNT);
2947                 return -1;
2948         }
2949
2950         ret = wimlib_unmount_image(argv[0], unmount_flags,
2951                                    imagex_progress_func);
2952         if (ret != 0)
2953                 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
2954         return ret;
2955 }
2956
2957 /*
2958  * Add, delete, or rename files in a WIM image.
2959  */
2960 static int
2961 imagex_update(int argc, tchar **argv)
2962 {
2963         const tchar *wimfile;
2964         const tchar *image_num_or_name;
2965         int image;
2966         WIMStruct *wim;
2967         int ret;
2968         int open_flags = 0;
2969         int write_flags = 0;
2970         int update_flags = 0;
2971         int default_add_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE;
2972         int default_delete_flags = 0;
2973         unsigned num_threads = 0;
2974         int c;
2975         tchar *cmd_file_contents;
2976         size_t cmd_file_nchars;
2977         struct wimlib_update_command *cmds;
2978         size_t num_cmds;
2979         int num_images;
2980
2981         const tchar *config_file = NULL;
2982         tchar *config_str;
2983         struct wimlib_capture_config *config = NULL;
2984
2985         for_opt(c, update_options) {
2986                 switch (c) {
2987                 /* Generic or write options */
2988                 case IMAGEX_THREADS_OPTION:
2989                         num_threads = parse_num_threads(optarg);
2990                         if (num_threads == UINT_MAX) {
2991                                 ret = -1;
2992                                 goto out;
2993                         }
2994                         break;
2995                 case IMAGEX_CHECK_OPTION:
2996                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2997                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2998                         break;
2999                 case IMAGEX_REBUILD_OPTION:
3000                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
3001                         break;
3002
3003                 /* Default delete options */
3004                 case IMAGEX_FORCE_OPTION:
3005                         default_delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
3006                         break;
3007                 case IMAGEX_RECURSIVE_OPTION:
3008                         default_delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
3009                         break;
3010
3011                 /* Global add option */
3012                 case IMAGEX_CONFIG_OPTION:
3013                         config_file = optarg;
3014                         break;
3015
3016                 /* Default add options */
3017                 case IMAGEX_VERBOSE_OPTION:
3018                         default_add_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
3019                         break;
3020                 case IMAGEX_DEREFERENCE_OPTION:
3021                         default_add_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
3022                         break;
3023                 case IMAGEX_UNIX_DATA_OPTION:
3024                         default_add_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
3025                         break;
3026                 case IMAGEX_NO_ACLS_OPTION:
3027                         default_add_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
3028                         break;
3029                 case IMAGEX_STRICT_ACLS_OPTION:
3030                         default_add_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
3031                         break;
3032                 default:
3033                         goto out_usage;
3034                 }
3035         }
3036         argv += optind;
3037         argc -= optind;
3038
3039         if (argc < 1 || argc > 2)
3040                 goto out_usage;
3041         wimfile = argv[0];
3042
3043         ret = file_writable(wimfile);
3044         if (ret)
3045                 goto out;
3046
3047         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3048         if (ret)
3049                 goto out;
3050
3051         if (argc == 2)
3052                 image_num_or_name = argv[1];
3053         else
3054                 image_num_or_name = T("1");
3055
3056         image = wimlib_resolve_image(wim, image_num_or_name);
3057
3058         ret = verify_image_exists_and_is_single(image, image_num_or_name,
3059                                                 wimfile);
3060         if (ret)
3061                 goto out_wimlib_free;
3062
3063         num_images = wimlib_get_num_images(wim);
3064         if (argc == 1 && num_images != 1) {
3065                 imagex_error(T("\"%"TS"\" contains %d images; Please select one."),
3066                              wimfile, num_images);
3067                 usage(UPDATE);
3068                 ret = -1;
3069                 goto out_wimlib_free;
3070         }
3071
3072         /* Parse capture configuration file if specified */
3073         if (config_file) {
3074                 size_t config_len;
3075
3076                 config_str = file_get_text_contents(config_file, &config_len);
3077                 if (!config_str) {
3078                         ret = -1;
3079                         goto out_wimlib_free;
3080                 }
3081
3082                 config = alloca(sizeof(*config));
3083                 ret = parse_capture_config(&config_str, config_len, config);
3084                 if (ret)
3085                         goto out_free_config;
3086         } else {
3087                 config = &default_capture_config;
3088         }
3089
3090         /* Read update commands from standard input */
3091         if (isatty(STDIN_FILENO)) {
3092                 tputs(T("Reading update commands from standard input..."));
3093                 recommend_man_page(T("update"));
3094         }
3095         cmd_file_contents = stdin_get_text_contents(&cmd_file_nchars);
3096         if (!cmd_file_contents) {
3097                 ret = -1;
3098                 goto out_free_config;
3099         }
3100
3101         /* Parse the update commands */
3102         cmds = parse_update_command_file(&cmd_file_contents, cmd_file_nchars,
3103                                          &num_cmds);
3104         if (!cmds) {
3105                 ret = -1;
3106                 goto out_free_cmd_file_contents;
3107         }
3108
3109         /* Set default flags and capture config on the update commands */
3110         for (size_t i = 0; i < num_cmds; i++) {
3111                 switch (cmds[i].op) {
3112                 case WIMLIB_UPDATE_OP_ADD:
3113                         cmds[i].add.add_flags |= default_add_flags;
3114                         cmds[i].add.config = config;
3115                         break;
3116                 case WIMLIB_UPDATE_OP_DELETE:
3117                         cmds[i].delete.delete_flags |= default_delete_flags;
3118                         break;
3119                 default:
3120                         break;
3121                 }
3122         }
3123
3124 #ifdef __WIN32__
3125         win32_acquire_capture_privileges();
3126 #endif
3127
3128         /* Execute the update commands */
3129         ret = wimlib_update_image(wim, image, cmds, num_cmds, update_flags,
3130                                   imagex_progress_func);
3131         if (ret)
3132                 goto out_release_privs;
3133
3134         /* Overwrite the updated WIM */
3135         ret = wimlib_overwrite(wim, write_flags, num_threads,
3136                                imagex_progress_func);
3137 out_release_privs:
3138 #ifdef __WIN32__
3139         win32_release_capture_privileges();
3140 #endif
3141 out_free_cmds:
3142         free(cmds);
3143 out_free_cmd_file_contents:
3144         free(cmd_file_contents);
3145 out_free_config:
3146         if (config != NULL && config != &default_capture_config) {
3147                 free(config->exclusion_pats.pats);
3148                 free(config->exclusion_exception_pats.pats);
3149                 free(config_str);
3150         }
3151 out_wimlib_free:
3152         wimlib_free(wim);
3153 out:
3154         return ret;
3155 out_usage:
3156         usage(UPDATE);
3157         ret = -1;
3158         goto out;
3159 }
3160
3161 struct imagex_command {
3162         const tchar *name;
3163         int (*func)(int , tchar **);
3164         int cmd;
3165 };
3166
3167
3168 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
3169                 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
3170
3171 static const struct imagex_command imagex_commands[] = {
3172         {T("append"),  imagex_capture_or_append, APPEND},
3173         {T("apply"),   imagex_apply,             APPLY},
3174         {T("capture"), imagex_capture_or_append, CAPTURE},
3175         {T("delete"),  imagex_delete,            DELETE},
3176         {T("dir"),     imagex_dir,               DIR},
3177         {T("export"),  imagex_export,            EXPORT},
3178         {T("extract"), imagex_extract,           EXTRACT},
3179         {T("info"),    imagex_info,              INFO},
3180         {T("join"),    imagex_join,              JOIN},
3181         {T("mount"),   imagex_mount_rw_or_ro,    MOUNT},
3182         {T("mountrw"), imagex_mount_rw_or_ro,    MOUNTRW},
3183         {T("optimize"),imagex_optimize,          OPTIMIZE},
3184         {T("split"),   imagex_split,             SPLIT},
3185         {T("unmount"), imagex_unmount,           UNMOUNT},
3186         {T("update"),  imagex_update,            UPDATE},
3187 };
3188
3189 static void
3190 version(void)
3191 {
3192         static const tchar *s =
3193         T(
3194 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
3195 "Copyright (C) 2012, 2013 Eric Biggers\n"
3196 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
3197 "This is free software: you are free to change and redistribute it.\n"
3198 "There is NO WARRANTY, to the extent permitted by law.\n"
3199 "\n"
3200 "Report bugs to "PACKAGE_BUGREPORT".\n"
3201         );
3202         tfputs(s, stdout);
3203 }
3204
3205
3206 static void
3207 help_or_version(int argc, tchar **argv)
3208 {
3209         int i;
3210         const tchar *p;
3211         const struct imagex_command *cmd;
3212
3213         for (i = 1; i < argc; i++) {
3214                 p = argv[i];
3215                 if (*p == T('-'))
3216                         p++;
3217                 else
3218                         continue;
3219                 if (*p == T('-'))
3220                         p++;
3221                 if (!tstrcmp(p, T("help"))) {
3222                         for_imagex_command(cmd) {
3223                                 if (!tstrcmp(cmd->name, argv[1])) {
3224                                         usage(cmd->cmd);
3225                                         exit(0);
3226                                 }
3227                         }
3228                         usage_all();
3229                         exit(0);
3230                 }
3231                 if (!tstrcmp(p, T("version"))) {
3232                         version();
3233                         exit(0);
3234                 }
3235         }
3236 }
3237
3238
3239 static void
3240 usage(int cmd_type)
3241 {
3242         const struct imagex_command *cmd;
3243         tprintf(T("Usage:\n%"TS), usage_strings[cmd_type]);
3244         for_imagex_command(cmd) {
3245                 if (cmd->cmd == cmd_type) {
3246                         tputc(T('\n'), stdout);
3247                         recommend_man_page(cmd->name);
3248                 }
3249         }
3250 }
3251
3252 static void
3253 usage_all(void)
3254 {
3255         tfputs(T("Usage:\n"), stdout);
3256         for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
3257                 tprintf(T("    %"TS), usage_strings[i]);
3258         static const tchar *extra =
3259         T(
3260 "    "IMAGEX_PROGNAME" --help\n"
3261 "    "IMAGEX_PROGNAME" --version\n"
3262 "\n"
3263 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
3264 "\n"
3265         );
3266         tfputs(extra, stdout);
3267         recommend_man_page(T(""));
3268 }
3269
3270 /* Entry point for wimlib's ImageX implementation.  On UNIX the command
3271  * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
3272  * something else), while an Windows the command arguments will be UTF-16LE
3273  * encoded 'wchar_t' strings. */
3274 int
3275 #ifdef __WIN32__
3276 wmain(int argc, wchar_t **argv, wchar_t **envp)
3277 #else
3278 main(int argc, char **argv)
3279 #endif
3280 {
3281         const struct imagex_command *cmd;
3282         int ret;
3283         int init_flags = 0;
3284
3285 #ifndef __WIN32__
3286         if (getenv("WIMLIB_IMAGEX_USE_UTF8")) {
3287                 init_flags |= WIMLIB_INIT_FLAG_ASSUME_UTF8;
3288         } else {
3289                 char *codeset;
3290
3291                 setlocale(LC_ALL, "");
3292                 codeset = nl_langinfo(CODESET);
3293                 if (!strstr(codeset, "UTF-8") &&
3294                     !strstr(codeset, "UTF8") &&
3295                     !strstr(codeset, "utf-8") &&
3296                     !strstr(codeset, "utf8"))
3297                 {
3298                         fputs(
3299 "WARNING: Running "IMAGEX_PROGNAME" in a UTF-8 locale is recommended!\n"
3300 "         Maybe try: `export LANG=en_US.UTF-8'?\n"
3301 "         Alternatively, set the environmental variable WIMLIB_IMAGEX_USE_UTF8\n"
3302 "         to any value to force wimlib to use UTF-8.\n",
3303                         stderr);
3304
3305                 }
3306         }
3307 #endif /* !__WIN32__ */
3308
3309         if (argc < 2) {
3310                 imagex_error(T("No command specified"));
3311                 usage_all();
3312                 ret = 2;
3313                 goto out;
3314         }
3315
3316         /* Handle --help and --version for all commands.  Note that this will
3317          * not return if either of these arguments are present. */
3318         help_or_version(argc, argv);
3319         argc--;
3320         argv++;
3321
3322         /* The user may like to see more informative error messages. */
3323         wimlib_set_print_errors(true);
3324
3325         /* Do any initializations that the library needs */
3326         ret = wimlib_global_init(init_flags);
3327         if (ret)
3328                 goto out_check_status;
3329
3330         /* Search for the function to handle the ImageX subcommand. */
3331         for_imagex_command(cmd) {
3332                 if (!tstrcmp(cmd->name, *argv)) {
3333                         ret = cmd->func(argc, argv);
3334                         goto out_check_write_error;
3335                 }
3336         }
3337
3338         imagex_error(T("Unrecognized command: `%"TS"'"), argv[0]);
3339         usage_all();
3340         ret = 2;
3341         goto out_cleanup;
3342 out_check_write_error:
3343         /* For 'wimlib-imagex info' and 'wimlib-imagex dir', data printed to
3344          * standard output is part of the program's actual behavior and not just
3345          * for informational purposes, so we should set a failure exit status if
3346          * there was a write error. */
3347         if (cmd == &imagex_commands[INFO] || cmd == &imagex_commands[DIR]) {
3348                 if (ferror(stdout) || fclose(stdout)) {
3349                         imagex_error_with_errno(T("error writing to standard output"));
3350                         if (ret == 0)
3351                                 ret = -1;
3352                 }
3353         }
3354 out_check_status:
3355         /* Exit status (ret):  -1 indicates an error found by 'wimlib-imagex'
3356          * outside of the wimlib library code.  0 indicates success.  > 0
3357          * indicates a wimlib error code from which an error message can be
3358          * printed. */
3359         if (ret > 0) {
3360                 imagex_error(T("Exiting with error code %d:\n"
3361                                "       %"TS"."), ret,
3362                              wimlib_get_error_string(ret));
3363                 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
3364                         imagex_error_with_errno(T("errno"));
3365         }
3366 out_cleanup:
3367         /* Make the library free any resources it's holding (not strictly
3368          * necessary because the process is ending anyway). */
3369         wimlib_global_cleanup();
3370 out:
3371         return ret;
3372 }