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