]> wimlib.net Git - wimlib/blob - programs/imagex.c
remove dead variable store
[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         } else {
1054                 wim_is_new = true;
1055                 /* dest_wimfile is not an existing file, so create a new WIM. */
1056                 if (!compression_type_specified)
1057                         compression_type = wimlib_get_compression_type(src_w);
1058                 if (errno == ENOENT) {
1059                         ret = wimlib_create_new_wim(compression_type, &dest_w);
1060                         if (ret != 0)
1061                                 goto out;
1062                 } else {
1063                         imagex_error_with_errno("Cannot stat file `%s'",
1064                                                 dest_wimfile);
1065                         ret = -1;
1066                         goto out;
1067                 }
1068         }
1069
1070         image = wimlib_resolve_image(src_w, src_image_num_or_name);
1071         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1072         if (ret != 0)
1073                 goto out;
1074
1075         if (swm_glob) {
1076                 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1077                                           &additional_swms,
1078                                           &num_additional_swms);
1079                 if (ret != 0)
1080                         goto out;
1081         }
1082
1083         ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1084                                   export_flags, additional_swms,
1085                                   num_additional_swms, imagex_progress_func);
1086         if (ret != 0)
1087                 goto out;
1088
1089
1090         if (wim_is_new)
1091                 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1092                                    write_flags, num_threads,
1093                                    imagex_progress_func);
1094         else
1095                 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1096                                        imagex_progress_func);
1097 out:
1098         if (ret == WIMLIB_ERR_REOPEN)
1099                 ret = 0;
1100         wimlib_free(src_w);
1101         wimlib_free(dest_w);
1102         if (additional_swms) {
1103                 for (unsigned i = 0; i < num_additional_swms; i++)
1104                         wimlib_free(additional_swms[i]);
1105                 free(additional_swms);
1106         }
1107         return ret;
1108 }
1109
1110 /* Prints information about a WIM file; also can mark an image as bootable,
1111  * change the name of an image, or change the description of an image. */
1112 static int imagex_info(int argc, const char **argv)
1113 {
1114         int c;
1115         bool boot         = false;
1116         bool check        = false;
1117         bool header       = false;
1118         bool lookup_table = false;
1119         bool xml          = false;
1120         bool metadata     = false;
1121         bool short_header = true;
1122         const char *xml_out_file = NULL;
1123         const char *wimfile;
1124         const char *image_num_or_name = "all";
1125         const char *new_name = NULL;
1126         const char *new_desc = NULL;
1127         WIMStruct *w;
1128         FILE *fp;
1129         int image;
1130         int ret;
1131         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1132         int part_number;
1133         int total_parts;
1134         int num_images;
1135
1136         for_opt(c, info_options) {
1137                 switch (c) {
1138                 case 'b':
1139                         boot = true;
1140                         break;
1141                 case 'c':
1142                         check = true;
1143                         break;
1144                 case 'h':
1145                         header = true;
1146                         short_header = false;
1147                         break;
1148                 case 'l':
1149                         lookup_table = true;
1150                         short_header = false;
1151                         break;
1152                 case 'x':
1153                         xml = true;
1154                         short_header = false;
1155                         break;
1156                 case 'X':
1157                         xml_out_file = optarg;
1158                         short_header = false;
1159                         break;
1160                 case 'm':
1161                         metadata = true;
1162                         short_header = false;
1163                         break;
1164                 default:
1165                         usage(INFO);
1166                         return -1;
1167                 }
1168         }
1169
1170         argc -= optind;
1171         argv += optind;
1172         if (argc == 0 || argc > 4) {
1173                 usage(INFO);
1174                 return -1;
1175         }
1176         wimfile = argv[0];
1177         if (argc > 1) {
1178                 image_num_or_name = argv[1];
1179                 if (argc > 2) {
1180                         new_name = argv[2];
1181                         if (argc > 3) {
1182                                 new_desc = argv[3];
1183                         }
1184                 }
1185         }
1186
1187         if (check)
1188                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1189
1190         ret = wimlib_open_wim(wimfile, open_flags, &w,
1191                               imagex_progress_func);
1192         if (ret != 0)
1193                 return ret;
1194
1195         part_number = wimlib_get_part_number(w, &total_parts);
1196
1197         image = wimlib_resolve_image(w, image_num_or_name);
1198         if (image == WIMLIB_NO_IMAGE && strcmp(image_num_or_name, "0") != 0) {
1199                 imagex_error("The image `%s' does not exist",
1200                              image_num_or_name);
1201                 if (boot)
1202                         imagex_error("If you would like to set the boot "
1203                                      "index to 0, specify image \"0\" with "
1204                                      "the --boot flag.");
1205                 ret = WIMLIB_ERR_INVALID_IMAGE;
1206                 goto out;
1207         }
1208
1209         num_images = wimlib_get_num_images(w);
1210
1211         if (num_images == 0) {
1212                 if (boot) {
1213                         imagex_error("--boot is meaningless on a WIM with no "
1214                                      "images");
1215                         ret = WIMLIB_ERR_INVALID_IMAGE;
1216                         goto out;
1217                 }
1218         }
1219
1220         if (image == WIMLIB_ALL_IMAGES && num_images > 1) {
1221                 if (boot) {
1222                         imagex_error("Cannot specify the --boot flag "
1223                                      "without specifying a specific "
1224                                      "image in a multi-image WIM");
1225                         ret = WIMLIB_ERR_INVALID_IMAGE;
1226                         goto out;
1227                 }
1228                 if (new_name) {
1229                         imagex_error("Cannot specify the NEW_NAME "
1230                                      "without specifying a specific "
1231                                      "image in a multi-image WIM");
1232                         ret = WIMLIB_ERR_INVALID_IMAGE;
1233                         goto out;
1234                 }
1235         }
1236
1237         /* Operations that print information are separated from operations that
1238          * recreate the WIM file. */
1239         if (!new_name && !boot) {
1240
1241                 /* Read-only operations */
1242
1243                 if (image == WIMLIB_NO_IMAGE) {
1244                         imagex_error("`%s' is not a valid image",
1245                                      image_num_or_name);
1246                         ret = WIMLIB_ERR_INVALID_IMAGE;
1247                         goto out;
1248                 }
1249
1250                 if (image == WIMLIB_ALL_IMAGES && short_header)
1251                         wimlib_print_wim_information(w);
1252
1253                 if (header)
1254                         wimlib_print_header(w);
1255
1256                 if (lookup_table) {
1257                         if (total_parts != 1) {
1258                                 printf("Warning: Only showing the lookup table "
1259                                        "for part %d of a %d-part WIM.\n",
1260                                        part_number, total_parts);
1261                         }
1262                         wimlib_print_lookup_table(w);
1263                 }
1264
1265                 if (xml) {
1266                         ret = wimlib_extract_xml_data(w, stdout);
1267                         if (ret != 0)
1268                                 goto out;
1269                 }
1270
1271                 if (xml_out_file) {
1272                         fp = fopen(xml_out_file, "wb");
1273                         if (!fp) {
1274                                 imagex_error_with_errno("Failed to open the "
1275                                                         "file `%s' for "
1276                                                         "writing ",
1277                                                         xml_out_file);
1278                                 ret = -1;
1279                                 goto out;
1280                         }
1281                         ret = wimlib_extract_xml_data(w, fp);
1282                         if (fclose(fp) != 0) {
1283                                 imagex_error("Failed to close the file `%s'",
1284                                              xml_out_file);
1285                                 ret = -1;
1286                         }
1287
1288                         if (ret != 0)
1289                                 goto out;
1290                 }
1291
1292                 if (short_header)
1293                         wimlib_print_available_images(w, image);
1294
1295                 if (metadata) {
1296                         ret = wimlib_print_metadata(w, image);
1297                         if (ret != 0)
1298                                 goto out;
1299                 }
1300         } else {
1301
1302                 /* Modification operations */
1303                 if (total_parts != 1) {
1304                         imagex_error("Modifying a split WIM is not supported.");
1305                         ret = -1;
1306                         goto out;
1307                 }
1308                 if (image == WIMLIB_ALL_IMAGES)
1309                         image = 1;
1310
1311                 if (image == WIMLIB_NO_IMAGE && new_name) {
1312                         imagex_error("Cannot specify new_name (`%s') when "
1313                                      "using image 0", new_name);
1314                         ret = -1;
1315                         goto out;
1316                 }
1317
1318                 if (boot) {
1319                         if (image == wimlib_get_boot_idx(w)) {
1320                                 printf("Image %d is already marked as "
1321                                        "bootable.\n", image);
1322                                 boot = false;
1323                         } else {
1324                                 printf("Marking image %d as bootable.\n",
1325                                        image);
1326                                 wimlib_set_boot_idx(w, image);
1327                         }
1328                 }
1329                 if (new_name) {
1330                         if (strcmp(wimlib_get_image_name(w, image),
1331                                                 new_name) == 0) {
1332                                 printf("Image %d is already named \"%s\".\n",
1333                                        image, new_name);
1334                                 new_name = NULL;
1335                         } else {
1336                                 printf("Changing the name of image %d to "
1337                                        "\"%s\".\n", image, new_name);
1338                                 ret = wimlib_set_image_name(w, image, new_name);
1339                                 if (ret != 0)
1340                                         goto out;
1341                         }
1342                 }
1343                 if (new_desc) {
1344                         const char *old_desc;
1345                         old_desc = wimlib_get_image_description(w, image);
1346                         if (old_desc && strcmp(old_desc, new_desc) == 0) {
1347                                 printf("The description of image %d is already "
1348                                        "\"%s\".\n", image, new_desc);
1349                                 new_desc = NULL;
1350                         } else {
1351                                 printf("Changing the description of image %d "
1352                                        "to \"%s\".\n", image, new_desc);
1353                                 ret = wimlib_set_image_descripton(w, image,
1354                                                                   new_desc);
1355                                 if (ret != 0)
1356                                         goto out;
1357                         }
1358                 }
1359
1360                 /* Only call wimlib_overwrite() if something actually needs to
1361                  * be changed. */
1362                 if (boot || new_name || new_desc ||
1363                     (check && !wimlib_has_integrity_table(w)))
1364                 {
1365                         int write_flags;
1366
1367                         ret = file_writable(wimfile);
1368                         if (ret != 0)
1369                                 return ret;
1370
1371                         if (check)
1372                                 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1373                         else
1374                                 write_flags = 0;
1375
1376                         ret = wimlib_overwrite(w, write_flags, 1,
1377                                                imagex_progress_func);
1378                         if (ret == WIMLIB_ERR_REOPEN)
1379                                 ret = 0;
1380                 } else {
1381                         printf("The file `%s' was not modified because nothing "
1382                                "needed to be done.\n", wimfile);
1383                         ret = 0;
1384                 }
1385         }
1386 out:
1387         wimlib_free(w);
1388         return ret;
1389 }
1390
1391 /* Join split WIMs into one part WIM */
1392 static int imagex_join(int argc, const char **argv)
1393 {
1394         int c;
1395         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1396         int wim_write_flags = 0;
1397         const char *output_path;
1398
1399         for_opt(c, join_options) {
1400                 switch (c) {
1401                 case 'c':
1402                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1403                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1404                         break;
1405                 default:
1406                         goto err;
1407                 }
1408         }
1409         argc -= optind;
1410         argv += optind;
1411
1412         if (argc < 2) {
1413                 imagex_error("Must specify one or more split WIM (.swm) parts "
1414                              "to join");
1415                 goto err;
1416         }
1417         output_path = argv[0];
1418         return wimlib_join(++argv, --argc, output_path, swm_open_flags,
1419                            wim_write_flags, imagex_progress_func);
1420 err:
1421         usage(JOIN);
1422         return -1;
1423 }
1424
1425 /* Mounts an image using a FUSE mount. */
1426 static int imagex_mount_rw_or_ro(int argc, const char **argv)
1427 {
1428         int c;
1429         int mount_flags = 0;
1430         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1431         const char *wimfile;
1432         const char *dir;
1433         WIMStruct *w;
1434         int image;
1435         int num_images;
1436         int ret;
1437         const char *swm_glob = NULL;
1438         WIMStruct **additional_swms = NULL;
1439         unsigned num_additional_swms = 0;
1440         const char *staging_dir = NULL;
1441
1442         if (strcmp(argv[0], "mountrw") == 0)
1443                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
1444
1445         for_opt(c, mount_options) {
1446                 switch (c) {
1447                 case 'A':
1448                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
1449                         break;
1450                 case 'c':
1451                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1452                         break;
1453                 case 'd':
1454                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
1455                         break;
1456                 case 's':
1457                         if (strcasecmp(optarg, "none") == 0)
1458                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
1459                         else if (strcasecmp(optarg, "xattr") == 0)
1460                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1461                         else if (strcasecmp(optarg, "windows") == 0)
1462                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
1463                         else {
1464                                 imagex_error("Unknown stream interface \"%s\"", optarg);
1465                                 goto mount_usage;
1466                         }
1467                         break;
1468                 case 'r':
1469                         swm_glob = optarg;
1470                         break;
1471                 case 'D':
1472                         staging_dir = optarg;
1473                         break;
1474                 case 'U':
1475                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
1476                         break;
1477                 default:
1478                         goto mount_usage;
1479                 }
1480         }
1481         argc -= optind;
1482         argv += optind;
1483         if (argc != 2 && argc != 3)
1484                 goto mount_usage;
1485
1486         wimfile = argv[0];
1487
1488         ret = wimlib_open_wim(wimfile, open_flags, &w,
1489                               imagex_progress_func);
1490         if (ret != 0)
1491                 return ret;
1492
1493         if (swm_glob) {
1494                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1495                                           &additional_swms,
1496                                           &num_additional_swms);
1497                 if (ret != 0)
1498                         goto out;
1499         }
1500
1501         if (argc == 2) {
1502                 image = 1;
1503                 num_images = wimlib_get_num_images(w);
1504                 if (num_images != 1) {
1505                         imagex_error("The file `%s' contains %d images; Please "
1506                                      "select one.", wimfile, num_images);
1507                         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
1508                                         ? MOUNTRW : MOUNT);
1509                         ret = -1;
1510                         goto out;
1511                 }
1512                 dir = argv[1];
1513         } else {
1514                 image = wimlib_resolve_image(w, argv[1]);
1515                 dir = argv[2];
1516                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
1517                 if (ret != 0)
1518                         goto out;
1519         }
1520
1521         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
1522                 ret = file_writable(wimfile);
1523                 if (ret != 0)
1524                         goto out;
1525         }
1526
1527         ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
1528                                  num_additional_swms, staging_dir);
1529         if (ret != 0) {
1530                 imagex_error("Failed to mount image %d from `%s' on `%s'",
1531                              image, wimfile, dir);
1532
1533         }
1534 out:
1535         wimlib_free(w);
1536         if (additional_swms) {
1537                 for (unsigned i = 0; i < num_additional_swms; i++)
1538                         wimlib_free(additional_swms[i]);
1539                 free(additional_swms);
1540         }
1541         return ret;
1542 mount_usage:
1543         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
1544                         ? MOUNTRW : MOUNT);
1545         return -1;
1546 }
1547
1548 static int imagex_optimize(int argc, const char **argv)
1549 {
1550         int c;
1551         int open_flags = 0;
1552         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
1553         int ret;
1554         WIMStruct *w;
1555         const char *wimfile;
1556         off_t old_size;
1557         off_t new_size;
1558
1559         for_opt(c, optimize_options) {
1560                 switch (c) {
1561                 case 'c':
1562                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1563                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1564                         break;
1565                 case 'r':
1566                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
1567                         break;
1568                 default:
1569                         usage(OPTIMIZE);
1570                         return -1;
1571                 }
1572         }
1573         argc -= optind;
1574         argv += optind;
1575
1576         if (argc != 1) {
1577                 usage(OPTIMIZE);
1578                 return -1;
1579         }
1580
1581         wimfile = argv[0];
1582
1583         ret = wimlib_open_wim(wimfile, open_flags, &w,
1584                               imagex_progress_func);
1585         if (ret != 0)
1586                 return ret;
1587
1588         old_size = file_get_size(argv[0]);
1589         printf("`%s' original size: ", wimfile);
1590         if (old_size == -1)
1591                 puts("Unknown");
1592         else
1593                 printf("%"PRIu64" KiB\n", old_size >> 10);
1594
1595         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1596
1597         if (ret == 0) {
1598                 new_size = file_get_size(argv[0]);
1599                 printf("`%s' optimized size: ", wimfile);
1600                 if (new_size == -1)
1601                         puts("Unknown");
1602                 else
1603                         printf("%"PRIu64" KiB\n", new_size >> 10);
1604
1605                 fputs("Space saved: ", stdout);
1606                 if (new_size != -1 && old_size != -1) {
1607                         printf("%lld KiB\n",
1608                                ((long long)old_size - (long long)new_size) >> 10);
1609                 } else {
1610                         puts("Unknown");
1611                 }
1612         }
1613
1614         wimlib_free(w);
1615         return ret;
1616 }
1617
1618 /* Split a WIM into a spanned set */
1619 static int imagex_split(int argc, const char **argv)
1620 {
1621         int c;
1622         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1623         int write_flags = 0;
1624         unsigned long part_size;
1625         char *tmp;
1626         int ret;
1627         WIMStruct *w;
1628
1629         for_opt(c, split_options) {
1630                 switch (c) {
1631                 case 'c':
1632                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1633                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1634                         break;
1635                 default:
1636                         usage(SPLIT);
1637                         return -1;
1638                 }
1639         }
1640         argc -= optind;
1641         argv += optind;
1642
1643         if (argc != 3) {
1644                 usage(SPLIT);
1645                 return -1;
1646         }
1647         part_size = strtod(argv[2], &tmp) * (1 << 20);
1648         if (tmp == argv[2] || *tmp) {
1649                 imagex_error("Invalid part size \"%s\"", argv[2]);
1650                 imagex_error("The part size must be an integer or floating-point number of megabytes.");
1651                 return -1;
1652         }
1653         ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
1654         if (ret != 0)
1655                 return ret;
1656         ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
1657         wimlib_free(w);
1658         return ret;
1659 }
1660
1661 /* Unmounts an image. */
1662 static int imagex_unmount(int argc, const char **argv)
1663 {
1664         int c;
1665         int unmount_flags = 0;
1666         int ret;
1667
1668         for_opt(c, unmount_options) {
1669                 switch (c) {
1670                 case 'c':
1671                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
1672                         break;
1673                 case 'C':
1674                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
1675                         break;
1676                 case 'R':
1677                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
1678                         break;
1679                 default:
1680                         usage(UNMOUNT);
1681                         return -1;
1682                 }
1683         }
1684         argc -= optind;
1685         argv += optind;
1686         if (argc != 1) {
1687                 usage(UNMOUNT);
1688                 return -1;
1689         }
1690
1691         ret = wimlib_unmount_image(argv[0], unmount_flags,
1692                                    imagex_progress_func);
1693         if (ret != 0)
1694                 imagex_error("Failed to unmount `%s'", argv[0]);
1695         return ret;
1696 }
1697
1698 struct imagex_command {
1699         const char *name;
1700         int (*func)(int , const char **);
1701         int cmd;
1702 };
1703
1704
1705 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
1706                 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
1707
1708 static const struct imagex_command imagex_commands[] = {
1709         {"append",  imagex_capture_or_append, APPEND},
1710         {"apply",   imagex_apply,             APPLY},
1711         {"capture", imagex_capture_or_append, CAPTURE},
1712         {"delete",  imagex_delete,            DELETE},
1713         {"dir",     imagex_dir,               DIR},
1714         {"export",  imagex_export,            EXPORT},
1715         {"info",    imagex_info,              INFO},
1716         {"join",    imagex_join,              JOIN},
1717         {"mount",   imagex_mount_rw_or_ro,    MOUNT},
1718         {"mountrw", imagex_mount_rw_or_ro,    MOUNTRW},
1719         {"optimize",imagex_optimize,          OPTIMIZE},
1720         {"split",   imagex_split,             SPLIT},
1721         {"unmount", imagex_unmount,           UNMOUNT},
1722 };
1723
1724 static void version()
1725 {
1726         static const char *s =
1727         "imagex (" PACKAGE ") " PACKAGE_VERSION "\n"
1728         "Copyright (C) 2012 Eric Biggers\n"
1729         "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
1730         "This is free software: you are free to change and redistribute it.\n"
1731         "There is NO WARRANTY, to the extent permitted by law.\n"
1732         "\n"
1733         "Report bugs to "PACKAGE_BUGREPORT".\n";
1734         fputs(s, stdout);
1735 }
1736
1737
1738 static void help_or_version(int argc, const char **argv)
1739 {
1740         int i;
1741         const char *p;
1742         const struct imagex_command *cmd;
1743
1744         for (i = 1; i < argc; i++) {
1745                 p = argv[i];
1746                 if (*p == '-')
1747                         p++;
1748                 else
1749                         continue;
1750                 if (*p == '-')
1751                         p++;
1752                 if (strcmp(p, "help") == 0) {
1753                         for_imagex_command(cmd) {
1754                                 if (strcmp(cmd->name, argv[1]) == 0) {
1755                                         usage(cmd->cmd);
1756                                         exit(0);
1757                                 }
1758                         }
1759                         usage_all();
1760                         exit(0);
1761                 }
1762                 if (strcmp(p, "version") == 0) {
1763                         version();
1764                         exit(0);
1765                 }
1766         }
1767 }
1768
1769
1770 static void usage(int cmd_type)
1771 {
1772         const struct imagex_command *cmd;
1773         printf("Usage: %s", usage_strings[cmd_type]);
1774         for_imagex_command(cmd) {
1775                 if (cmd->cmd == cmd_type)
1776                         printf("\nTry `man imagex-%s' for more details.\n",
1777                                cmd->name);
1778         }
1779 }
1780
1781 static void usage_all()
1782 {
1783         puts("IMAGEX: Usage:");
1784         for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
1785                 printf("    %s", usage_strings[i]);
1786         static const char *extra =
1787 "    imagex --help\n"
1788 "    imagex --version\n"
1789 "\n"
1790 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
1791 "\n"
1792 "    Try `man imagex' for more information.\n"
1793         ;
1794         fputs(extra, stdout);
1795 }
1796
1797
1798 int main(int argc, const char **argv)
1799 {
1800         const struct imagex_command *cmd;
1801         int ret;
1802
1803         if (argc < 2) {
1804                 imagex_error("No command specified");
1805                 usage_all();
1806                 return 1;
1807         }
1808
1809         help_or_version(argc, argv);
1810         argc--;
1811         argv++;
1812
1813         wimlib_set_print_errors(true);
1814         ret = wimlib_global_init();
1815         if (ret)
1816                 goto out;
1817
1818         for_imagex_command(cmd) {
1819                 if (strcmp(cmd->name, *argv) == 0) {
1820                         ret = cmd->func(argc, argv);
1821                         goto out;
1822                 }
1823         }
1824
1825         imagex_error("Unrecognized command: `%s'", argv[0]);
1826         usage_all();
1827         return 1;
1828 out:
1829         if (ret > 0) {
1830                 imagex_error("Exiting with error code %d:\n"
1831                              "       %s.", ret,
1832                              wimlib_get_error_string(ret));
1833                 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
1834                         imagex_error_with_errno("errno");
1835         }
1836         wimlib_global_cleanup();
1837         return ret;
1838 }