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