Move VERBOSE flags to progress callbacks
[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 "wimlib.h"
26 #include "config.h"
27 #include <getopt.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <glob.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <libgen.h>
34 #include <limits.h>
35 #include <sys/stat.h>
36 #include <unistd.h>
37 #include <inttypes.h>
38
39 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
40
41 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (char**)argv, "", \
42                                 opts, NULL)) != -1)
43
44
45 enum imagex_op_type {
46         APPEND,
47         APPLY,
48         CAPTURE,
49         DELETE,
50         DIR,
51         EXPORT,
52         INFO,
53         JOIN,
54         MOUNT,
55         MOUNTRW,
56         OPTIMIZE,
57         SPLIT,
58         UNMOUNT,
59 };
60
61 static void usage(int cmd_type);
62 static void usage_all();
63
64 static const char *usage_strings[] = {
65 [APPEND] =
66 "imagex append (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
67 "                     [DESCRIPTION] [--boot] [--check] [--flags EDITION_ID]\n"
68 "                     [--verbose] [--dereference] [--config=FILE]\n"
69 "                     [--threads=NUM_THREADS] [--rebuild]\n",
70 [APPLY] =
71 "imagex apply WIMFILE [IMAGE_NUM | IMAGE_NAME | all]\n"
72 "                    (DIRECTORY | NTFS_VOLUME) [--check] [--hardlink]\n"
73 "                    [--symlink] [--verbose] [--ref=\"GLOB\"]\n",
74 [CAPTURE] =
75 "imagex capture (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
76 "                      [DESCRIPTION] [--boot] [--check] [--compress=TYPE]\n"
77 "                      [--flags EDITION_ID] [--verbose] [--dereference]\n"
78 "                      [--config=FILE] [--threads=NUM_THREADS]\n",
79 [DELETE] =
80 "imagex delete WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check] [--soft]\n",
81 [DIR] =
82 "imagex dir WIMFILE (IMAGE_NUM | IMAGE_NAME | all)\n",
83 [EXPORT] =
84 "imagex export SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
85 "              DEST_WIMFILE [DEST_IMAGE_NAME] [DEST_IMAGE_DESCRIPTION]\n"
86 "              [--boot] [--check] [--compress=TYPE] [--ref=\"GLOB\"]\n"
87 "              [--threads=NUM_THREADS] [--rebuild]\n",
88 [INFO] =
89 "imagex info WIMFILE [IMAGE_NUM | IMAGE_NAME] [NEW_NAME]\n"
90 "                   [NEW_DESC] [--boot] [--check] [--header] [--lookup-table]\n"
91 "                   [--xml] [--extract-xml FILE] [--metadata]\n",
92 [JOIN] =
93 "imagex join [--check] WIMFILE SPLIT_WIM...\n",
94 [MOUNT] =
95 "imagex mount WIMFILE (IMAGE_NUM | IMAGE_NAME) DIRECTORY\n"
96 "                    [--check] [--debug] [--streams-interface=INTERFACE]\n"
97 "                    [--ref=\"GLOB\"]\n",
98 [MOUNTRW] =
99 "imagex mountrw WIMFILE [IMAGE_NUM | IMAGE_NAME] DIRECTORY\n"
100 "                      [--check] [--debug] [--streams-interface=INTERFACE]\n",
101 [OPTIMIZE] =
102 "imagex optimize WIMFILE [--check] [--recompress]\n",
103 [SPLIT] =
104 "imagex split WIMFILE SPLIT_WIMFILE PART_SIZE_MB [--check]\n",
105 [UNMOUNT] =
106 "imagex unmount DIRECTORY [--commit] [--check]\n",
107 };
108
109 static const struct option common_options[] = {
110         {"help", 0, NULL, 'h'},
111         {"version", 0, NULL, 'v'},
112         {NULL, 0, NULL, 0},
113 };
114
115 static const struct option apply_options[] = {
116         {"check",    no_argument,       NULL, 'c'},
117         {"hardlink", no_argument,       NULL, 'h'},
118         {"symlink",  no_argument,       NULL, 's'},
119         {"verbose",  no_argument,       NULL, 'v'},
120         {"ref",      required_argument, NULL, 'r'},
121         {NULL, 0, NULL, 0},
122 };
123 static const struct option capture_or_append_options[] = {
124         {"boot",        no_argument,       NULL, 'b'},
125         {"check",       no_argument,       NULL, 'c'},
126         {"compress",    required_argument, NULL, 'x'},
127         {"config",      required_argument, NULL, 'C'},
128         {"dereference", no_argument,       NULL, 'L'},
129         {"flags",       required_argument, NULL, 'f'},
130         {"verbose",     no_argument,       NULL, 'v'},
131         {"threads",     required_argument, NULL, 't'},
132         {"rebuild",     no_argument,       NULL, 'R'},
133         {NULL, 0, NULL, 0},
134 };
135 static const struct option delete_options[] = {
136         {"check", no_argument, NULL, 'c'},
137         {"soft",  no_argument, NULL, 's'},
138         {NULL, 0, NULL, 0},
139 };
140
141 static const struct option export_options[] = {
142         {"boot",       no_argument,       NULL, 'b'},
143         {"check",      no_argument,       NULL, 'c'},
144         {"compress",   required_argument, NULL, 'x'},
145         {"ref",        required_argument, NULL, 'r'},
146         {"threads",    required_argument, NULL, 't'},
147         {"rebuild",    no_argument,       NULL, 'R'},
148         {NULL, 0, NULL, 0},
149 };
150
151 static const struct option info_options[] = {
152         {"boot",         no_argument, NULL, 'b'},
153         {"check",        no_argument, NULL, 'c'},
154         {"extract-xml",  required_argument, NULL, 'X'},
155         {"header",       no_argument, NULL, 'h'},
156         {"lookup-table", no_argument, NULL, 'l'},
157         {"metadata",     no_argument, NULL, 'm'},
158         {"xml",          no_argument, NULL, 'x'},
159         {NULL, 0, NULL, 0},
160 };
161
162 static const struct option join_options[] = {
163         {"check", no_argument, NULL, 'c'},
164         {NULL, 0, NULL, 0},
165 };
166
167 static const struct option mount_options[] = {
168         {"check", no_argument, NULL, 'c'},
169         {"debug", no_argument, NULL, 'd'},
170         {"streams-interface", required_argument, NULL, 's'},
171         {"ref",      required_argument, NULL, 'r'},
172         {NULL, 0, NULL, 0},
173 };
174
175 static const struct option optimize_options[] = {
176         {"check",      no_argument, NULL, 'c'},
177         {"recompress", no_argument, NULL, 'r'},
178         {NULL, 0, NULL, 0},
179 };
180
181 static const struct option split_options[] = {
182         {"check", no_argument, NULL, 'c'},
183         {NULL, 0, NULL, 0},
184 };
185
186 static const struct option unmount_options[] = {
187         {"commit", no_argument, NULL, 'c'},
188         {"check", no_argument, NULL, 'C'},
189         {NULL, 0, NULL, 0},
190 };
191
192
193
194 /* Print formatted error message to stderr. */
195 static void imagex_error(const char *format, ...)
196 {
197         va_list va;
198         va_start(va, format);
199         fputs("ERROR: ", stderr);
200         vfprintf(stderr, format, va);
201         putc('\n', stderr);
202         va_end(va);
203 }
204
205 /* Print formatted error message to stderr. */
206 static void imagex_error_with_errno(const char *format, ...)
207 {
208         int errno_save = errno;
209         va_list va;
210         va_start(va, format);
211         fputs("ERROR: ", stderr);
212         vfprintf(stderr, format, va);
213         fprintf(stderr, ": %s\n", strerror(errno_save));
214         va_end(va);
215 }
216
217 static int verify_image_exists(int image, const char *image_name,
218                                const char *wim_name)
219 {
220         if (image == WIMLIB_NO_IMAGE) {
221                 imagex_error("\"%s\" is not a valid image in `%s'!\n"
222                              "       Please specify a 1-based imagex index or "
223                              "image name.\n"
224                              "       You may use `imagex info' to list the images "
225                              "contained in a WIM.",
226                              image_name, wim_name);
227                 return -1;
228         }
229         return 0;
230 }
231
232 static int verify_image_is_single(int image)
233 {
234         if (image == WIMLIB_ALL_IMAGES) {
235                 imagex_error("Cannot specify all images for this action!");
236                 return -1;
237         }
238         return 0;
239 }
240
241 static int verify_image_exists_and_is_single(int image, const char *image_name,
242                                              const char *wim_name)
243 {
244         int ret;
245         ret = verify_image_exists(image, image_name, wim_name);
246         if (ret == 0)
247                 ret = verify_image_is_single(image);
248         return ret;
249 }
250
251 static int get_compression_type(const char *optarg)
252 {
253         if (strcasecmp(optarg, "maximum") == 0 || strcasecmp(optarg, "lzx") == 0)
254                 return WIMLIB_COMPRESSION_TYPE_LZX;
255         else if (strcasecmp(optarg, "fast") == 0 || strcasecmp(optarg, "xpress") == 0)
256                 return WIMLIB_COMPRESSION_TYPE_XPRESS;
257         else if (strcasecmp(optarg, "none") == 0)
258                 return WIMLIB_COMPRESSION_TYPE_NONE;
259         else {
260                 imagex_error("Invalid compression type `%s'! Must be "
261                              "\"maximum\", \"fast\", or \"none\".", optarg);
262                 return WIMLIB_COMPRESSION_TYPE_INVALID;
263         }
264 }
265
266 static off_t file_get_size(const char *filename)
267 {
268         struct stat st;
269         if (stat(filename, &st) == 0)
270                 return st.st_size;
271         else
272                 return (off_t)-1;
273 }
274
275 static char *file_get_contents(const char *filename, size_t *len_ret)
276 {
277         struct stat stbuf;
278         char *buf;
279         size_t len;
280         FILE *fp;
281
282         if (stat(filename, &stbuf) != 0) {
283                 imagex_error_with_errno("Failed to stat the file `%s'", filename);
284                 return NULL;
285         }
286         len = stbuf.st_size;
287
288         fp = fopen(filename, "rb");
289         if (!fp) {
290                 imagex_error_with_errno("Failed to open the file `%s'", filename);
291                 return NULL;
292         }
293
294         buf = malloc(len);
295         if (!buf) {
296                 imagex_error("Failed to allocate buffer of %zu bytes to hold "
297                              "contents of file `%s'", len, filename);
298                 goto out_fclose;
299         }
300         if (fread(buf, 1, len, fp) != len) {
301                 imagex_error_with_errno("Failed to read %lu bytes from the "
302                                         "file `%s'", len, filename);
303                 goto out_free_buf;
304         }
305         *len_ret = len;
306         return buf;
307 out_free_buf:
308         free(buf);
309 out_fclose:
310         fclose(fp);
311         return NULL;
312 }
313
314 static int file_writable(const char *path)
315 {
316         int ret;
317         ret = access(path, F_OK | W_OK);
318         if (ret != 0)
319                 imagex_error_with_errno("Can't modify `%s'", path);
320         return ret;
321 }
322
323 #define TO_PERCENT(numerator, denominator) \
324         (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
325
326 static const char *get_data_type(int ctype)
327 {
328         switch (ctype) {
329         case WIMLIB_COMPRESSION_TYPE_NONE:
330                 return "uncompressed";
331         case WIMLIB_COMPRESSION_TYPE_LZX:
332                 return "LZX-compressed";
333         case WIMLIB_COMPRESSION_TYPE_XPRESS:
334                 return "XPRESS-compressed";
335         }
336         return NULL;
337 }
338
339 static int imagex_progress_func(enum wimlib_progress_msg msg,
340                                 const union wimlib_progress_info *info)
341 {
342         unsigned percent_done;
343         switch (msg) {
344         case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
345                 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
346                                           info->write_streams.total_bytes);
347                 if (info->write_streams.completed_streams == 0) {
348                         const char *data_type;
349
350                         data_type = get_data_type(info->write_streams.compression_type);
351                         printf("Writing %s data using %u thread%s\n",
352                                data_type, info->write_streams.num_threads,
353                                (info->write_streams.num_threads == 1) ? "" : "s");
354                 }
355                 printf("\r%"PRIu64" MiB of %"PRIu64" MiB (uncompressed) "
356                        "written (%u%% done)",
357                        info->write_streams.completed_bytes >> 20,
358                        info->write_streams.total_bytes >> 20,
359                        percent_done);
360                 if (info->write_streams.completed_bytes == info->write_streams.total_bytes)
361                         putchar('\n');
362                 break;
363         case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
364                 printf("Scanning `%s'...\n", info->scan.source);
365                 break;
366         case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
367                 if (info->scan.excluded)
368                         printf("Excluding `%s' from capture\n", info->scan.cur_path);
369                 else
370                         printf("Scanning `%s'\n", info->scan.cur_path);
371                 break;
372         /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
373                 /*break;*/
374         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
375                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
376                                           info->integrity.total_bytes);
377                 printf("\rVerifying integrity of `%s': %"PRIu64" MiB "
378                        "of %"PRIu64" MiB (%u%%) done",
379                        info->integrity.filename,
380                        info->integrity.completed_bytes >> 20,
381                        info->integrity.total_bytes >> 20,
382                        percent_done);
383                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
384                         putchar('\n');
385                 break;
386         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
387                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
388                                           info->integrity.total_bytes);
389                 printf("\rCalculating integrity table for WIM: %"PRIu64" MiB "
390                        "of %"PRIu64" MiB (%u%%) done",
391                        info->integrity.completed_bytes >> 20,
392                        info->integrity.total_bytes >> 20,
393                        percent_done);
394                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
395                         putchar('\n');
396                 break;
397         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
398                 /*printf("Applying image %d (%s) to `%s'\n",*/
399                        /*info->extract.image,*/
400                        /*info->extract.image_name,*/
401                        /*info->extract.target);*/
402                 break;
403         /*case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:*/
404                 /*printf("Done applying image %d!\n",*/
405                        /*info->extract.image);*/
406                 /*break;*/
407         /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
408                 /*printf("Applying directory structure to %s\n",*/
409                        /*info->extract.target);*/
410                 /*break;*/
411         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
412                 percent_done = TO_PERCENT(info->extract.completed_bytes,
413                                           info->extract.total_bytes);
414                 printf("\rExtracting files: "
415                        "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done",
416                        info->extract.completed_bytes >> 20,
417                        info->extract.total_bytes >> 20,
418                        percent_done);
419                 if (info->extract.completed_bytes == info->extract.total_bytes)
420                         putchar('\n');
421                 break;
422         case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
423                 puts(info->extract.cur_path);
424                 break;
425         case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
426                 percent_done = TO_PERCENT(info->join.completed_bytes,
427                                           info->join.total_bytes);
428                 printf("Writing resources from part %u of %u: "
429                        "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n",
430                        (info->join.completed_parts == info->join.total_parts) ?
431                                 info->join.completed_parts : info->join.completed_parts + 1,
432                        info->join.total_parts,
433                        info->join.completed_bytes >> 20,
434                        info->join.total_bytes >> 20,
435                        percent_done);
436                 break;
437         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
438                 percent_done = TO_PERCENT(info->split.completed_bytes,
439                                           info->split.total_bytes);
440                 printf("Writing `%s': %"PRIu64" MiB of %"PRIu64" MiB (%u%%) written\n",
441                        info->split.part_name,
442                        info->split.completed_bytes >> 20,
443                        info->split.total_bytes >> 20,
444                        percent_done);
445                 break;
446         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
447                 if (info->split.completed_bytes == info->split.total_bytes) {
448                         printf("Finished writing %u split WIM parts\n",
449                                info->split.cur_part_number);
450                 }
451                 break;
452         default:
453                 break;
454         }
455         fflush(stdout);
456         return 0;
457 }
458
459
460 static int open_swms_from_glob(const char *swm_glob,
461                                const char *first_part,
462                                int open_flags,
463                                WIMStruct ***additional_swms_ret,
464                                unsigned *num_additional_swms_ret)
465 {
466         unsigned num_additional_swms = 0;
467         WIMStruct **additional_swms = NULL;
468         glob_t globbuf;
469         int ret;
470
471         ret = glob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
472         if (ret != 0) {
473                 if (ret == GLOB_NOMATCH) {
474                         imagex_error("Found no files for glob \"%s\"",
475                                      swm_glob);
476                 } else {
477                         imagex_error_with_errno("Failed to process glob "
478                                                 "\"%s\"", swm_glob);
479                 }
480                 ret = -1;
481                 goto out;
482         }
483         num_additional_swms = globbuf.gl_pathc;
484         additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
485         if (!additional_swms) {
486                 imagex_error("Out of memory");
487                 ret = -1;
488                 goto out_globfree;
489         }
490         unsigned offset = 0;
491         for (unsigned i = 0; i < num_additional_swms; i++) {
492                 if (strcmp(globbuf.gl_pathv[i], first_part) == 0) {
493                         offset++;
494                         continue;
495                 }
496                 ret = wimlib_open_wim(globbuf.gl_pathv[i],
497                                       open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
498                                       &additional_swms[i - offset],
499                                       imagex_progress_func);
500                 if (ret != 0)
501                         goto out_close_swms;
502         }
503         *additional_swms_ret = additional_swms;
504         *num_additional_swms_ret = num_additional_swms - offset;
505         ret = 0;
506         goto out_globfree;
507 out_close_swms:
508         for (unsigned i = 0; i < num_additional_swms; i++)
509                 wimlib_free(additional_swms[i]);
510         free(additional_swms);
511 out_globfree:
512         globfree(&globbuf);
513 out:
514         return ret;
515 }
516
517
518 static unsigned parse_num_threads(const char *optarg)
519 {
520         char *tmp;
521         unsigned nthreads = strtoul(optarg, &tmp, 10);
522         if (nthreads == UINT_MAX || *tmp || tmp == optarg) {
523                 imagex_error("Number of threads must be a non-negative integer!");
524                 return UINT_MAX;
525         } else {
526                 return nthreads;
527         }
528 }
529
530
531 /* Extract one image, or all images, from a WIM file into a directory. */
532 static int imagex_apply(int argc, const char **argv)
533 {
534         int c;
535         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
536         int image;
537         int num_images;
538         WIMStruct *w;
539         int ret;
540         const char *wimfile;
541         const char *target;
542         const char *image_num_or_name;
543         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
544
545         const char *swm_glob = NULL;
546         WIMStruct **additional_swms = NULL;
547         unsigned num_additional_swms = 0;
548
549         for_opt(c, apply_options) {
550                 switch (c) {
551                 case 'c':
552                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
553                         break;
554                 case 'h':
555                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
556                         break;
557                 case 's':
558                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
559                         break;
560                 case 'v':
561                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
562                         break;
563                 case 'r':
564                         swm_glob = optarg;
565                         break;
566                 default:
567                         usage(APPLY);
568                         return -1;
569                 }
570         }
571         argc -= optind;
572         argv += optind;
573         if (argc != 2 && argc != 3) {
574                 usage(APPLY);
575                 return -1;
576         }
577
578         wimfile = argv[0];
579         if (argc == 2) {
580                 image_num_or_name = "1";
581                 target = argv[1];
582         } else {
583                 image_num_or_name = argv[1];
584                 target = argv[2];
585         }
586
587         ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
588         if (ret != 0)
589                 return ret;
590
591         image = wimlib_resolve_image(w, image_num_or_name);
592         ret = verify_image_exists(image, image_num_or_name, wimfile);
593         if (ret != 0)
594                 goto out;
595
596         num_images = wimlib_get_num_images(w);
597         if (argc == 2 && num_images != 1) {
598                 imagex_error("`%s' contains %d images; Please select one "
599                              "(or all)", wimfile, num_images);
600                 usage(APPLY);
601                 ret = -1;
602                 goto out;
603         }
604
605         if (swm_glob) {
606                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
607                                           &additional_swms,
608                                           &num_additional_swms);
609                 if (ret != 0)
610                         goto out;
611         }
612
613 #ifdef WITH_NTFS_3G
614         struct stat stbuf;
615
616         ret = stat(target, &stbuf);
617         if (ret == 0) {
618                 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
619                         extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
620                         printf("Applying `%s' image %d to NTFS volume `%s'\n",
621                                wimfile, image, target);
622                 }
623         } else {
624                 if (errno != ENOENT) {
625                         imagex_error_with_errno("Failed to stat `%s'", target);
626                         ret = -1;
627                         goto out;
628                 }
629         }
630 #endif
631
632         ret = wimlib_extract_image(w, image, target, extract_flags,
633                                    additional_swms, num_additional_swms,
634                                    imagex_progress_func);
635 out:
636         wimlib_free(w);
637         if (additional_swms) {
638                 for (unsigned i = 0; i < num_additional_swms; i++)
639                         wimlib_free(additional_swms[i]);
640                 free(additional_swms);
641         }
642         return ret;
643 }
644
645 static int imagex_capture_or_append(int argc, const char **argv)
646 {
647         int c;
648         int open_flags = 0;
649         int add_image_flags = 0;
650         int write_flags = 0;
651         int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
652         const char *source;
653         const char *wimfile;
654         const char *name;
655         const char *desc;
656         const char *flags_element = NULL;
657         const char *config_file = NULL;
658         char *config_str = NULL;
659         size_t config_len = 0;
660         WIMStruct *w = NULL;
661         int ret;
662         int cur_image;
663         char *default_name;
664         int cmd = strcmp(argv[0], "append") ? CAPTURE : APPEND;
665         unsigned num_threads = 0;
666
667         for_opt(c, capture_or_append_options) {
668                 switch (c) {
669                 case 'b':
670                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
671                         break;
672                 case 'c':
673                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
674                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
675                         break;
676                 case 'C':
677                         config_file = optarg;
678                         break;
679                 case 'x':
680                         compression_type = get_compression_type(optarg);
681                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
682                                 return -1;
683                         break;
684                 case 'f':
685                         flags_element = optarg;
686                         break;
687                 case 'L':
688                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
689                         break;
690                 case 'v':
691                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
692                         break;
693                 case 't':
694                         num_threads = parse_num_threads(optarg);
695                         if (num_threads == UINT_MAX)
696                                 return -1;
697                         break;
698                 case 'R':
699                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
700                         break;
701                 default:
702                         usage(cmd);
703                         return -1;
704                 }
705         }
706         argc -= optind;
707         argv += optind;
708         if (argc < 2 || argc > 4) {
709                 usage(cmd);
710                 return -1;
711         }
712         source = argv[0];
713         wimfile = argv[1];
714
715         char source_copy[strlen(source) + 1];
716         memcpy(source_copy, source, strlen(source) + 1);
717         default_name = basename(source_copy);
718
719         name = (argc >= 3) ? argv[2] : default_name;
720         desc = (argc >= 4) ? argv[3] : NULL;
721
722         if (config_file) {
723                 config_str = file_get_contents(config_file, &config_len);
724                 if (!config_str)
725                         return -1;
726         }
727
728         if (cmd == APPEND)
729                 ret = wimlib_open_wim(wimfile, open_flags, &w,
730                                       imagex_progress_func);
731         else
732                 ret = wimlib_create_new_wim(compression_type, &w);
733         if (ret != 0)
734                 goto out;
735
736 #ifdef WITH_NTFS_3G
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 #endif
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
1392         if (strcmp(argv[0], "mountrw") == 0)
1393                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
1394
1395         for_opt(c, mount_options) {
1396                 switch (c) {
1397                 case 'c':
1398                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1399                         break;
1400                 case 'd':
1401                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
1402                         break;
1403                 case 's':
1404                         if (strcasecmp(optarg, "none") == 0)
1405                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
1406                         else if (strcasecmp(optarg, "xattr") == 0)
1407                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1408                         else if (strcasecmp(optarg, "windows") == 0)
1409                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
1410                         else {
1411                                 imagex_error("Unknown stream interface \"%s\"", optarg);
1412                                 goto mount_usage;
1413                         }
1414                         break;
1415                 case 'r':
1416                         swm_glob = optarg;
1417                         break;
1418                 default:
1419                         goto mount_usage;
1420                 }
1421         }
1422         argc -= optind;
1423         argv += optind;
1424         if (argc != 2 && argc != 3)
1425                 goto mount_usage;
1426
1427         wimfile = argv[0];
1428
1429         ret = wimlib_open_wim(wimfile, open_flags, &w,
1430                               imagex_progress_func);
1431         if (ret != 0)
1432                 return ret;
1433
1434         if (swm_glob) {
1435                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1436                                           &additional_swms,
1437                                           &num_additional_swms);
1438                 if (ret != 0)
1439                         goto out;
1440         }
1441
1442         if (argc == 2) {
1443                 image = 1;
1444                 num_images = wimlib_get_num_images(w);
1445                 if (num_images != 1) {
1446                         imagex_error("The file `%s' contains %d images; Please "
1447                                      "select one.", wimfile, num_images);
1448                         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
1449                                         ? MOUNTRW : MOUNT);
1450                         ret = -1;
1451                         goto out;
1452                 }
1453                 dir = argv[1];
1454         } else {
1455                 image = wimlib_resolve_image(w, argv[1]);
1456                 dir = argv[2];
1457                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
1458                 if (ret != 0)
1459                         goto out;
1460         }
1461
1462         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1463                 ret = file_writable(wimfile);
1464                 if (ret != 0)
1465                         return ret;
1466         }
1467
1468         ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
1469                                  num_additional_swms, NULL);
1470         if (ret != 0) {
1471                 imagex_error("Failed to mount image %d from `%s' on `%s'",
1472                              image, wimfile, dir);
1473
1474         }
1475 out:
1476         wimlib_free(w);
1477         if (additional_swms) {
1478                 for (unsigned i = 0; i < num_additional_swms; i++)
1479                         wimlib_free(additional_swms[i]);
1480                 free(additional_swms);
1481         }
1482         return ret;
1483 mount_usage:
1484         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
1485                         ? MOUNTRW : MOUNT);
1486         return -1;
1487 }
1488
1489 static int imagex_optimize(int argc, const char **argv)
1490 {
1491         int c;
1492         int open_flags = 0;
1493         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
1494         int ret;
1495         WIMStruct *w;
1496         const char *wimfile;
1497         off_t old_size;
1498         off_t new_size;
1499
1500         for_opt(c, optimize_options) {
1501                 switch (c) {
1502                 case 'c':
1503                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1504                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1505                         break;
1506                 case 'r':
1507                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1508                         break;
1509                 default:
1510                         usage(OPTIMIZE);
1511                         return -1;
1512                 }
1513         }
1514         argc -= optind;
1515         argv += optind;
1516
1517         if (argc != 1) {
1518                 usage(OPTIMIZE);
1519                 return -1;
1520         }
1521
1522         wimfile = argv[0];
1523
1524         ret = wimlib_open_wim(wimfile, open_flags, &w,
1525                               imagex_progress_func);
1526         if (ret != 0)
1527                 return ret;
1528
1529         old_size = file_get_size(argv[0]);
1530         printf("`%s' original size: ", wimfile);
1531         if (old_size == -1)
1532                 puts("Unknown");
1533         else
1534                 printf("%"PRIu64" KiB\n", old_size >> 10);
1535
1536         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1537
1538         new_size = file_get_size(argv[0]);
1539         printf("`%s' optimized size: ", wimfile);
1540         if (new_size == -1)
1541                 puts("Unknown");
1542         else
1543                 printf("%"PRIu64" KiB\n", new_size >> 10);
1544
1545         fputs("Space saved: ", stdout);
1546         if (new_size != -1 && old_size != -1) {
1547                 printf("%lld KiB\n",
1548                        ((long long)old_size - (long long)new_size) >> 10);
1549         } else {
1550                 puts("Unknown");
1551         }
1552
1553         wimlib_free(w);
1554         return ret;
1555 }
1556
1557 /* Split a WIM into a spanned set */
1558 static int imagex_split(int argc, const char **argv)
1559 {
1560         int c;
1561         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1562         int write_flags = 0;
1563         unsigned long part_size;
1564         char *tmp;
1565         int ret;
1566         WIMStruct *w;
1567
1568         for_opt(c, split_options) {
1569                 switch (c) {
1570                 case 'c':
1571                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1572                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1573                         break;
1574                 default:
1575                         usage(SPLIT);
1576                         return -1;
1577                 }
1578         }
1579         argc -= optind;
1580         argv += optind;
1581
1582         if (argc != 3) {
1583                 usage(SPLIT);
1584                 return -1;
1585         }
1586         part_size = strtod(argv[2], &tmp) * (1 << 20);
1587         if (tmp == argv[2] || *tmp) {
1588                 imagex_error("Invalid part size \"%s\"", argv[2]);
1589                 imagex_error("The part size must be an integer or floating-point number of megabytes.");
1590                 return -1;
1591         }
1592         ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
1593         if (ret != 0)
1594                 return ret;
1595         ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
1596         wimlib_free(w);
1597         return ret;
1598 }
1599
1600 /* Unmounts an image. */
1601 static int imagex_unmount(int argc, const char **argv)
1602 {
1603         int c;
1604         int unmount_flags = 0;
1605         int ret;
1606
1607         for_opt(c, unmount_options) {
1608                 switch (c) {
1609                 case 'c':
1610                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
1611                         break;
1612                 case 'C':
1613                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
1614                         break;
1615                 default:
1616                         usage(UNMOUNT);
1617                         return -1;
1618                 }
1619         }
1620         argc -= optind;
1621         argv += optind;
1622         if (argc != 1) {
1623                 usage(UNMOUNT);
1624                 return -1;
1625         }
1626
1627         ret = wimlib_unmount_image(argv[0], unmount_flags,
1628                                    imagex_progress_func);
1629         if (ret != 0)
1630                 imagex_error("Failed to unmount `%s'", argv[0]);
1631         return ret;
1632 }
1633
1634 struct imagex_command {
1635         const char *name;
1636         int (*func)(int , const char **);
1637         int cmd;
1638 };
1639
1640
1641 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
1642                 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
1643
1644 static const struct imagex_command imagex_commands[] = {
1645         {"append",  imagex_capture_or_append, APPEND},
1646         {"apply",   imagex_apply,             APPLY},
1647         {"capture", imagex_capture_or_append, CAPTURE},
1648         {"delete",  imagex_delete,            DELETE},
1649         {"dir",     imagex_dir,               DIR},
1650         {"export",  imagex_export,            EXPORT},
1651         {"info",    imagex_info,              INFO},
1652         {"join",    imagex_join,              JOIN},
1653         {"mount",   imagex_mount_rw_or_ro,    MOUNT},
1654         {"mountrw", imagex_mount_rw_or_ro,    MOUNTRW},
1655         {"optimize",imagex_optimize,          OPTIMIZE},
1656         {"split",   imagex_split,             SPLIT},
1657         {"unmount", imagex_unmount,           UNMOUNT},
1658 };
1659
1660 static void version()
1661 {
1662         static const char *s =
1663         "imagex (" PACKAGE ") " PACKAGE_VERSION "\n"
1664         "Copyright (C) 2012 Eric Biggers\n"
1665         "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
1666         "This is free software: you are free to change and redistribute it.\n"
1667         "There is NO WARRANTY, to the extent permitted by law.\n"
1668         "\n"
1669         "Report bugs to "PACKAGE_BUGREPORT".\n";
1670         fputs(s, stdout);
1671 }
1672
1673
1674 static void help_or_version(int argc, const char **argv)
1675 {
1676         int i;
1677         const char *p;
1678         const struct imagex_command *cmd;
1679
1680         for (i = 1; i < argc; i++) {
1681                 p = argv[i];
1682                 if (*p == '-')
1683                         p++;
1684                 else
1685                         continue;
1686                 if (*p == '-')
1687                         p++;
1688                 if (strcmp(p, "help") == 0) {
1689                         for_imagex_command(cmd) {
1690                                 if (strcmp(cmd->name, argv[1]) == 0) {
1691                                         usage(cmd->cmd);
1692                                         exit(0);
1693                                 }
1694                         }
1695                         usage_all();
1696                         exit(0);
1697                 }
1698                 if (strcmp(p, "version") == 0) {
1699                         version();
1700                         exit(0);
1701                 }
1702         }
1703 }
1704
1705
1706 static void usage(int cmd_type)
1707 {
1708         const struct imagex_command *cmd;
1709         printf("Usage: %s", usage_strings[cmd_type]);
1710         for_imagex_command(cmd) {
1711                 if (cmd->cmd == cmd_type)
1712                         printf("\nTry `man imagex-%s' for more details.\n",
1713                                cmd->name);
1714         }
1715 }
1716
1717 static void usage_all()
1718 {
1719         puts("IMAGEX: Usage:");
1720         for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
1721                 printf("    %s", usage_strings[i]);
1722         static const char *extra =
1723 "    imagex --help\n"
1724 "    imagex --version\n"
1725 "\n"
1726 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
1727 "\n"
1728 "    Try `man imagex' for more information.\n"
1729         ;
1730         fputs(extra, stdout);
1731 }
1732
1733
1734 int main(int argc, const char **argv)
1735 {
1736         const struct imagex_command *cmd;
1737         int ret;
1738
1739         if (argc < 2) {
1740                 imagex_error("No command specified");
1741                 usage_all();
1742                 return 1;
1743         }
1744
1745         help_or_version(argc, argv);
1746         argc--;
1747         argv++;
1748
1749         wimlib_set_print_errors(true);
1750
1751         for_imagex_command(cmd) {
1752                 if (strcmp(cmd->name, *argv) == 0) {
1753                         ret = cmd->func(argc, argv);
1754                         if (ret > 0) {
1755                                 imagex_error("Exiting with error code %d:\n"
1756                                              "       %s.", ret,
1757                                              wimlib_get_error_string(ret));
1758                                 if (ret == WIMLIB_ERR_NTFS_3G)
1759                                         imagex_error_with_errno("errno");
1760                         }
1761                         return ret;
1762                 }
1763         }
1764
1765         imagex_error("Unrecognized command: `%s'", argv[0]);
1766         usage_all();
1767         return 1;
1768 }