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