]> wimlib.net Git - wimlib/blob - programs/imagex.c
Improve progress messages for NTFS apply
[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 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 <errno.h>
30 #include <getopt.h>
31 #include <glob.h>
32 #include <inttypes.h>
33 #include <libgen.h>
34 #include <limits.h>
35 #include <stdarg.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
40
41 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
42
43 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (char**)argv, "", \
44                                 opts, NULL)) != -1)
45
46 enum imagex_op_type {
47         APPEND,
48         APPLY,
49         CAPTURE,
50         DELETE,
51         DIR,
52         EXPORT,
53         INFO,
54         JOIN,
55         MOUNT,
56         MOUNTRW,
57         OPTIMIZE,
58         SPLIT,
59         UNMOUNT,
60 };
61
62 static void usage(int cmd_type);
63 static void usage_all();
64
65 static const char *usage_strings[] = {
66 [APPEND] =
67 "imagex append (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
68 "                     [DESCRIPTION] [--boot] [--check] [--flags EDITION_ID]\n"
69 "                     [--verbose] [--dereference] [--config=FILE]\n"
70 "                     [--threads=NUM_THREADS] [--rebuild]\n",
71 [APPLY] =
72 "imagex apply WIMFILE [IMAGE_NUM | IMAGE_NAME | all]\n"
73 "                    (DIRECTORY | NTFS_VOLUME) [--check] [--hardlink]\n"
74 "                    [--symlink] [--verbose] [--ref=\"GLOB\"]\n",
75 [CAPTURE] =
76 "imagex capture (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
77 "                      [DESCRIPTION] [--boot] [--check] [--compress=TYPE]\n"
78 "                      [--flags EDITION_ID] [--verbose] [--dereference]\n"
79 "                      [--config=FILE] [--threads=NUM_THREADS]\n",
80 [DELETE] =
81 "imagex delete WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check] [--soft]\n",
82 [DIR] =
83 "imagex dir WIMFILE (IMAGE_NUM | IMAGE_NAME | all)\n",
84 [EXPORT] =
85 "imagex export SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
86 "              DEST_WIMFILE [DEST_IMAGE_NAME] [DEST_IMAGE_DESCRIPTION]\n"
87 "              [--boot] [--check] [--compress=TYPE] [--ref=\"GLOB\"]\n"
88 "              [--threads=NUM_THREADS] [--rebuild]\n",
89 [INFO] =
90 "imagex info WIMFILE [IMAGE_NUM | IMAGE_NAME] [NEW_NAME]\n"
91 "                   [NEW_DESC] [--boot] [--check] [--header] [--lookup-table]\n"
92 "                   [--xml] [--extract-xml FILE] [--metadata]\n",
93 [JOIN] =
94 "imagex join [--check] WIMFILE SPLIT_WIM...\n",
95 [MOUNT] =
96 "imagex mount WIMFILE (IMAGE_NUM | IMAGE_NAME) DIRECTORY\n"
97 "                    [--check] [--debug] [--streams-interface=INTERFACE]\n"
98 "                    [--ref=\"GLOB\"]\n",
99 [MOUNTRW] =
100 "imagex mountrw WIMFILE [IMAGE_NUM | IMAGE_NAME] DIRECTORY\n"
101 "                      [--check] [--debug] [--streams-interface=INTERFACE]\n"
102 "                      [--staging-dir=DIR]\n",
103 [OPTIMIZE] =
104 "imagex optimize WIMFILE [--check] [--recompress] [--compress=TYPE]\n",
105 [SPLIT] =
106 "imagex split WIMFILE SPLIT_WIMFILE PART_SIZE_MB [--check]\n",
107 [UNMOUNT] =
108 "imagex unmount DIRECTORY [--commit] [--check]\n",
109 };
110
111 static const struct option common_options[] = {
112         {"help", 0, NULL, 'h'},
113         {"version", 0, NULL, 'v'},
114         {NULL, 0, NULL, 0},
115 };
116
117 static const struct option apply_options[] = {
118         {"check",    no_argument,       NULL, 'c'},
119         {"hardlink", no_argument,       NULL, 'h'},
120         {"symlink",  no_argument,       NULL, 's'},
121         {"verbose",  no_argument,       NULL, 'v'},
122         {"ref",      required_argument, NULL, 'r'},
123         {NULL, 0, NULL, 0},
124 };
125 static const struct option capture_or_append_options[] = {
126         {"boot",        no_argument,       NULL, 'b'},
127         {"check",       no_argument,       NULL, 'c'},
128         {"compress",    required_argument, NULL, 'x'},
129         {"config",      required_argument, NULL, 'C'},
130         {"dereference", no_argument,       NULL, 'L'},
131         {"flags",       required_argument, NULL, 'f'},
132         {"verbose",     no_argument,       NULL, 'v'},
133         {"threads",     required_argument, NULL, 't'},
134         {"rebuild",     no_argument,       NULL, 'R'},
135         {NULL, 0, NULL, 0},
136 };
137 static const struct option delete_options[] = {
138         {"check", no_argument, NULL, 'c'},
139         {"soft",  no_argument, NULL, 's'},
140         {NULL, 0, NULL, 0},
141 };
142
143 static const struct option export_options[] = {
144         {"boot",       no_argument,       NULL, 'b'},
145         {"check",      no_argument,       NULL, 'c'},
146         {"compress",   required_argument, NULL, 'x'},
147         {"ref",        required_argument, NULL, 'r'},
148         {"threads",    required_argument, NULL, 't'},
149         {"rebuild",    no_argument,       NULL, 'R'},
150         {NULL, 0, NULL, 0},
151 };
152
153 static const struct option info_options[] = {
154         {"boot",         no_argument, NULL, 'b'},
155         {"check",        no_argument, NULL, 'c'},
156         {"extract-xml",  required_argument, NULL, 'X'},
157         {"header",       no_argument, NULL, 'h'},
158         {"lookup-table", no_argument, NULL, 'l'},
159         {"metadata",     no_argument, NULL, 'm'},
160         {"xml",          no_argument, NULL, 'x'},
161         {NULL, 0, NULL, 0},
162 };
163
164 static const struct option join_options[] = {
165         {"check", no_argument, NULL, 'c'},
166         {NULL, 0, NULL, 0},
167 };
168
169 static const struct option mount_options[] = {
170         {"check",             no_argument,       NULL, 'c'},
171         {"debug",             no_argument,       NULL, 'd'},
172         {"streams-interface", required_argument, NULL, 's'},
173         {"ref",               required_argument, NULL, 'r'},
174         {"staging-dir",       required_argument, NULL, 'D'},
175         {NULL, 0, NULL, 0},
176 };
177
178 static const struct option optimize_options[] = {
179         {"check",      no_argument, NULL, 'c'},
180         {"recompress", no_argument, NULL, 'r'},
181         {NULL, 0, NULL, 0},
182 };
183
184 static const struct option split_options[] = {
185         {"check", no_argument, NULL, 'c'},
186         {NULL, 0, NULL, 0},
187 };
188
189 static const struct option unmount_options[] = {
190         {"commit", no_argument, NULL, 'c'},
191         {"check", no_argument, NULL, 'C'},
192         {NULL, 0, NULL, 0},
193 };
194
195
196
197 /* Print formatted error message to stderr. */
198 static void imagex_error(const char *format, ...)
199 {
200         va_list va;
201         va_start(va, format);
202         fputs("ERROR: ", stderr);
203         vfprintf(stderr, format, va);
204         putc('\n', stderr);
205         va_end(va);
206 }
207
208 /* Print formatted error message to stderr. */
209 static void imagex_error_with_errno(const char *format, ...)
210 {
211         int errno_save = errno;
212         va_list va;
213         va_start(va, format);
214         fputs("ERROR: ", stderr);
215         vfprintf(stderr, format, va);
216         fprintf(stderr, ": %s\n", strerror(errno_save));
217         va_end(va);
218 }
219
220 static int verify_image_exists(int image, const char *image_name,
221                                const char *wim_name)
222 {
223         if (image == WIMLIB_NO_IMAGE) {
224                 imagex_error("\"%s\" is not a valid image in `%s'!\n"
225                              "       Please specify a 1-based imagex index or "
226                              "image name.\n"
227                              "       You may use `imagex info' to list the images "
228                              "contained in a WIM.",
229                              image_name, wim_name);
230                 return -1;
231         }
232         return 0;
233 }
234
235 static int verify_image_is_single(int image)
236 {
237         if (image == WIMLIB_ALL_IMAGES) {
238                 imagex_error("Cannot specify all images for this action!");
239                 return -1;
240         }
241         return 0;
242 }
243
244 static int verify_image_exists_and_is_single(int image, const char *image_name,
245                                              const char *wim_name)
246 {
247         int ret;
248         ret = verify_image_exists(image, image_name, wim_name);
249         if (ret == 0)
250                 ret = verify_image_is_single(image);
251         return ret;
252 }
253
254 static int get_compression_type(const char *optarg)
255 {
256         if (strcasecmp(optarg, "maximum") == 0 || strcasecmp(optarg, "lzx") == 0)
257                 return WIMLIB_COMPRESSION_TYPE_LZX;
258         else if (strcasecmp(optarg, "fast") == 0 || strcasecmp(optarg, "xpress") == 0)
259                 return WIMLIB_COMPRESSION_TYPE_XPRESS;
260         else if (strcasecmp(optarg, "none") == 0)
261                 return WIMLIB_COMPRESSION_TYPE_NONE;
262         else {
263                 imagex_error("Invalid compression type `%s'! Must be "
264                              "\"maximum\", \"fast\", or \"none\".", optarg);
265                 return WIMLIB_COMPRESSION_TYPE_INVALID;
266         }
267 }
268
269 static off_t file_get_size(const char *filename)
270 {
271         struct stat st;
272         if (stat(filename, &st) == 0)
273                 return st.st_size;
274         else
275                 return (off_t)-1;
276 }
277
278 static char *file_get_contents(const char *filename, size_t *len_ret)
279 {
280         struct stat stbuf;
281         char *buf;
282         size_t len;
283         FILE *fp;
284
285         if (stat(filename, &stbuf) != 0) {
286                 imagex_error_with_errno("Failed to stat the file `%s'", filename);
287                 return NULL;
288         }
289         len = stbuf.st_size;
290
291         fp = fopen(filename, "rb");
292         if (!fp) {
293                 imagex_error_with_errno("Failed to open the file `%s'", filename);
294                 return NULL;
295         }
296
297         buf = malloc(len);
298         if (!buf) {
299                 imagex_error("Failed to allocate buffer of %zu bytes to hold "
300                              "contents of file `%s'", len, filename);
301                 goto out_fclose;
302         }
303         if (fread(buf, 1, len, fp) != len) {
304                 imagex_error_with_errno("Failed to read %lu bytes from the "
305                                         "file `%s'", len, filename);
306                 goto out_free_buf;
307         }
308         *len_ret = len;
309         return buf;
310 out_free_buf:
311         free(buf);
312 out_fclose:
313         fclose(fp);
314         return NULL;
315 }
316
317 static int file_writable(const char *path)
318 {
319         int ret;
320         ret = access(path, F_OK | W_OK);
321         if (ret != 0)
322                 imagex_error_with_errno("Can't modify `%s'", path);
323         return ret;
324 }
325
326 #define TO_PERCENT(numerator, denominator) \
327         (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
328
329 static const char *get_data_type(int ctype)
330 {
331         switch (ctype) {
332         case WIMLIB_COMPRESSION_TYPE_NONE:
333                 return "uncompressed";
334         case WIMLIB_COMPRESSION_TYPE_LZX:
335                 return "LZX-compressed";
336         case WIMLIB_COMPRESSION_TYPE_XPRESS:
337                 return "XPRESS-compressed";
338         }
339         return NULL;
340 }
341
342 static int imagex_progress_func(enum wimlib_progress_msg msg,
343                                 const union wimlib_progress_info *info)
344 {
345         unsigned percent_done;
346         switch (msg) {
347         case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
348                 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
349                                           info->write_streams.total_bytes);
350                 if (info->write_streams.completed_streams == 0) {
351                         const char *data_type;
352
353                         data_type = get_data_type(info->write_streams.compression_type);
354                         printf("Writing %s data using %u thread%s\n",
355                                data_type, info->write_streams.num_threads,
356                                (info->write_streams.num_threads == 1) ? "" : "s");
357                 }
358                 printf("\r%"PRIu64" MiB of %"PRIu64" MiB (uncompressed) "
359                        "written (%u%% done)",
360                        info->write_streams.completed_bytes >> 20,
361                        info->write_streams.total_bytes >> 20,
362                        percent_done);
363                 if (info->write_streams.completed_bytes == info->write_streams.total_bytes)
364                         putchar('\n');
365                 break;
366         case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
367                 printf("Scanning `%s'...\n", info->scan.source);
368                 break;
369         case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
370                 if (info->scan.excluded)
371                         printf("Excluding `%s' from capture\n", info->scan.cur_path);
372                 else
373                         printf("Scanning `%s'\n", info->scan.cur_path);
374                 break;
375         /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
376                 /*break;*/
377         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
378                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
379                                           info->integrity.total_bytes);
380                 printf("\rVerifying integrity of `%s': %"PRIu64" MiB "
381                        "of %"PRIu64" MiB (%u%%) done",
382                        info->integrity.filename,
383                        info->integrity.completed_bytes >> 20,
384                        info->integrity.total_bytes >> 20,
385                        percent_done);
386                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
387                         putchar('\n');
388                 break;
389         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
390                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
391                                           info->integrity.total_bytes);
392                 printf("\rCalculating integrity table for WIM: %"PRIu64" MiB "
393                        "of %"PRIu64" MiB (%u%%) done",
394                        info->integrity.completed_bytes >> 20,
395                        info->integrity.total_bytes >> 20,
396                        percent_done);
397                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
398                         putchar('\n');
399                 break;
400         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
401                 printf("Applying image %d (%s) from `%s' to %s `%s'\n",
402                        info->extract.image,
403                        info->extract.image_name,
404                        info->extract.wimfile_name,
405                        ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
406                                 "NTFS volume" : "directory"),
407                        info->extract.target);
408                 break;
409         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
410                 printf("Done applying WIM image.\n",
411                        info->extract.image);
412                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
413                         printf("Unmounting NTFS volume `%s'...\n",
414                                info->extract.target);
415                 }
416                 break;
417         /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
418                 /*printf("Applying directory structure to %s\n",*/
419                        /*info->extract.target);*/
420                 /*break;*/
421         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
422                 percent_done = TO_PERCENT(info->extract.completed_bytes,
423                                           info->extract.total_bytes);
424                 printf("\rExtracting files: "
425                        "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done",
426                        info->extract.completed_bytes >> 20,
427                        info->extract.total_bytes >> 20,
428                        percent_done);
429                 if (info->extract.completed_bytes == info->extract.total_bytes)
430                         putchar('\n');
431                 break;
432         case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
433                 puts(info->extract.cur_path);
434                 break;
435         case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
436                 percent_done = TO_PERCENT(info->join.completed_bytes,
437                                           info->join.total_bytes);
438                 printf("Writing resources from part %u of %u: "
439                        "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n",
440                        (info->join.completed_parts == info->join.total_parts) ?
441                                 info->join.completed_parts : info->join.completed_parts + 1,
442                        info->join.total_parts,
443                        info->join.completed_bytes >> 20,
444                        info->join.total_bytes >> 20,
445                        percent_done);
446                 break;
447         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
448                 percent_done = TO_PERCENT(info->split.completed_bytes,
449                                           info->split.total_bytes);
450                 printf("Writing `%s': %"PRIu64" MiB of %"PRIu64" MiB (%u%%) written\n",
451                        info->split.part_name,
452                        info->split.completed_bytes >> 20,
453                        info->split.total_bytes >> 20,
454                        percent_done);
455                 break;
456         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
457                 if (info->split.completed_bytes == info->split.total_bytes) {
458                         printf("Finished writing %u split WIM parts\n",
459                                info->split.cur_part_number);
460                 }
461                 break;
462         default:
463                 break;
464         }
465         fflush(stdout);
466         return 0;
467 }
468
469
470 static int open_swms_from_glob(const char *swm_glob,
471                                const char *first_part,
472                                int open_flags,
473                                WIMStruct ***additional_swms_ret,
474                                unsigned *num_additional_swms_ret)
475 {
476         unsigned num_additional_swms = 0;
477         WIMStruct **additional_swms = NULL;
478         glob_t globbuf;
479         int ret;
480
481         ret = glob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
482         if (ret != 0) {
483                 if (ret == GLOB_NOMATCH) {
484                         imagex_error("Found no files for glob \"%s\"",
485                                      swm_glob);
486                 } else {
487                         imagex_error_with_errno("Failed to process glob "
488                                                 "\"%s\"", swm_glob);
489                 }
490                 ret = -1;
491                 goto out;
492         }
493         num_additional_swms = globbuf.gl_pathc;
494         additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
495         if (!additional_swms) {
496                 imagex_error("Out of memory");
497                 ret = -1;
498                 goto out_globfree;
499         }
500         unsigned offset = 0;
501         for (unsigned i = 0; i < num_additional_swms; i++) {
502                 if (strcmp(globbuf.gl_pathv[i], first_part) == 0) {
503                         offset++;
504                         continue;
505                 }
506                 ret = wimlib_open_wim(globbuf.gl_pathv[i],
507                                       open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
508                                       &additional_swms[i - offset],
509                                       imagex_progress_func);
510                 if (ret != 0)
511                         goto out_close_swms;
512         }
513         *additional_swms_ret = additional_swms;
514         *num_additional_swms_ret = num_additional_swms - offset;
515         ret = 0;
516         goto out_globfree;
517 out_close_swms:
518         for (unsigned i = 0; i < num_additional_swms; i++)
519                 wimlib_free(additional_swms[i]);
520         free(additional_swms);
521 out_globfree:
522         globfree(&globbuf);
523 out:
524         return ret;
525 }
526
527
528 static unsigned parse_num_threads(const char *optarg)
529 {
530         char *tmp;
531         unsigned nthreads = strtoul(optarg, &tmp, 10);
532         if (nthreads == UINT_MAX || *tmp || tmp == optarg) {
533                 imagex_error("Number of threads must be a non-negative integer!");
534                 return UINT_MAX;
535         } else {
536                 return nthreads;
537         }
538 }
539
540
541 /* Extract one image, or all images, from a WIM file into a directory. */
542 static int imagex_apply(int argc, const char **argv)
543 {
544         int c;
545         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
546         int image;
547         int num_images;
548         WIMStruct *w;
549         int ret;
550         const char *wimfile;
551         const char *target;
552         const char *image_num_or_name;
553         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
554
555         const char *swm_glob = NULL;
556         WIMStruct **additional_swms = NULL;
557         unsigned num_additional_swms = 0;
558
559         for_opt(c, apply_options) {
560                 switch (c) {
561                 case 'c':
562                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
563                         break;
564                 case 'h':
565                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
566                         break;
567                 case 's':
568                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
569                         break;
570                 case 'v':
571                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
572                         break;
573                 case 'r':
574                         swm_glob = optarg;
575                         break;
576                 default:
577                         usage(APPLY);
578                         return -1;
579                 }
580         }
581         argc -= optind;
582         argv += optind;
583         if (argc != 2 && argc != 3) {
584                 usage(APPLY);
585                 return -1;
586         }
587
588         wimfile = argv[0];
589         if (argc == 2) {
590                 image_num_or_name = "1";
591                 target = argv[1];
592         } else {
593                 image_num_or_name = argv[1];
594                 target = argv[2];
595         }
596
597         ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
598         if (ret != 0)
599                 return ret;
600
601         image = wimlib_resolve_image(w, image_num_or_name);
602         ret = verify_image_exists(image, image_num_or_name, wimfile);
603         if (ret != 0)
604                 goto out;
605
606         num_images = wimlib_get_num_images(w);
607         if (argc == 2 && num_images != 1) {
608                 imagex_error("`%s' contains %d images; Please select one "
609                              "(or all)", wimfile, num_images);
610                 usage(APPLY);
611                 ret = -1;
612                 goto out;
613         }
614
615         if (swm_glob) {
616                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
617                                           &additional_swms,
618                                           &num_additional_swms);
619                 if (ret != 0)
620                         goto out;
621         }
622
623         struct stat stbuf;
624
625         ret = stat(target, &stbuf);
626         if (ret == 0) {
627                 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
628                         extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
629         } else {
630                 if (errno != ENOENT) {
631                         imagex_error_with_errno("Failed to stat `%s'", target);
632                         ret = -1;
633                         goto out;
634                 }
635         }
636
637         ret = wimlib_extract_image(w, image, target, extract_flags,
638                                    additional_swms, num_additional_swms,
639                                    imagex_progress_func);
640 out:
641         wimlib_free(w);
642         if (additional_swms) {
643                 for (unsigned i = 0; i < num_additional_swms; i++)
644                         wimlib_free(additional_swms[i]);
645                 free(additional_swms);
646         }
647         return ret;
648 }
649
650 static int imagex_capture_or_append(int argc, const char **argv)
651 {
652         int c;
653         int open_flags = 0;
654         int add_image_flags = 0;
655         int write_flags = 0;
656         int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
657         const char *source;
658         const char *wimfile;
659         const char *name;
660         const char *desc;
661         const char *flags_element = NULL;
662         const char *config_file = NULL;
663         char *config_str = NULL;
664         size_t config_len = 0;
665         WIMStruct *w = NULL;
666         int ret;
667         int cur_image;
668         char *default_name;
669         int cmd = strcmp(argv[0], "append") ? CAPTURE : APPEND;
670         unsigned num_threads = 0;
671
672         for_opt(c, capture_or_append_options) {
673                 switch (c) {
674                 case 'b':
675                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
676                         break;
677                 case 'c':
678                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
679                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
680                         break;
681                 case 'C':
682                         config_file = optarg;
683                         break;
684                 case 'x':
685                         compression_type = get_compression_type(optarg);
686                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
687                                 return -1;
688                         break;
689                 case 'f':
690                         flags_element = optarg;
691                         break;
692                 case 'L':
693                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
694                         break;
695                 case 'v':
696                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
697                         break;
698                 case 't':
699                         num_threads = parse_num_threads(optarg);
700                         if (num_threads == UINT_MAX)
701                                 return -1;
702                         break;
703                 case 'R':
704                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
705                         break;
706                 default:
707                         usage(cmd);
708                         return -1;
709                 }
710         }
711         argc -= optind;
712         argv += optind;
713         if (argc < 2 || argc > 4) {
714                 usage(cmd);
715                 return -1;
716         }
717         source = argv[0];
718         wimfile = argv[1];
719
720         char source_copy[strlen(source) + 1];
721         memcpy(source_copy, source, strlen(source) + 1);
722         default_name = basename(source_copy);
723
724         name = (argc >= 3) ? argv[2] : default_name;
725         desc = (argc >= 4) ? argv[3] : NULL;
726
727         if (config_file) {
728                 config_str = file_get_contents(config_file, &config_len);
729                 if (!config_str)
730                         return -1;
731         }
732
733         if (cmd == APPEND)
734                 ret = wimlib_open_wim(wimfile, open_flags, &w,
735                                       imagex_progress_func);
736         else
737                 ret = wimlib_create_new_wim(compression_type, &w);
738         if (ret != 0)
739                 goto out;
740
741         struct stat stbuf;
742
743         ret = stat(source, &stbuf);
744         if (ret == 0) {
745                 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
746                         printf("Capturing WIM image from NTFS filesystem on `%s'\n",
747                                source);
748                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
749                 }
750         } else {
751                 if (errno != ENOENT) {
752                         imagex_error_with_errno("Failed to stat `%s'", source);
753                         ret = -1;
754                         goto out;
755                 }
756         }
757
758         ret = wimlib_add_image(w, source, name, config_str, config_len,
759                                add_image_flags, imagex_progress_func);
760
761         if (ret != 0)
762                 goto out;
763         cur_image = wimlib_get_num_images(w);
764         if (desc) {
765                 ret = wimlib_set_image_descripton(w, cur_image, desc);
766                 if (ret != 0)
767                         goto out;
768         }
769         if (flags_element) {
770                 ret = wimlib_set_image_flags(w, cur_image, flags_element);
771                 if (ret != 0)
772                         goto out;
773         }
774         if (cmd == APPEND) {
775                 ret = wimlib_overwrite(w, write_flags, num_threads,
776                                        imagex_progress_func);
777         } else {
778                 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
779                                    num_threads, imagex_progress_func);
780         }
781         if (ret == WIMLIB_ERR_REOPEN)
782                 ret = 0;
783         if (ret != 0)
784                 imagex_error("Failed to write the WIM file `%s'", wimfile);
785 out:
786         wimlib_free(w);
787         free(config_str);
788         return ret;
789 }
790
791 /* Remove image(s) from a WIM. */
792 static int imagex_delete(int argc, const char **argv)
793 {
794         int c;
795         int open_flags = 0;
796         int write_flags = 0;
797         const char *wimfile;
798         const char *image_num_or_name;
799         WIMStruct *w;
800         int image;
801         int ret;
802
803         for_opt(c, delete_options) {
804                 switch (c) {
805                 case 'c':
806                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
807                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
808                         break;
809                 case 's':
810                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
811                         break;
812                 default:
813                         usage(DELETE);
814                         return -1;
815                 }
816         }
817         argc -= optind;
818         argv += optind;
819
820         if (argc != 2) {
821                 if (argc < 1)
822                         imagex_error("Must specify a WIM file");
823                 if (argc < 2)
824                         imagex_error("Must specify an image");
825                 usage(DELETE);
826                 return -1;
827         }
828         wimfile = argv[0];
829         image_num_or_name = argv[1];
830
831         ret = file_writable(wimfile);
832         if (ret != 0)
833                 return ret;
834
835         ret = wimlib_open_wim(wimfile, open_flags, &w,
836                               imagex_progress_func);
837         if (ret != 0)
838                 return ret;
839
840         image = wimlib_resolve_image(w, image_num_or_name);
841
842         ret = verify_image_exists(image, image_num_or_name, wimfile);
843         if (ret != 0)
844                 goto out;
845
846         ret = wimlib_delete_image(w, image);
847         if (ret != 0) {
848                 imagex_error("Failed to delete image from `%s'", wimfile);
849                 goto out;
850         }
851
852         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
853         if (ret == WIMLIB_ERR_REOPEN)
854                 ret = 0;
855         if (ret != 0) {
856                 imagex_error("Failed to write the file `%s' with image "
857                              "deleted", wimfile);
858         }
859 out:
860         wimlib_free(w);
861         return ret;
862 }
863
864 /* Print the files contained in an image(s) in a WIM file. */
865 static int imagex_dir(int argc, const char **argv)
866 {
867         const char *wimfile;
868         WIMStruct *w;
869         int image;
870         int ret;
871         int num_images;
872
873         if (argc < 2) {
874                 imagex_error("Must specify a WIM file");
875                 usage(DIR);
876                 return -1;
877         }
878         if (argc > 3) {
879                 imagex_error("Too many arguments");
880                 usage(DIR);
881                 return -1;
882         }
883
884         wimfile = argv[1];
885         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
886                               imagex_progress_func);
887         if (ret != 0)
888                 return ret;
889
890         if (argc == 3) {
891                 image = wimlib_resolve_image(w, argv[2]);
892                 ret = verify_image_exists(image, argv[2], wimfile);
893                 if (ret != 0)
894                         goto out;
895         } else {
896                 /* Image was not specified.  If the WIM only contains one image,
897                  * choose that one; otherwise, print an error. */
898                 num_images = wimlib_get_num_images(w);
899                 if (num_images != 1) {
900                         imagex_error("The file `%s' contains %d images; Please "
901                                      "select one.", wimfile, num_images);
902                         usage(DIR);
903                         ret = -1;
904                         goto out;
905                 }
906                 image = 1;
907         }
908
909         ret = wimlib_print_files(w, image);
910 out:
911         wimlib_free(w);
912         return ret;
913 }
914
915 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
916  * WIM file. */
917 static int imagex_export(int argc, const char **argv)
918 {
919         int c;
920         int open_flags = 0;
921         int export_flags = 0;
922         int write_flags = 0;
923         int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
924         bool compression_type_specified = false;
925         const char *src_wimfile;
926         const char *src_image_num_or_name;
927         const char *dest_wimfile;
928         const char *dest_name;
929         const char *dest_desc;
930         WIMStruct *src_w = NULL;
931         WIMStruct *dest_w = NULL;
932         int ret;
933         int image;
934         struct stat stbuf;
935         bool wim_is_new;
936         const char *swm_glob = NULL;
937         WIMStruct **additional_swms = NULL;
938         unsigned num_additional_swms = 0;
939         unsigned num_threads = 0;
940
941         for_opt(c, export_options) {
942                 switch (c) {
943                 case 'b':
944                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
945                         break;
946                 case 'c':
947                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
948                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
949                         break;
950                 case 'x':
951                         compression_type = get_compression_type(optarg);
952                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
953                                 return -1;
954                         compression_type_specified = true;
955                         break;
956                 case 'r':
957                         swm_glob = optarg;
958                         break;
959                 case 't':
960                         num_threads = parse_num_threads(optarg);
961                         if (num_threads == UINT_MAX)
962                                 return -1;
963                         break;
964                 case 'R':
965                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
966                         break;
967                 default:
968                         usage(EXPORT);
969                         return -1;
970                 }
971         }
972         argc -= optind;
973         argv += optind;
974         if (argc < 3 || argc > 5) {
975                 usage(EXPORT);
976                 return -1;
977         }
978         src_wimfile           = argv[0];
979         src_image_num_or_name = argv[1];
980         dest_wimfile          = argv[2];
981         dest_name             = (argc >= 4) ? argv[3] : NULL;
982         dest_desc             = (argc >= 5) ? argv[4] : NULL;
983         ret = wimlib_open_wim(src_wimfile,
984                               open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
985                               imagex_progress_func);
986         if (ret != 0)
987                 return ret;
988
989         /* Determine if the destination is an existing file or not.
990          * If so, we try to append the exported image(s) to it; otherwise, we
991          * create a new WIM containing the exported image(s). */
992         if (stat(dest_wimfile, &stbuf) == 0) {
993                 int dest_ctype;
994
995                 wim_is_new = false;
996                 /* Destination file exists. */
997                 if (!S_ISREG(stbuf.st_mode) && !S_ISLNK(stbuf.st_mode)) {
998                         imagex_error("`%s' is not a regular file",
999                                         dest_wimfile);
1000                         ret = -1;
1001                         goto out;
1002                 }
1003                 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
1004                                       imagex_progress_func);
1005                 if (ret != 0)
1006                         goto out;
1007
1008                 ret = file_writable(dest_wimfile);
1009                 if (ret != 0)
1010                         return ret;
1011
1012                 dest_ctype = wimlib_get_compression_type(dest_w);
1013                 if (compression_type_specified
1014                     && compression_type != dest_ctype)
1015                 {
1016                         imagex_error("Cannot specify a compression type that is "
1017                                      "not the same as that used in the "
1018                                      "destination WIM");
1019                         ret = -1;
1020                         goto out;
1021                 }
1022                 compression_type = dest_ctype;
1023         } else {
1024                 wim_is_new = true;
1025                 /* dest_wimfile is not an existing file, so create a new WIM. */
1026                 if (!compression_type_specified)
1027                         compression_type = wimlib_get_compression_type(src_w);
1028                 if (errno == ENOENT) {
1029                         ret = wimlib_create_new_wim(compression_type, &dest_w);
1030                         if (ret != 0)
1031                                 goto out;
1032                 } else {
1033                         imagex_error_with_errno("Cannot stat file `%s'",
1034                                                 dest_wimfile);
1035                         ret = -1;
1036                         goto out;
1037                 }
1038         }
1039
1040         image = wimlib_resolve_image(src_w, src_image_num_or_name);
1041         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1042         if (ret != 0)
1043                 goto out;
1044
1045         if (swm_glob) {
1046                 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1047                                           &additional_swms,
1048                                           &num_additional_swms);
1049                 if (ret != 0)
1050                         goto out;
1051         }
1052
1053         ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1054                                   export_flags, additional_swms,
1055                                   num_additional_swms, imagex_progress_func);
1056         if (ret != 0)
1057                 goto out;
1058
1059
1060         if (wim_is_new)
1061                 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1062                                    write_flags, num_threads,
1063                                    imagex_progress_func);
1064         else
1065                 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1066                                        imagex_progress_func);
1067 out:
1068         if (ret == WIMLIB_ERR_REOPEN)
1069                 ret = 0;
1070         wimlib_free(src_w);
1071         wimlib_free(dest_w);
1072         if (additional_swms) {
1073                 for (unsigned i = 0; i < num_additional_swms; i++)
1074                         wimlib_free(additional_swms[i]);
1075                 free(additional_swms);
1076         }
1077         return ret;
1078 }
1079
1080 /* Prints information about a WIM file; also can mark an image as bootable,
1081  * change the name of an image, or change the description of an image. */
1082 static int imagex_info(int argc, const char **argv)
1083 {
1084         int c;
1085         bool boot         = false;
1086         bool check        = false;
1087         bool header       = false;
1088         bool lookup_table = false;
1089         bool xml          = false;
1090         bool metadata     = false;
1091         bool short_header = true;
1092         const char *xml_out_file = NULL;
1093         const char *wimfile;
1094         const char *image_num_or_name = "all";
1095         const char *new_name = NULL;
1096         const char *new_desc = NULL;
1097         WIMStruct *w;
1098         FILE *fp;
1099         int image;
1100         int ret;
1101         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1102         int part_number;
1103         int total_parts;
1104
1105         for_opt(c, info_options) {
1106                 switch (c) {
1107                 case 'b':
1108                         boot = true;
1109                         break;
1110                 case 'c':
1111                         check = true;
1112                         break;
1113                 case 'h':
1114                         header = true;
1115                         short_header = false;
1116                         break;
1117                 case 'l':
1118                         lookup_table = true;
1119                         short_header = false;
1120                         break;
1121                 case 'x':
1122                         xml = true;
1123                         short_header = false;
1124                         break;
1125                 case 'X':
1126                         xml_out_file = optarg;
1127                         short_header = false;
1128                         break;
1129                 case 'm':
1130                         metadata = true;
1131                         short_header = false;
1132                         break;
1133                 default:
1134                         usage(INFO);
1135                         return -1;
1136                 }
1137         }
1138
1139         argc -= optind;
1140         argv += optind;
1141         if (argc == 0 || argc > 4) {
1142                 usage(INFO);
1143                 return -1;
1144         }
1145         wimfile = argv[0];
1146         if (argc > 1) {
1147                 image_num_or_name = argv[1];
1148                 if (argc > 2) {
1149                         new_name = argv[2];
1150                         if (argc > 3) {
1151                                 new_desc = argv[3];
1152                         }
1153                 }
1154         }
1155
1156         if (check)
1157                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1158
1159         ret = wimlib_open_wim(wimfile, open_flags, &w,
1160                               imagex_progress_func);
1161         if (ret != 0)
1162                 return ret;
1163
1164         part_number = wimlib_get_part_number(w, &total_parts);
1165
1166         image = wimlib_resolve_image(w, image_num_or_name);
1167         if (image == WIMLIB_NO_IMAGE && strcmp(image_num_or_name, "0") != 0) {
1168                 imagex_error("The image `%s' does not exist",
1169                                                 image_num_or_name);
1170                 if (boot)
1171                         imagex_error("If you would like to set the boot "
1172                                      "index to 0, specify image \"0\" with "
1173                                      "the --boot flag.");
1174                 ret = WIMLIB_ERR_INVALID_IMAGE;
1175                 goto out;
1176         }
1177
1178         if (image == WIMLIB_ALL_IMAGES && wimlib_get_num_images(w) > 1) {
1179                 if (boot) {
1180                         imagex_error("Cannot specify the --boot flag "
1181                                      "without specifying a specific "
1182                                      "image in a multi-image WIM");
1183                         ret = WIMLIB_ERR_INVALID_IMAGE;
1184                         goto out;
1185                 }
1186                 if (new_name) {
1187                         imagex_error("Cannot specify the NEW_NAME "
1188                                      "without specifying a specific "
1189                                      "image in a multi-image WIM");
1190                         ret = WIMLIB_ERR_INVALID_IMAGE;
1191                         goto out;
1192                 }
1193         }
1194
1195         /* Operations that print information are separated from operations that
1196          * recreate the WIM file. */
1197         if (!new_name && !boot) {
1198
1199                 /* Read-only operations */
1200
1201                 if (image == WIMLIB_NO_IMAGE) {
1202                         imagex_error("`%s' is not a valid image",
1203                                      image_num_or_name);
1204                         ret = WIMLIB_ERR_INVALID_IMAGE;
1205                         goto out;
1206                 }
1207
1208                 if (image == WIMLIB_ALL_IMAGES && short_header)
1209                         wimlib_print_wim_information(w);
1210
1211                 if (header)
1212                         wimlib_print_header(w);
1213
1214                 if (lookup_table) {
1215                         if (total_parts != 1) {
1216                                 printf("Warning: Only showing the lookup table "
1217                                        "for part %d of a %d-part WIM.\n",
1218                                        part_number, total_parts);
1219                         }
1220                         wimlib_print_lookup_table(w);
1221                 }
1222
1223                 if (xml) {
1224                         ret = wimlib_extract_xml_data(w, stdout);
1225                         if (ret != 0)
1226                                 goto out;
1227                 }
1228
1229                 if (xml_out_file) {
1230                         fp = fopen(xml_out_file, "wb");
1231                         if (!fp) {
1232                                 imagex_error_with_errno("Failed to open the "
1233                                                         "file `%s' for "
1234                                                         "writing ",
1235                                                         xml_out_file);
1236                                 goto out;
1237                         }
1238                         ret = wimlib_extract_xml_data(w, fp);
1239                         if (fclose(fp) != 0) {
1240                                 imagex_error("Failed to close the file `%s'",
1241                                              xml_out_file);
1242                                 goto out;
1243                         }
1244
1245                         if (ret != 0)
1246                                 goto out;
1247                 }
1248
1249                 if (short_header)
1250                         wimlib_print_available_images(w, image);
1251
1252                 if (metadata) {
1253                         ret = wimlib_print_metadata(w, image);
1254                         if (ret != 0)
1255                                 goto out;
1256                 }
1257         } else {
1258
1259                 /* Modification operations */
1260                 if (total_parts != 1) {
1261                         imagex_error("Modifying a split WIM is not supported.");
1262                         return -1;
1263                 }
1264                 if (image == WIMLIB_ALL_IMAGES)
1265                         image = 1;
1266
1267                 if (image == WIMLIB_NO_IMAGE && new_name) {
1268                         imagex_error("Cannot specify new_name (`%s') when "
1269                                      "using image 0", new_name);
1270                         return -1;
1271                 }
1272
1273                 if (boot) {
1274                         if (image == wimlib_get_boot_idx(w)) {
1275                                 printf("Image %d is already marked as "
1276                                        "bootable.\n", image);
1277                                 boot = false;
1278                         } else {
1279                                 printf("Marking image %d as bootable.\n",
1280                                        image);
1281                                 wimlib_set_boot_idx(w, image);
1282                         }
1283                 }
1284                 if (new_name) {
1285                         if (strcmp(wimlib_get_image_name(w, image),
1286                                                 new_name) == 0) {
1287                                 printf("Image %d is already named \"%s\".\n",
1288                                        image, new_name);
1289                                 new_name = NULL;
1290                         } else {
1291                                 printf("Changing the name of image %d to "
1292                                        "\"%s\".\n", image, new_name);
1293                                 ret = wimlib_set_image_name(w, image, new_name);
1294                                 if (ret != 0)
1295                                         goto out;
1296                         }
1297                 }
1298                 if (new_desc) {
1299                         const char *old_desc;
1300                         old_desc = wimlib_get_image_description(w, image);
1301                         if (old_desc && strcmp(old_desc, new_desc) == 0) {
1302                                 printf("The description of image %d is already "
1303                                        "\"%s\".\n", image, new_desc);
1304                                 new_desc = NULL;
1305                         } else {
1306                                 printf("Changing the description of image %d "
1307                                        "to \"%s\".\n", image, new_desc);
1308                                 ret = wimlib_set_image_descripton(w, image,
1309                                                                   new_desc);
1310                                 if (ret != 0)
1311                                         goto out;
1312                         }
1313                 }
1314
1315                 /* Only call wimlib_overwrite() if something actually needs to
1316                  * be changed. */
1317                 if (boot || new_name || new_desc ||
1318                                 check != wimlib_has_integrity_table(w)) {
1319
1320                         ret = file_writable(wimfile);
1321                         if (ret != 0)
1322                                 return ret;
1323
1324                         int write_flags;
1325                         if (check) {
1326                                 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1327                         } else {
1328                                 write_flags = 0;
1329                         }
1330
1331                         ret = wimlib_overwrite(w, write_flags, 1,
1332                                                imagex_progress_func);
1333                         if (ret == WIMLIB_ERR_REOPEN)
1334                                 ret = 0;
1335                 } else {
1336                         printf("The file `%s' was not modified because nothing "
1337                                         "needed to be done.\n", wimfile);
1338                         ret = 0;
1339                 }
1340         }
1341 out:
1342         wimlib_free(w);
1343         return ret;
1344 }
1345
1346 /* Join split WIMs into one part WIM */
1347 static int imagex_join(int argc, const char **argv)
1348 {
1349         int c;
1350         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1351         int wim_write_flags = 0;
1352         const char *output_path;
1353
1354         for_opt(c, join_options) {
1355                 switch (c) {
1356                 case 'c':
1357                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1358                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1359                         break;
1360                 default:
1361                         goto err;
1362                 }
1363         }
1364         argc -= optind;
1365         argv += optind;
1366
1367         if (argc < 2) {
1368                 imagex_error("Must specify one or more split WIM (.swm) parts "
1369                              "to join");
1370                 goto err;
1371         }
1372         output_path = argv[0];
1373         return wimlib_join(++argv, --argc, output_path, swm_open_flags,
1374                            wim_write_flags, imagex_progress_func);
1375 err:
1376         usage(JOIN);
1377         return -1;
1378 }
1379
1380 /* Mounts an image using a FUSE mount. */
1381 static int imagex_mount_rw_or_ro(int argc, const char **argv)
1382 {
1383         int c;
1384         int mount_flags = 0;
1385         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1386         const char *wimfile;
1387         const char *dir;
1388         WIMStruct *w;
1389         int image;
1390         int num_images;
1391         int ret;
1392         const char *swm_glob = NULL;
1393         WIMStruct **additional_swms = NULL;
1394         unsigned num_additional_swms = 0;
1395         const char *staging_dir = NULL;
1396
1397         if (strcmp(argv[0], "mountrw") == 0)
1398                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
1399
1400         for_opt(c, mount_options) {
1401                 switch (c) {
1402                 case 'c':
1403                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1404                         break;
1405                 case 'd':
1406                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
1407                         break;
1408                 case 's':
1409                         if (strcasecmp(optarg, "none") == 0)
1410                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
1411                         else if (strcasecmp(optarg, "xattr") == 0)
1412                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1413                         else if (strcasecmp(optarg, "windows") == 0)
1414                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
1415                         else {
1416                                 imagex_error("Unknown stream interface \"%s\"", optarg);
1417                                 goto mount_usage;
1418                         }
1419                         break;
1420                 case 'r':
1421                         swm_glob = optarg;
1422                         break;
1423                 case 'D':
1424                         staging_dir = optarg;
1425                         break;
1426                 default:
1427                         goto mount_usage;
1428                 }
1429         }
1430         argc -= optind;
1431         argv += optind;
1432         if (argc != 2 && argc != 3)
1433                 goto mount_usage;
1434
1435         wimfile = argv[0];
1436
1437         ret = wimlib_open_wim(wimfile, open_flags, &w,
1438                               imagex_progress_func);
1439         if (ret != 0)
1440                 return ret;
1441
1442         if (swm_glob) {
1443                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1444                                           &additional_swms,
1445                                           &num_additional_swms);
1446                 if (ret != 0)
1447                         goto out;
1448         }
1449
1450         if (argc == 2) {
1451                 image = 1;
1452                 num_images = wimlib_get_num_images(w);
1453                 if (num_images != 1) {
1454                         imagex_error("The file `%s' contains %d images; Please "
1455                                      "select one.", wimfile, num_images);
1456                         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
1457                                         ? MOUNTRW : MOUNT);
1458                         ret = -1;
1459                         goto out;
1460                 }
1461                 dir = argv[1];
1462         } else {
1463                 image = wimlib_resolve_image(w, argv[1]);
1464                 dir = argv[2];
1465                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
1466                 if (ret != 0)
1467                         goto out;
1468         }
1469
1470         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1471                 ret = file_writable(wimfile);
1472                 if (ret != 0)
1473                         return ret;
1474         }
1475
1476         ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
1477                                  num_additional_swms, staging_dir);
1478         if (ret != 0) {
1479                 imagex_error("Failed to mount image %d from `%s' on `%s'",
1480                              image, wimfile, dir);
1481
1482         }
1483 out:
1484         wimlib_free(w);
1485         if (additional_swms) {
1486                 for (unsigned i = 0; i < num_additional_swms; i++)
1487                         wimlib_free(additional_swms[i]);
1488                 free(additional_swms);
1489         }
1490         return ret;
1491 mount_usage:
1492         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
1493                         ? MOUNTRW : MOUNT);
1494         return -1;
1495 }
1496
1497 static int imagex_optimize(int argc, const char **argv)
1498 {
1499         int c;
1500         int open_flags = 0;
1501         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
1502         int ret;
1503         WIMStruct *w;
1504         const char *wimfile;
1505         off_t old_size;
1506         off_t new_size;
1507
1508         for_opt(c, optimize_options) {
1509                 switch (c) {
1510                 case 'c':
1511                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1512                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1513                         break;
1514                 case 'r':
1515                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1516                         break;
1517                 default:
1518                         usage(OPTIMIZE);
1519                         return -1;
1520                 }
1521         }
1522         argc -= optind;
1523         argv += optind;
1524
1525         if (argc != 1) {
1526                 usage(OPTIMIZE);
1527                 return -1;
1528         }
1529
1530         wimfile = argv[0];
1531
1532         ret = wimlib_open_wim(wimfile, open_flags, &w,
1533                               imagex_progress_func);
1534         if (ret != 0)
1535                 return ret;
1536
1537         old_size = file_get_size(argv[0]);
1538         printf("`%s' original size: ", wimfile);
1539         if (old_size == -1)
1540                 puts("Unknown");
1541         else
1542                 printf("%"PRIu64" KiB\n", old_size >> 10);
1543
1544         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1545
1546         if (ret == 0) {
1547                 new_size = file_get_size(argv[0]);
1548                 printf("`%s' optimized size: ", wimfile);
1549                 if (new_size == -1)
1550                         puts("Unknown");
1551                 else
1552                         printf("%"PRIu64" KiB\n", new_size >> 10);
1553
1554                 fputs("Space saved: ", stdout);
1555                 if (new_size != -1 && old_size != -1) {
1556                         printf("%lld KiB\n",
1557                                ((long long)old_size - (long long)new_size) >> 10);
1558                 } else {
1559                         puts("Unknown");
1560                 }
1561         }
1562
1563         wimlib_free(w);
1564         return ret;
1565 }
1566
1567 /* Split a WIM into a spanned set */
1568 static int imagex_split(int argc, const char **argv)
1569 {
1570         int c;
1571         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1572         int write_flags = 0;
1573         unsigned long part_size;
1574         char *tmp;
1575         int ret;
1576         WIMStruct *w;
1577
1578         for_opt(c, split_options) {
1579                 switch (c) {
1580                 case 'c':
1581                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1582                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1583                         break;
1584                 default:
1585                         usage(SPLIT);
1586                         return -1;
1587                 }
1588         }
1589         argc -= optind;
1590         argv += optind;
1591
1592         if (argc != 3) {
1593                 usage(SPLIT);
1594                 return -1;
1595         }
1596         part_size = strtod(argv[2], &tmp) * (1 << 20);
1597         if (tmp == argv[2] || *tmp) {
1598                 imagex_error("Invalid part size \"%s\"", argv[2]);
1599                 imagex_error("The part size must be an integer or floating-point number of megabytes.");
1600                 return -1;
1601         }
1602         ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
1603         if (ret != 0)
1604                 return ret;
1605         ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
1606         wimlib_free(w);
1607         return ret;
1608 }
1609
1610 /* Unmounts an image. */
1611 static int imagex_unmount(int argc, const char **argv)
1612 {
1613         int c;
1614         int unmount_flags = 0;
1615         int ret;
1616
1617         for_opt(c, unmount_options) {
1618                 switch (c) {
1619                 case 'c':
1620                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
1621                         break;
1622                 case 'C':
1623                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
1624                         break;
1625                 default:
1626                         usage(UNMOUNT);
1627                         return -1;
1628                 }
1629         }
1630         argc -= optind;
1631         argv += optind;
1632         if (argc != 1) {
1633                 usage(UNMOUNT);
1634                 return -1;
1635         }
1636
1637         ret = wimlib_unmount_image(argv[0], unmount_flags,
1638                                    imagex_progress_func);
1639         if (ret != 0)
1640                 imagex_error("Failed to unmount `%s'", argv[0]);
1641         return ret;
1642 }
1643
1644 struct imagex_command {
1645         const char *name;
1646         int (*func)(int , const char **);
1647         int cmd;
1648 };
1649
1650
1651 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
1652                 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
1653
1654 static const struct imagex_command imagex_commands[] = {
1655         {"append",  imagex_capture_or_append, APPEND},
1656         {"apply",   imagex_apply,             APPLY},
1657         {"capture", imagex_capture_or_append, CAPTURE},
1658         {"delete",  imagex_delete,            DELETE},
1659         {"dir",     imagex_dir,               DIR},
1660         {"export",  imagex_export,            EXPORT},
1661         {"info",    imagex_info,              INFO},
1662         {"join",    imagex_join,              JOIN},
1663         {"mount",   imagex_mount_rw_or_ro,    MOUNT},
1664         {"mountrw", imagex_mount_rw_or_ro,    MOUNTRW},
1665         {"optimize",imagex_optimize,          OPTIMIZE},
1666         {"split",   imagex_split,             SPLIT},
1667         {"unmount", imagex_unmount,           UNMOUNT},
1668 };
1669
1670 static void version()
1671 {
1672         static const char *s =
1673         "imagex (" PACKAGE ") " PACKAGE_VERSION "\n"
1674         "Copyright (C) 2012 Eric Biggers\n"
1675         "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
1676         "This is free software: you are free to change and redistribute it.\n"
1677         "There is NO WARRANTY, to the extent permitted by law.\n"
1678         "\n"
1679         "Report bugs to "PACKAGE_BUGREPORT".\n";
1680         fputs(s, stdout);
1681 }
1682
1683
1684 static void help_or_version(int argc, const char **argv)
1685 {
1686         int i;
1687         const char *p;
1688         const struct imagex_command *cmd;
1689
1690         for (i = 1; i < argc; i++) {
1691                 p = argv[i];
1692                 if (*p == '-')
1693                         p++;
1694                 else
1695                         continue;
1696                 if (*p == '-')
1697                         p++;
1698                 if (strcmp(p, "help") == 0) {
1699                         for_imagex_command(cmd) {
1700                                 if (strcmp(cmd->name, argv[1]) == 0) {
1701                                         usage(cmd->cmd);
1702                                         exit(0);
1703                                 }
1704                         }
1705                         usage_all();
1706                         exit(0);
1707                 }
1708                 if (strcmp(p, "version") == 0) {
1709                         version();
1710                         exit(0);
1711                 }
1712         }
1713 }
1714
1715
1716 static void usage(int cmd_type)
1717 {
1718         const struct imagex_command *cmd;
1719         printf("Usage: %s", usage_strings[cmd_type]);
1720         for_imagex_command(cmd) {
1721                 if (cmd->cmd == cmd_type)
1722                         printf("\nTry `man imagex-%s' for more details.\n",
1723                                cmd->name);
1724         }
1725 }
1726
1727 static void usage_all()
1728 {
1729         puts("IMAGEX: Usage:");
1730         for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
1731                 printf("    %s", usage_strings[i]);
1732         static const char *extra =
1733 "    imagex --help\n"
1734 "    imagex --version\n"
1735 "\n"
1736 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
1737 "\n"
1738 "    Try `man imagex' for more information.\n"
1739         ;
1740         fputs(extra, stdout);
1741 }
1742
1743
1744 int main(int argc, const char **argv)
1745 {
1746         const struct imagex_command *cmd;
1747         int ret;
1748
1749         if (argc < 2) {
1750                 imagex_error("No command specified");
1751                 usage_all();
1752                 return 1;
1753         }
1754
1755         help_or_version(argc, argv);
1756         argc--;
1757         argv++;
1758
1759         wimlib_set_print_errors(true);
1760
1761         for_imagex_command(cmd) {
1762                 if (strcmp(cmd->name, *argv) == 0) {
1763                         ret = cmd->func(argc, argv);
1764                         if (ret > 0) {
1765                                 imagex_error("Exiting with error code %d:\n"
1766                                              "       %s.", ret,
1767                                              wimlib_get_error_string(ret));
1768                                 if (ret == WIMLIB_ERR_NTFS_3G)
1769                                         imagex_error_with_errno("errno");
1770                         }
1771                         return ret;
1772                 }
1773         }
1774
1775         imagex_error("Unrecognized command: `%s'", argv[0]);
1776         usage_all();
1777         return 1;
1778 }