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