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