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