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