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