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