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