]> wimlib.net Git - wimlib/blob - programs/imagex.c
f7d8b66558389d97e16b7b16086588d1ebf37a34
[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                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
412                         printf("Unmounting NTFS volume `%s'...\n",
413                                info->extract.target);
414                 }
415                 break;
416         /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
417                 /*printf("Applying directory structure to %s\n",*/
418                        /*info->extract.target);*/
419                 /*break;*/
420         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
421                 percent_done = TO_PERCENT(info->extract.completed_bytes,
422                                           info->extract.total_bytes);
423                 printf("\rExtracting files: "
424                        "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done",
425                        info->extract.completed_bytes >> 20,
426                        info->extract.total_bytes >> 20,
427                        percent_done);
428                 if (info->extract.completed_bytes == info->extract.total_bytes)
429                         putchar('\n');
430                 break;
431         case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
432                 puts(info->extract.cur_path);
433                 break;
434         case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
435                 percent_done = TO_PERCENT(info->join.completed_bytes,
436                                           info->join.total_bytes);
437                 printf("Writing resources from part %u of %u: "
438                        "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n",
439                        (info->join.completed_parts == info->join.total_parts) ?
440                                 info->join.completed_parts : info->join.completed_parts + 1,
441                        info->join.total_parts,
442                        info->join.completed_bytes >> 20,
443                        info->join.total_bytes >> 20,
444                        percent_done);
445                 break;
446         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
447                 percent_done = TO_PERCENT(info->split.completed_bytes,
448                                           info->split.total_bytes);
449                 printf("Writing `%s': %"PRIu64" MiB of %"PRIu64" MiB (%u%%) written\n",
450                        info->split.part_name,
451                        info->split.completed_bytes >> 20,
452                        info->split.total_bytes >> 20,
453                        percent_done);
454                 break;
455         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
456                 if (info->split.completed_bytes == info->split.total_bytes) {
457                         printf("Finished writing %u split WIM parts\n",
458                                info->split.cur_part_number);
459                 }
460                 break;
461         default:
462                 break;
463         }
464         fflush(stdout);
465         return 0;
466 }
467
468
469 static int open_swms_from_glob(const char *swm_glob,
470                                const char *first_part,
471                                int open_flags,
472                                WIMStruct ***additional_swms_ret,
473                                unsigned *num_additional_swms_ret)
474 {
475         unsigned num_additional_swms = 0;
476         WIMStruct **additional_swms = NULL;
477         glob_t globbuf;
478         int ret;
479
480         ret = glob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
481         if (ret != 0) {
482                 if (ret == GLOB_NOMATCH) {
483                         imagex_error("Found no files for glob \"%s\"",
484                                      swm_glob);
485                 } else {
486                         imagex_error_with_errno("Failed to process glob "
487                                                 "\"%s\"", swm_glob);
488                 }
489                 ret = -1;
490                 goto out;
491         }
492         num_additional_swms = globbuf.gl_pathc;
493         additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
494         if (!additional_swms) {
495                 imagex_error("Out of memory");
496                 ret = -1;
497                 goto out_globfree;
498         }
499         unsigned offset = 0;
500         for (unsigned i = 0; i < num_additional_swms; i++) {
501                 if (strcmp(globbuf.gl_pathv[i], first_part) == 0) {
502                         offset++;
503                         continue;
504                 }
505                 ret = wimlib_open_wim(globbuf.gl_pathv[i],
506                                       open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
507                                       &additional_swms[i - offset],
508                                       imagex_progress_func);
509                 if (ret != 0)
510                         goto out_close_swms;
511         }
512         *additional_swms_ret = additional_swms;
513         *num_additional_swms_ret = num_additional_swms - offset;
514         ret = 0;
515         goto out_globfree;
516 out_close_swms:
517         for (unsigned i = 0; i < num_additional_swms; i++)
518                 wimlib_free(additional_swms[i]);
519         free(additional_swms);
520 out_globfree:
521         globfree(&globbuf);
522 out:
523         return ret;
524 }
525
526
527 static unsigned parse_num_threads(const char *optarg)
528 {
529         char *tmp;
530         unsigned nthreads = strtoul(optarg, &tmp, 10);
531         if (nthreads == UINT_MAX || *tmp || tmp == optarg) {
532                 imagex_error("Number of threads must be a non-negative integer!");
533                 return UINT_MAX;
534         } else {
535                 return nthreads;
536         }
537 }
538
539
540 /* Extract one image, or all images, from a WIM file into a directory. */
541 static int imagex_apply(int argc, const char **argv)
542 {
543         int c;
544         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
545         int image;
546         int num_images;
547         WIMStruct *w;
548         int ret;
549         const char *wimfile;
550         const char *target;
551         const char *image_num_or_name;
552         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
553
554         const char *swm_glob = NULL;
555         WIMStruct **additional_swms = NULL;
556         unsigned num_additional_swms = 0;
557
558         for_opt(c, apply_options) {
559                 switch (c) {
560                 case 'c':
561                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
562                         break;
563                 case 'h':
564                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
565                         break;
566                 case 's':
567                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
568                         break;
569                 case 'v':
570                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
571                         break;
572                 case 'r':
573                         swm_glob = optarg;
574                         break;
575                 default:
576                         usage(APPLY);
577                         return -1;
578                 }
579         }
580         argc -= optind;
581         argv += optind;
582         if (argc != 2 && argc != 3) {
583                 usage(APPLY);
584                 return -1;
585         }
586
587         wimfile = argv[0];
588         if (argc == 2) {
589                 image_num_or_name = "1";
590                 target = argv[1];
591         } else {
592                 image_num_or_name = argv[1];
593                 target = argv[2];
594         }
595
596         ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
597         if (ret != 0)
598                 return ret;
599
600         image = wimlib_resolve_image(w, image_num_or_name);
601         ret = verify_image_exists(image, image_num_or_name, wimfile);
602         if (ret != 0)
603                 goto out;
604
605         num_images = wimlib_get_num_images(w);
606         if (argc == 2 && num_images != 1) {
607                 imagex_error("`%s' contains %d images; Please select one "
608                              "(or all)", wimfile, num_images);
609                 usage(APPLY);
610                 ret = -1;
611                 goto out;
612         }
613
614         if (swm_glob) {
615                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
616                                           &additional_swms,
617                                           &num_additional_swms);
618                 if (ret != 0)
619                         goto out;
620         }
621
622         struct stat stbuf;
623
624         ret = stat(target, &stbuf);
625         if (ret == 0) {
626                 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
627                         extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
628         } else {
629                 if (errno != ENOENT) {
630                         imagex_error_with_errno("Failed to stat `%s'", target);
631                         ret = -1;
632                         goto out;
633                 }
634         }
635
636         ret = wimlib_extract_image(w, image, target, extract_flags,
637                                    additional_swms, num_additional_swms,
638                                    imagex_progress_func);
639 out:
640         wimlib_free(w);
641         if (additional_swms) {
642                 for (unsigned i = 0; i < num_additional_swms; i++)
643                         wimlib_free(additional_swms[i]);
644                 free(additional_swms);
645         }
646         return ret;
647 }
648
649 static int imagex_capture_or_append(int argc, const char **argv)
650 {
651         int c;
652         int open_flags = 0;
653         int add_image_flags = 0;
654         int write_flags = 0;
655         int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
656         const char *source;
657         const char *wimfile;
658         const char *name;
659         const char *desc;
660         const char *flags_element = NULL;
661         const char *config_file = NULL;
662         char *config_str = NULL;
663         size_t config_len = 0;
664         WIMStruct *w = NULL;
665         int ret;
666         int cur_image;
667         char *default_name;
668         int cmd = strcmp(argv[0], "append") ? CAPTURE : APPEND;
669         unsigned num_threads = 0;
670
671         for_opt(c, capture_or_append_options) {
672                 switch (c) {
673                 case 'b':
674                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
675                         break;
676                 case 'c':
677                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
678                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
679                         break;
680                 case 'C':
681                         config_file = optarg;
682                         break;
683                 case 'x':
684                         compression_type = get_compression_type(optarg);
685                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
686                                 return -1;
687                         break;
688                 case 'f':
689                         flags_element = optarg;
690                         break;
691                 case 'L':
692                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
693                         break;
694                 case 'v':
695                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
696                         break;
697                 case 't':
698                         num_threads = parse_num_threads(optarg);
699                         if (num_threads == UINT_MAX)
700                                 return -1;
701                         break;
702                 case 'R':
703                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
704                         break;
705                 default:
706                         usage(cmd);
707                         return -1;
708                 }
709         }
710         argc -= optind;
711         argv += optind;
712         if (argc < 2 || argc > 4) {
713                 usage(cmd);
714                 return -1;
715         }
716         source = argv[0];
717         wimfile = argv[1];
718
719         char source_copy[strlen(source) + 1];
720         memcpy(source_copy, source, strlen(source) + 1);
721         default_name = basename(source_copy);
722
723         name = (argc >= 3) ? argv[2] : default_name;
724         desc = (argc >= 4) ? argv[3] : NULL;
725
726         if (config_file) {
727                 config_str = file_get_contents(config_file, &config_len);
728                 if (!config_str)
729                         return -1;
730         }
731
732         if (cmd == APPEND)
733                 ret = wimlib_open_wim(wimfile, open_flags, &w,
734                                       imagex_progress_func);
735         else
736                 ret = wimlib_create_new_wim(compression_type, &w);
737         if (ret != 0)
738                 goto out;
739
740         struct stat stbuf;
741
742         ret = stat(source, &stbuf);
743         if (ret == 0) {
744                 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
745                         printf("Capturing WIM image from NTFS filesystem on `%s'\n",
746                                source);
747                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
748                 }
749         } else {
750                 if (errno != ENOENT) {
751                         imagex_error_with_errno("Failed to stat `%s'", source);
752                         ret = -1;
753                         goto out;
754                 }
755         }
756
757         ret = wimlib_add_image(w, source, name, config_str, config_len,
758                                add_image_flags, imagex_progress_func);
759
760         if (ret != 0)
761                 goto out;
762         cur_image = wimlib_get_num_images(w);
763         if (desc) {
764                 ret = wimlib_set_image_descripton(w, cur_image, desc);
765                 if (ret != 0)
766                         goto out;
767         }
768         if (flags_element) {
769                 ret = wimlib_set_image_flags(w, cur_image, flags_element);
770                 if (ret != 0)
771                         goto out;
772         }
773         if (cmd == APPEND) {
774                 ret = wimlib_overwrite(w, write_flags, num_threads,
775                                        imagex_progress_func);
776         } else {
777                 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
778                                    num_threads, imagex_progress_func);
779         }
780         if (ret == WIMLIB_ERR_REOPEN)
781                 ret = 0;
782         if (ret != 0)
783                 imagex_error("Failed to write the WIM file `%s'", wimfile);
784 out:
785         wimlib_free(w);
786         free(config_str);
787         return ret;
788 }
789
790 /* Remove image(s) from a WIM. */
791 static int imagex_delete(int argc, const char **argv)
792 {
793         int c;
794         int open_flags = 0;
795         int write_flags = 0;
796         const char *wimfile;
797         const char *image_num_or_name;
798         WIMStruct *w;
799         int image;
800         int ret;
801
802         for_opt(c, delete_options) {
803                 switch (c) {
804                 case 'c':
805                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
806                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
807                         break;
808                 case 's':
809                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
810                         break;
811                 default:
812                         usage(DELETE);
813                         return -1;
814                 }
815         }
816         argc -= optind;
817         argv += optind;
818
819         if (argc != 2) {
820                 if (argc < 1)
821                         imagex_error("Must specify a WIM file");
822                 if (argc < 2)
823                         imagex_error("Must specify an image");
824                 usage(DELETE);
825                 return -1;
826         }
827         wimfile = argv[0];
828         image_num_or_name = argv[1];
829
830         ret = file_writable(wimfile);
831         if (ret != 0)
832                 return ret;
833
834         ret = wimlib_open_wim(wimfile, open_flags, &w,
835                               imagex_progress_func);
836         if (ret != 0)
837                 return ret;
838
839         image = wimlib_resolve_image(w, image_num_or_name);
840
841         ret = verify_image_exists(image, image_num_or_name, wimfile);
842         if (ret != 0)
843                 goto out;
844
845         ret = wimlib_delete_image(w, image);
846         if (ret != 0) {
847                 imagex_error("Failed to delete image from `%s'", wimfile);
848                 goto out;
849         }
850
851         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
852         if (ret == WIMLIB_ERR_REOPEN)
853                 ret = 0;
854         if (ret != 0) {
855                 imagex_error("Failed to write the file `%s' with image "
856                              "deleted", wimfile);
857         }
858 out:
859         wimlib_free(w);
860         return ret;
861 }
862
863 /* Print the files contained in an image(s) in a WIM file. */
864 static int imagex_dir(int argc, const char **argv)
865 {
866         const char *wimfile;
867         WIMStruct *w;
868         int image;
869         int ret;
870         int num_images;
871
872         if (argc < 2) {
873                 imagex_error("Must specify a WIM file");
874                 usage(DIR);
875                 return -1;
876         }
877         if (argc > 3) {
878                 imagex_error("Too many arguments");
879                 usage(DIR);
880                 return -1;
881         }
882
883         wimfile = argv[1];
884         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
885                               imagex_progress_func);
886         if (ret != 0)
887                 return ret;
888
889         if (argc == 3) {
890                 image = wimlib_resolve_image(w, argv[2]);
891                 ret = verify_image_exists(image, argv[2], wimfile);
892                 if (ret != 0)
893                         goto out;
894         } else {
895                 /* Image was not specified.  If the WIM only contains one image,
896                  * choose that one; otherwise, print an error. */
897                 num_images = wimlib_get_num_images(w);
898                 if (num_images != 1) {
899                         imagex_error("The file `%s' contains %d images; Please "
900                                      "select one.", wimfile, num_images);
901                         usage(DIR);
902                         ret = -1;
903                         goto out;
904                 }
905                 image = 1;
906         }
907
908         ret = wimlib_print_files(w, image);
909 out:
910         wimlib_free(w);
911         return ret;
912 }
913
914 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
915  * WIM file. */
916 static int imagex_export(int argc, const char **argv)
917 {
918         int c;
919         int open_flags = 0;
920         int export_flags = 0;
921         int write_flags = 0;
922         int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
923         bool compression_type_specified = false;
924         const char *src_wimfile;
925         const char *src_image_num_or_name;
926         const char *dest_wimfile;
927         const char *dest_name;
928         const char *dest_desc;
929         WIMStruct *src_w = NULL;
930         WIMStruct *dest_w = NULL;
931         int ret;
932         int image;
933         struct stat stbuf;
934         bool wim_is_new;
935         const char *swm_glob = NULL;
936         WIMStruct **additional_swms = NULL;
937         unsigned num_additional_swms = 0;
938         unsigned num_threads = 0;
939
940         for_opt(c, export_options) {
941                 switch (c) {
942                 case 'b':
943                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
944                         break;
945                 case 'c':
946                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
947                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
948                         break;
949                 case 'x':
950                         compression_type = get_compression_type(optarg);
951                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
952                                 return -1;
953                         compression_type_specified = true;
954                         break;
955                 case 'r':
956                         swm_glob = optarg;
957                         break;
958                 case 't':
959                         num_threads = parse_num_threads(optarg);
960                         if (num_threads == UINT_MAX)
961                                 return -1;
962                         break;
963                 case 'R':
964                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
965                         break;
966                 default:
967                         usage(EXPORT);
968                         return -1;
969                 }
970         }
971         argc -= optind;
972         argv += optind;
973         if (argc < 3 || argc > 5) {
974                 usage(EXPORT);
975                 return -1;
976         }
977         src_wimfile           = argv[0];
978         src_image_num_or_name = argv[1];
979         dest_wimfile          = argv[2];
980         dest_name             = (argc >= 4) ? argv[3] : NULL;
981         dest_desc             = (argc >= 5) ? argv[4] : NULL;
982         ret = wimlib_open_wim(src_wimfile,
983                               open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
984                               imagex_progress_func);
985         if (ret != 0)
986                 return ret;
987
988         /* Determine if the destination is an existing file or not.
989          * If so, we try to append the exported image(s) to it; otherwise, we
990          * create a new WIM containing the exported image(s). */
991         if (stat(dest_wimfile, &stbuf) == 0) {
992                 int dest_ctype;
993
994                 wim_is_new = false;
995                 /* Destination file exists. */
996                 if (!S_ISREG(stbuf.st_mode) && !S_ISLNK(stbuf.st_mode)) {
997                         imagex_error("`%s' is not a regular file",
998                                         dest_wimfile);
999                         ret = -1;
1000                         goto out;
1001                 }
1002                 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
1003                                       imagex_progress_func);
1004                 if (ret != 0)
1005                         goto out;
1006
1007                 ret = file_writable(dest_wimfile);
1008                 if (ret != 0)
1009                         return ret;
1010
1011                 dest_ctype = wimlib_get_compression_type(dest_w);
1012                 if (compression_type_specified
1013                     && compression_type != dest_ctype)
1014                 {
1015                         imagex_error("Cannot specify a compression type that is "
1016                                      "not the same as that used in the "
1017                                      "destination WIM");
1018                         ret = -1;
1019                         goto out;
1020                 }
1021                 compression_type = dest_ctype;
1022         } else {
1023                 wim_is_new = true;
1024                 /* dest_wimfile is not an existing file, so create a new WIM. */
1025                 if (!compression_type_specified)
1026                         compression_type = wimlib_get_compression_type(src_w);
1027                 if (errno == ENOENT) {
1028                         ret = wimlib_create_new_wim(compression_type, &dest_w);
1029                         if (ret != 0)
1030                                 goto out;
1031                 } else {
1032                         imagex_error_with_errno("Cannot stat file `%s'",
1033                                                 dest_wimfile);
1034                         ret = -1;
1035                         goto out;
1036                 }
1037         }
1038
1039         image = wimlib_resolve_image(src_w, src_image_num_or_name);
1040         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1041         if (ret != 0)
1042                 goto out;
1043
1044         if (swm_glob) {
1045                 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1046                                           &additional_swms,
1047                                           &num_additional_swms);
1048                 if (ret != 0)
1049                         goto out;
1050         }
1051
1052         ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1053                                   export_flags, additional_swms,
1054                                   num_additional_swms, imagex_progress_func);
1055         if (ret != 0)
1056                 goto out;
1057
1058
1059         if (wim_is_new)
1060                 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1061                                    write_flags, num_threads,
1062                                    imagex_progress_func);
1063         else
1064                 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1065                                        imagex_progress_func);
1066 out:
1067         if (ret == WIMLIB_ERR_REOPEN)
1068                 ret = 0;
1069         wimlib_free(src_w);
1070         wimlib_free(dest_w);
1071         if (additional_swms) {
1072                 for (unsigned i = 0; i < num_additional_swms; i++)
1073                         wimlib_free(additional_swms[i]);
1074                 free(additional_swms);
1075         }
1076         return ret;
1077 }
1078
1079 /* Prints information about a WIM file; also can mark an image as bootable,
1080  * change the name of an image, or change the description of an image. */
1081 static int imagex_info(int argc, const char **argv)
1082 {
1083         int c;
1084         bool boot         = false;
1085         bool check        = false;
1086         bool header       = false;
1087         bool lookup_table = false;
1088         bool xml          = false;
1089         bool metadata     = false;
1090         bool short_header = true;
1091         const char *xml_out_file = NULL;
1092         const char *wimfile;
1093         const char *image_num_or_name = "all";
1094         const char *new_name = NULL;
1095         const char *new_desc = NULL;
1096         WIMStruct *w;
1097         FILE *fp;
1098         int image;
1099         int ret;
1100         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1101         int part_number;
1102         int total_parts;
1103
1104         for_opt(c, info_options) {
1105                 switch (c) {
1106                 case 'b':
1107                         boot = true;
1108                         break;
1109                 case 'c':
1110                         check = true;
1111                         break;
1112                 case 'h':
1113                         header = true;
1114                         short_header = false;
1115                         break;
1116                 case 'l':
1117                         lookup_table = true;
1118                         short_header = false;
1119                         break;
1120                 case 'x':
1121                         xml = true;
1122                         short_header = false;
1123                         break;
1124                 case 'X':
1125                         xml_out_file = optarg;
1126                         short_header = false;
1127                         break;
1128                 case 'm':
1129                         metadata = true;
1130                         short_header = false;
1131                         break;
1132                 default:
1133                         usage(INFO);
1134                         return -1;
1135                 }
1136         }
1137
1138         argc -= optind;
1139         argv += optind;
1140         if (argc == 0 || argc > 4) {
1141                 usage(INFO);
1142                 return -1;
1143         }
1144         wimfile = argv[0];
1145         if (argc > 1) {
1146                 image_num_or_name = argv[1];
1147                 if (argc > 2) {
1148                         new_name = argv[2];
1149                         if (argc > 3) {
1150                                 new_desc = argv[3];
1151                         }
1152                 }
1153         }
1154
1155         if (check)
1156                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1157
1158         ret = wimlib_open_wim(wimfile, open_flags, &w,
1159                               imagex_progress_func);
1160         if (ret != 0)
1161                 return ret;
1162
1163         part_number = wimlib_get_part_number(w, &total_parts);
1164
1165         image = wimlib_resolve_image(w, image_num_or_name);
1166         if (image == WIMLIB_NO_IMAGE && strcmp(image_num_or_name, "0") != 0) {
1167                 imagex_error("The image `%s' does not exist",
1168                                                 image_num_or_name);
1169                 if (boot)
1170                         imagex_error("If you would like to set the boot "
1171                                      "index to 0, specify image \"0\" with "
1172                                      "the --boot flag.");
1173                 ret = WIMLIB_ERR_INVALID_IMAGE;
1174                 goto out;
1175         }
1176
1177         if (image == WIMLIB_ALL_IMAGES && wimlib_get_num_images(w) > 1) {
1178                 if (boot) {
1179                         imagex_error("Cannot specify the --boot flag "
1180                                      "without specifying a specific "
1181                                      "image in a multi-image WIM");
1182                         ret = WIMLIB_ERR_INVALID_IMAGE;
1183                         goto out;
1184                 }
1185                 if (new_name) {
1186                         imagex_error("Cannot specify the NEW_NAME "
1187                                      "without specifying a specific "
1188                                      "image in a multi-image WIM");
1189                         ret = WIMLIB_ERR_INVALID_IMAGE;
1190                         goto out;
1191                 }
1192         }
1193
1194         /* Operations that print information are separated from operations that
1195          * recreate the WIM file. */
1196         if (!new_name && !boot) {
1197
1198                 /* Read-only operations */
1199
1200                 if (image == WIMLIB_NO_IMAGE) {
1201                         imagex_error("`%s' is not a valid image",
1202                                      image_num_or_name);
1203                         ret = WIMLIB_ERR_INVALID_IMAGE;
1204                         goto out;
1205                 }
1206
1207                 if (image == WIMLIB_ALL_IMAGES && short_header)
1208                         wimlib_print_wim_information(w);
1209
1210                 if (header)
1211                         wimlib_print_header(w);
1212
1213                 if (lookup_table) {
1214                         if (total_parts != 1) {
1215                                 printf("Warning: Only showing the lookup table "
1216                                        "for part %d of a %d-part WIM.\n",
1217                                        part_number, total_parts);
1218                         }
1219                         wimlib_print_lookup_table(w);
1220                 }
1221
1222                 if (xml) {
1223                         ret = wimlib_extract_xml_data(w, stdout);
1224                         if (ret != 0)
1225                                 goto out;
1226                 }
1227
1228                 if (xml_out_file) {
1229                         fp = fopen(xml_out_file, "wb");
1230                         if (!fp) {
1231                                 imagex_error_with_errno("Failed to open the "
1232                                                         "file `%s' for "
1233                                                         "writing ",
1234                                                         xml_out_file);
1235                                 goto out;
1236                         }
1237                         ret = wimlib_extract_xml_data(w, fp);
1238                         if (fclose(fp) != 0) {
1239                                 imagex_error("Failed to close the file `%s'",
1240                                              xml_out_file);
1241                                 goto out;
1242                         }
1243
1244                         if (ret != 0)
1245                                 goto out;
1246                 }
1247
1248                 if (short_header)
1249                         wimlib_print_available_images(w, image);
1250
1251                 if (metadata) {
1252                         ret = wimlib_print_metadata(w, image);
1253                         if (ret != 0)
1254                                 goto out;
1255                 }
1256         } else {
1257
1258                 /* Modification operations */
1259                 if (total_parts != 1) {
1260                         imagex_error("Modifying a split WIM is not supported.");
1261                         return -1;
1262                 }
1263                 if (image == WIMLIB_ALL_IMAGES)
1264                         image = 1;
1265
1266                 if (image == WIMLIB_NO_IMAGE && new_name) {
1267                         imagex_error("Cannot specify new_name (`%s') when "
1268                                      "using image 0", new_name);
1269                         return -1;
1270                 }
1271
1272                 if (boot) {
1273                         if (image == wimlib_get_boot_idx(w)) {
1274                                 printf("Image %d is already marked as "
1275                                        "bootable.\n", image);
1276                                 boot = false;
1277                         } else {
1278                                 printf("Marking image %d as bootable.\n",
1279                                        image);
1280                                 wimlib_set_boot_idx(w, image);
1281                         }
1282                 }
1283                 if (new_name) {
1284                         if (strcmp(wimlib_get_image_name(w, image),
1285                                                 new_name) == 0) {
1286                                 printf("Image %d is already named \"%s\".\n",
1287                                        image, new_name);
1288                                 new_name = NULL;
1289                         } else {
1290                                 printf("Changing the name of image %d to "
1291                                        "\"%s\".\n", image, new_name);
1292                                 ret = wimlib_set_image_name(w, image, new_name);
1293                                 if (ret != 0)
1294                                         goto out;
1295                         }
1296                 }
1297                 if (new_desc) {
1298                         const char *old_desc;
1299                         old_desc = wimlib_get_image_description(w, image);
1300                         if (old_desc && strcmp(old_desc, new_desc) == 0) {
1301                                 printf("The description of image %d is already "
1302                                        "\"%s\".\n", image, new_desc);
1303                                 new_desc = NULL;
1304                         } else {
1305                                 printf("Changing the description of image %d "
1306                                        "to \"%s\".\n", image, new_desc);
1307                                 ret = wimlib_set_image_descripton(w, image,
1308                                                                   new_desc);
1309                                 if (ret != 0)
1310                                         goto out;
1311                         }
1312                 }
1313
1314                 /* Only call wimlib_overwrite() if something actually needs to
1315                  * be changed. */
1316                 if (boot || new_name || new_desc ||
1317                                 check != wimlib_has_integrity_table(w)) {
1318
1319                         ret = file_writable(wimfile);
1320                         if (ret != 0)
1321                                 return ret;
1322
1323                         int write_flags;
1324                         if (check) {
1325                                 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1326                         } else {
1327                                 write_flags = 0;
1328                         }
1329
1330                         ret = wimlib_overwrite(w, write_flags, 1,
1331                                                imagex_progress_func);
1332                         if (ret == WIMLIB_ERR_REOPEN)
1333                                 ret = 0;
1334                 } else {
1335                         printf("The file `%s' was not modified because nothing "
1336                                         "needed to be done.\n", wimfile);
1337                         ret = 0;
1338                 }
1339         }
1340 out:
1341         wimlib_free(w);
1342         return ret;
1343 }
1344
1345 /* Join split WIMs into one part WIM */
1346 static int imagex_join(int argc, const char **argv)
1347 {
1348         int c;
1349         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1350         int wim_write_flags = 0;
1351         const char *output_path;
1352
1353         for_opt(c, join_options) {
1354                 switch (c) {
1355                 case 'c':
1356                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1357                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1358                         break;
1359                 default:
1360                         goto err;
1361                 }
1362         }
1363         argc -= optind;
1364         argv += optind;
1365
1366         if (argc < 2) {
1367                 imagex_error("Must specify one or more split WIM (.swm) parts "
1368                              "to join");
1369                 goto err;
1370         }
1371         output_path = argv[0];
1372         return wimlib_join(++argv, --argc, output_path, swm_open_flags,
1373                            wim_write_flags, imagex_progress_func);
1374 err:
1375         usage(JOIN);
1376         return -1;
1377 }
1378
1379 /* Mounts an image using a FUSE mount. */
1380 static int imagex_mount_rw_or_ro(int argc, const char **argv)
1381 {
1382         int c;
1383         int mount_flags = 0;
1384         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1385         const char *wimfile;
1386         const char *dir;
1387         WIMStruct *w;
1388         int image;
1389         int num_images;
1390         int ret;
1391         const char *swm_glob = NULL;
1392         WIMStruct **additional_swms = NULL;
1393         unsigned num_additional_swms = 0;
1394         const char *staging_dir = NULL;
1395
1396         if (strcmp(argv[0], "mountrw") == 0)
1397                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
1398
1399         for_opt(c, mount_options) {
1400                 switch (c) {
1401                 case 'c':
1402                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1403                         break;
1404                 case 'd':
1405                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
1406                         break;
1407                 case 's':
1408                         if (strcasecmp(optarg, "none") == 0)
1409                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
1410                         else if (strcasecmp(optarg, "xattr") == 0)
1411                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1412                         else if (strcasecmp(optarg, "windows") == 0)
1413                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
1414                         else {
1415                                 imagex_error("Unknown stream interface \"%s\"", optarg);
1416                                 goto mount_usage;
1417                         }
1418                         break;
1419                 case 'r':
1420                         swm_glob = optarg;
1421                         break;
1422                 case 'D':
1423                         staging_dir = optarg;
1424                         break;
1425                 default:
1426                         goto mount_usage;
1427                 }
1428         }
1429         argc -= optind;
1430         argv += optind;
1431         if (argc != 2 && argc != 3)
1432                 goto mount_usage;
1433
1434         wimfile = argv[0];
1435
1436         ret = wimlib_open_wim(wimfile, open_flags, &w,
1437                               imagex_progress_func);
1438         if (ret != 0)
1439                 return ret;
1440
1441         if (swm_glob) {
1442                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1443                                           &additional_swms,
1444                                           &num_additional_swms);
1445                 if (ret != 0)
1446                         goto out;
1447         }
1448
1449         if (argc == 2) {
1450                 image = 1;
1451                 num_images = wimlib_get_num_images(w);
1452                 if (num_images != 1) {
1453                         imagex_error("The file `%s' contains %d images; Please "
1454                                      "select one.", wimfile, num_images);
1455                         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
1456                                         ? MOUNTRW : MOUNT);
1457                         ret = -1;
1458                         goto out;
1459                 }
1460                 dir = argv[1];
1461         } else {
1462                 image = wimlib_resolve_image(w, argv[1]);
1463                 dir = argv[2];
1464                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
1465                 if (ret != 0)
1466                         goto out;
1467         }
1468
1469         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1470                 ret = file_writable(wimfile);
1471                 if (ret != 0)
1472                         return ret;
1473         }
1474
1475         ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
1476                                  num_additional_swms, staging_dir);
1477         if (ret != 0) {
1478                 imagex_error("Failed to mount image %d from `%s' on `%s'",
1479                              image, wimfile, dir);
1480
1481         }
1482 out:
1483         wimlib_free(w);
1484         if (additional_swms) {
1485                 for (unsigned i = 0; i < num_additional_swms; i++)
1486                         wimlib_free(additional_swms[i]);
1487                 free(additional_swms);
1488         }
1489         return ret;
1490 mount_usage:
1491         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
1492                         ? MOUNTRW : MOUNT);
1493         return -1;
1494 }
1495
1496 static int imagex_optimize(int argc, const char **argv)
1497 {
1498         int c;
1499         int open_flags = 0;
1500         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
1501         int ret;
1502         WIMStruct *w;
1503         const char *wimfile;
1504         off_t old_size;
1505         off_t new_size;
1506
1507         for_opt(c, optimize_options) {
1508                 switch (c) {
1509                 case 'c':
1510                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1511                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1512                         break;
1513                 case 'r':
1514                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1515                         break;
1516                 default:
1517                         usage(OPTIMIZE);
1518                         return -1;
1519                 }
1520         }
1521         argc -= optind;
1522         argv += optind;
1523
1524         if (argc != 1) {
1525                 usage(OPTIMIZE);
1526                 return -1;
1527         }
1528
1529         wimfile = argv[0];
1530
1531         ret = wimlib_open_wim(wimfile, open_flags, &w,
1532                               imagex_progress_func);
1533         if (ret != 0)
1534                 return ret;
1535
1536         old_size = file_get_size(argv[0]);
1537         printf("`%s' original size: ", wimfile);
1538         if (old_size == -1)
1539                 puts("Unknown");
1540         else
1541                 printf("%"PRIu64" KiB\n", old_size >> 10);
1542
1543         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1544
1545         if (ret == 0) {
1546                 new_size = file_get_size(argv[0]);
1547                 printf("`%s' optimized size: ", wimfile);
1548                 if (new_size == -1)
1549                         puts("Unknown");
1550                 else
1551                         printf("%"PRIu64" KiB\n", new_size >> 10);
1552
1553                 fputs("Space saved: ", stdout);
1554                 if (new_size != -1 && old_size != -1) {
1555                         printf("%lld KiB\n",
1556                                ((long long)old_size - (long long)new_size) >> 10);
1557                 } else {
1558                         puts("Unknown");
1559                 }
1560         }
1561
1562         wimlib_free(w);
1563         return ret;
1564 }
1565
1566 /* Split a WIM into a spanned set */
1567 static int imagex_split(int argc, const char **argv)
1568 {
1569         int c;
1570         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1571         int write_flags = 0;
1572         unsigned long part_size;
1573         char *tmp;
1574         int ret;
1575         WIMStruct *w;
1576
1577         for_opt(c, split_options) {
1578                 switch (c) {
1579                 case 'c':
1580                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1581                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1582                         break;
1583                 default:
1584                         usage(SPLIT);
1585                         return -1;
1586                 }
1587         }
1588         argc -= optind;
1589         argv += optind;
1590
1591         if (argc != 3) {
1592                 usage(SPLIT);
1593                 return -1;
1594         }
1595         part_size = strtod(argv[2], &tmp) * (1 << 20);
1596         if (tmp == argv[2] || *tmp) {
1597                 imagex_error("Invalid part size \"%s\"", argv[2]);
1598                 imagex_error("The part size must be an integer or floating-point number of megabytes.");
1599                 return -1;
1600         }
1601         ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
1602         if (ret != 0)
1603                 return ret;
1604         ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
1605         wimlib_free(w);
1606         return ret;
1607 }
1608
1609 /* Unmounts an image. */
1610 static int imagex_unmount(int argc, const char **argv)
1611 {
1612         int c;
1613         int unmount_flags = 0;
1614         int ret;
1615
1616         for_opt(c, unmount_options) {
1617                 switch (c) {
1618                 case 'c':
1619                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
1620                         break;
1621                 case 'C':
1622                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
1623                         break;
1624                 default:
1625                         usage(UNMOUNT);
1626                         return -1;
1627                 }
1628         }
1629         argc -= optind;
1630         argv += optind;
1631         if (argc != 1) {
1632                 usage(UNMOUNT);
1633                 return -1;
1634         }
1635
1636         ret = wimlib_unmount_image(argv[0], unmount_flags,
1637                                    imagex_progress_func);
1638         if (ret != 0)
1639                 imagex_error("Failed to unmount `%s'", argv[0]);
1640         return ret;
1641 }
1642
1643 struct imagex_command {
1644         const char *name;
1645         int (*func)(int , const char **);
1646         int cmd;
1647 };
1648
1649
1650 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
1651                 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
1652
1653 static const struct imagex_command imagex_commands[] = {
1654         {"append",  imagex_capture_or_append, APPEND},
1655         {"apply",   imagex_apply,             APPLY},
1656         {"capture", imagex_capture_or_append, CAPTURE},
1657         {"delete",  imagex_delete,            DELETE},
1658         {"dir",     imagex_dir,               DIR},
1659         {"export",  imagex_export,            EXPORT},
1660         {"info",    imagex_info,              INFO},
1661         {"join",    imagex_join,              JOIN},
1662         {"mount",   imagex_mount_rw_or_ro,    MOUNT},
1663         {"mountrw", imagex_mount_rw_or_ro,    MOUNTRW},
1664         {"optimize",imagex_optimize,          OPTIMIZE},
1665         {"split",   imagex_split,             SPLIT},
1666         {"unmount", imagex_unmount,           UNMOUNT},
1667 };
1668
1669 static void version()
1670 {
1671         static const char *s =
1672         "imagex (" PACKAGE ") " PACKAGE_VERSION "\n"
1673         "Copyright (C) 2012 Eric Biggers\n"
1674         "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
1675         "This is free software: you are free to change and redistribute it.\n"
1676         "There is NO WARRANTY, to the extent permitted by law.\n"
1677         "\n"
1678         "Report bugs to "PACKAGE_BUGREPORT".\n";
1679         fputs(s, stdout);
1680 }
1681
1682
1683 static void help_or_version(int argc, const char **argv)
1684 {
1685         int i;
1686         const char *p;
1687         const struct imagex_command *cmd;
1688
1689         for (i = 1; i < argc; i++) {
1690                 p = argv[i];
1691                 if (*p == '-')
1692                         p++;
1693                 else
1694                         continue;
1695                 if (*p == '-')
1696                         p++;
1697                 if (strcmp(p, "help") == 0) {
1698                         for_imagex_command(cmd) {
1699                                 if (strcmp(cmd->name, argv[1]) == 0) {
1700                                         usage(cmd->cmd);
1701                                         exit(0);
1702                                 }
1703                         }
1704                         usage_all();
1705                         exit(0);
1706                 }
1707                 if (strcmp(p, "version") == 0) {
1708                         version();
1709                         exit(0);
1710                 }
1711         }
1712 }
1713
1714
1715 static void usage(int cmd_type)
1716 {
1717         const struct imagex_command *cmd;
1718         printf("Usage: %s", usage_strings[cmd_type]);
1719         for_imagex_command(cmd) {
1720                 if (cmd->cmd == cmd_type)
1721                         printf("\nTry `man imagex-%s' for more details.\n",
1722                                cmd->name);
1723         }
1724 }
1725
1726 static void usage_all()
1727 {
1728         puts("IMAGEX: Usage:");
1729         for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
1730                 printf("    %s", usage_strings[i]);
1731         static const char *extra =
1732 "    imagex --help\n"
1733 "    imagex --version\n"
1734 "\n"
1735 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
1736 "\n"
1737 "    Try `man imagex' for more information.\n"
1738         ;
1739         fputs(extra, stdout);
1740 }
1741
1742
1743 int main(int argc, const char **argv)
1744 {
1745         const struct imagex_command *cmd;
1746         int ret;
1747
1748         if (argc < 2) {
1749                 imagex_error("No command specified");
1750                 usage_all();
1751                 return 1;
1752         }
1753
1754         help_or_version(argc, argv);
1755         argc--;
1756         argv++;
1757
1758         wimlib_set_print_errors(true);
1759
1760         for_imagex_command(cmd) {
1761                 if (strcmp(cmd->name, *argv) == 0) {
1762                         ret = cmd->func(argc, argv);
1763                         if (ret > 0) {
1764                                 imagex_error("Exiting with error code %d:\n"
1765                                              "       %s.", ret,
1766                                              wimlib_get_error_string(ret));
1767                                 if (ret == WIMLIB_ERR_NTFS_3G)
1768                                         imagex_error_with_errno("errno");
1769                         }
1770                         return ret;
1771                 }
1772         }
1773
1774         imagex_error("Unrecognized command: `%s'", argv[0]);
1775         usage_all();
1776         return 1;
1777 }