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