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