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