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