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