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