mkntfs, ntfs-3g in imagex
[wimlib] / programs / imagex.c
1 /*
2  * imagex.c
3  *
4  * Use wimlib to create, modify, extract, mount, unmount, or display information
5  * about a WIM file
6  */
7
8 /*
9  * Copyright (C) 2012 Eric Biggers
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25 #include "wimlib.h"
26 #include "config.h"
27 #include <getopt.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <sys/stat.h>
33
34 #ifdef WITH_NTFS_3G
35 #include <unistd.h>
36 #include <sys/wait.h>
37 #endif
38
39 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
40
41 #define swap(a, b) ({ typeof(a) __a = (a); typeof(b) __b = (b); \
42                                 a = __b; b = __a; })
43
44 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (char**)argv, "", \
45                                 opts, NULL)) != -1)
46
47
48 enum imagex_op_type {
49         APPEND,
50         APPLY,
51         CAPTURE,
52         DELETE,
53         DIR,
54         EXPORT,
55         INFO,
56         JOIN,
57         MOUNT,
58         MOUNTRW,
59         SPLIT,
60         UNMOUNT,
61 };
62
63 static const char *path_basename(const char *path)
64 {
65         const char *p = path;
66         while (*p)
67                 p++;
68         p--;
69
70         /* Trailing slashes. */
71         while ((p != path - 1) && *p == '/')
72                 p--;
73
74         while ((p != path - 1) && *p != '/')
75                 p--;
76
77         return p + 1;
78 }
79
80
81 static const char *usage_strings[] = {
82 [APPEND] = 
83 "    imagex append DIRECTORY WIMFILE [\"IMAGE_NAME\"] [\"DESCRIPTION\"] [--boot]\n"
84 "                  [--check] [--flags EDITIONID] [--dereference]\n",
85 [APPLY] = 
86 "    imagex apply WIMFILE [IMAGE_NUM | IMAGE_NAME | all] DIRECTORY [--check]\n"
87 "                 [--hardlink] [--symlink] [--verbose]\n",
88 [CAPTURE] = 
89 "    imagex capture DIRECTORY WIMFILE [\"IMAGE_NAME\"] [\"DESCRIPTION\"]\n"
90 "       l           [--boot] [--check] [--compress[=TYPE]]\n"
91 "                   [--flags \"EditionID\"] [--verbose] [--dereference]\n",
92 [DELETE] = 
93 "    imagex delete WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check]\n",
94 [DIR] = 
95 "    imagex dir WIMFILE (IMAGE_NUM | IMAGE_NAME | \"all\")\n",
96 [EXPORT] = 
97 "    imagex export SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
98 "        DEST_WIMFILE [\"DEST_IMAGE_NAME\"] [\"DEST_IMAGE_DESCRIPTION\"]\n"
99 "                  [--boot] [--check] [--compress[=TYPE]]\n",
100 [INFO] = 
101 "    imagex info WIMFILE [IMAGE_NUM | IMAGE_NAME] [NEW_NAME]\n"
102 "                [NEW_DESC] [--boot] [--check] [--header] [--lookup-table]\n"
103 "                [--xml] [--extract-xml FILE] [--metadata]\n",
104 [JOIN] = 
105 "    imagex join [--check] WIMFILE SPLIT_WIM...\n",
106 [MOUNT] = 
107 "    imagex mount WIMFILE (IMAGE_NUM | IMAGE_NAME) DIRECTORY\n"
108 "                 [--check] [--debug] [--stream-interface=INTERFACE]\n",
109 [MOUNTRW] = 
110 "    imagex mountrw WIMFILE [IMAGE_NUM | IMAGE_NAME] DIRECTORY\n"
111 "                   [--check] [--debug] [--stream-interface=INTERFACE]\n",
112 [SPLIT] = 
113 "    imagex split WIMFILE SPLIT_WIMFILE PART_SIZE [--check]\n",
114 [UNMOUNT] = 
115 "    imagex unmount DIRECTORY [--commit] [--check]\n",
116 };
117
118 static const struct option common_options[] = {
119         {"help", 0, NULL, 'h'},
120         {"version", 0, NULL, 'v'},
121         {NULL, 0, NULL, 0},
122 };
123
124 static const struct option append_options[] = {
125         {"boot",   no_argument,       NULL, 'b'},
126         {"check",  no_argument,       NULL, 'c'},
127         {"flags",    required_argument, NULL, 'f'},
128         {"dereference", no_argument, NULL, 'L'},
129         {NULL, 0, NULL, 0},
130 };
131 static const struct option apply_options[] = {
132         {"check",    no_argument,       NULL, 'c'},
133         {"hardlink", no_argument,       NULL, 'h'},
134         {"symlink",  no_argument,       NULL, 's'},
135         {"verbose",  no_argument,       NULL, 'v'},
136         {"ntfs",     no_argument,       NULL, 'N'},
137         {"mkntfs-args", required_argument, NULL, 'm'},
138         {NULL, 0, NULL, 0},
139 };
140 static const struct option capture_options[] = {
141         {"boot",     no_argument,       NULL, 'b'},
142         {"check",    no_argument,       NULL, 'c'},
143         {"compress", optional_argument, NULL, 'x'},
144         {"flags",    required_argument, NULL, 'f'},
145         {"verbose",  no_argument,       NULL,'v'},
146         {"ntfs",     no_argument,       NULL, 'N'},
147         {"dereference", no_argument, NULL, 'L'},
148         {NULL, 0, NULL, 0},
149 };
150 static const struct option delete_options[] = {
151         {"check", no_argument, NULL, 'c'},
152         {NULL, 0, NULL, 0},
153 };
154
155 static const struct option export_options[] = {
156         {"boot",       no_argument, NULL, 'b'},
157         {"check",      no_argument , NULL, 'c'},
158         {"compress",   optional_argument, NULL, 'x'},
159         {NULL, 0, NULL, 0},
160 };
161
162 static const struct option info_options[] = {
163         {"boot",         no_argument, NULL, 'b'},
164         {"check",        no_argument, NULL, 'c'},
165         {"header",       no_argument, NULL, 'h'},
166         {"lookup-table", no_argument, NULL, 'l'},
167         {"xml",          no_argument, NULL, 'x'},
168         {"extract-xml",  required_argument, NULL, 'X'},
169         {"metadata",     no_argument, NULL, 'm'},
170         {NULL, 0, NULL, 0},
171 };
172
173 static const struct option join_options[] = {
174         {"check", no_argument, NULL, 'c'},
175         {NULL, 0, NULL, 0},
176 };
177
178 static const struct option mount_options[] = {
179         {"check", no_argument, NULL, 'c'},
180         {"debug", no_argument, NULL, 'd'},
181         {"stream-interface", required_argument, NULL, 's'},
182         {NULL, 0, NULL, 0},
183 };
184
185 static const struct option split_options[] = {
186         {"check", no_argument, NULL, 'c'},
187         {NULL, 0, NULL, 0},
188 };
189
190 static const struct option unmount_options[] = {
191         {"commit", no_argument, NULL, 'c'},
192         {"check", no_argument, NULL, 'C'},
193         {NULL, 0, NULL, 0},
194 };
195
196
197 /* Print formatted error message to stderr. */
198 static void imagex_error(const char *format, ...)
199 {
200         va_list va;
201         va_start(va, format);
202         fputs("ERROR: ", stderr);
203         vfprintf(stderr, format, va);
204         putc('\n', stderr);
205         va_end(va);
206 }
207
208 /* Print formatted error message to stderr. */
209 static void imagex_error_with_errno(const char *format, ...)
210 {
211         int errno_save = errno;
212         va_list va;
213         va_start(va, format);
214         fputs("ERROR: ", stderr);
215         vfprintf(stderr, format, va);
216         fprintf(stderr, ": %s\n", strerror(errno_save));
217         va_end(va);
218 }
219
220
221 static inline void version()
222 {
223         static const char *s = 
224         "imagex (" PACKAGE ") " PACKAGE_VERSION "\n"
225         "Copyright (C) 2012 Eric Biggers\n"
226         "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
227         "This is free software: you are free to change and redistribute it.\n"
228         "There is NO WARRANTY, to the extent permitted by law.\n"
229         "\n"
230         "Report bugs to "PACKAGE_BUGREPORT".\n";
231         fputs(s, stdout);
232 }
233
234 static inline void usage(int cmd)
235 {
236         puts("IMAGEX: Usage:");
237         fputs(usage_strings[cmd], stdout);
238 }
239
240 static void usage_all()
241 {
242         puts("IMAGEX: Usage:");
243         for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
244                 fputs(usage_strings[i], stdout);
245         static const char *extra = 
246 "    imagex --help\n"
247 "    imagex --version\n"
248 "\n"
249 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
250         ;
251         fputs(extra, stdout);
252 }
253
254 static int verify_image_exists(int image)
255 {
256         if (image == WIM_NO_IMAGE) {
257                 imagex_error("Not a valid image");
258                 return WIMLIB_ERR_INVALID_IMAGE;
259         }
260         return 0;
261 }
262
263 static int verify_image_is_single(int image)
264 {
265         if (image == WIM_ALL_IMAGES) {
266                 imagex_error("Cannot specify all images for this action");
267                 return WIMLIB_ERR_INVALID_IMAGE;
268         }
269         return 0;
270 }
271
272 static int verify_image_exists_and_is_single(int image)
273 {
274         int ret;
275         ret = verify_image_exists(image);
276         if (ret == 0)
277                 ret = verify_image_is_single(image);
278         return ret;
279 }
280
281 static int get_compression_type(const char *optarg)
282 {
283         if (!optarg)
284                 return WIM_COMPRESSION_TYPE_LZX;
285         if (strcasecmp(optarg, "maximum") == 0 || strcasecmp(optarg, "lzx") == 0)
286                 return WIM_COMPRESSION_TYPE_LZX;
287         else if (strcasecmp(optarg, "fast") == 0 || strcasecmp(optarg, "xpress") == 0)
288                 return WIM_COMPRESSION_TYPE_XPRESS;
289         else if (strcasecmp(optarg, "none") == 0)
290                 return WIM_COMPRESSION_TYPE_NONE;
291         else {
292                 imagex_error("Invalid compression type `%s'! Must be "
293                              "\"maximum\", \"fast\", or \"none\".", optarg);
294                 return WIM_COMPRESSION_TYPE_INVALID;
295         }
296 }
297
298 static int imagex_append(int argc, const char **argv)
299 {
300         int c;
301         const char *flags_element = NULL;
302         int open_flags = WIMLIB_OPEN_FLAG_SHOW_PROGRESS;
303         int add_image_flags = 0;
304         int write_flags = WIMLIB_WRITE_FLAG_SHOW_PROGRESS;
305         const char *dir;
306         const char *wimfile;
307         const char *name;
308         const char *desc;
309         WIMStruct *w;
310         int ret;
311
312         for_opt(c, append_options) {
313                 switch (c) {
314                 case 'b':
315                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
316                         break;
317                 case 'c':
318                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
319                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
320                         break;
321                 case 'f':
322                         flags_element = optarg;
323                         break;
324                 case 'L':
325                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
326                         break;
327                 default:
328                         usage(APPEND);
329                         return -1;
330                 }
331         }
332         argc -= optind;
333         argv += optind;
334         if (argc < 2 || argc > 4) {
335                 usage(APPEND);
336                 return -1;
337         }
338         dir     = argv[0];
339         wimfile = argv[1];
340         name    = (argc >= 3) ? argv[2] : path_basename(dir);
341         desc    = (argc >= 4) ? argv[3] : NULL;
342
343         ret = wimlib_open_wim(wimfile, open_flags, &w);
344         if (ret != 0)
345                 return ret;
346
347         ret = wimlib_add_image(w, dir, name, desc, 
348                                flags_element, add_image_flags);
349         if (ret != 0)
350                 goto done;
351         ret = wimlib_overwrite(w, write_flags);
352 done:
353         wimlib_free(w);
354         return ret;
355 }
356
357 /* Extract one image, or all images, from a WIM file into a directory. */
358 static int imagex_apply(int argc, const char **argv)
359 {
360         int c;
361         int open_flags = WIMLIB_OPEN_FLAG_SHOW_PROGRESS;
362         int image;
363         int num_images;
364         WIMStruct *w;
365         int ret;
366         const char *wimfile;
367         const char *dir;
368         const char *image_num_or_name;
369         const char *mkntfs_args = "";
370         int extract_flags = 0;
371
372         for_opt(c, apply_options) {
373                 switch (c) {
374                 case 'c':
375                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
376                         break;
377                 case 'h':
378                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
379                         break;
380                 case 's':
381                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
382                         break;
383                 case 'v':
384                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
385                         break;
386                 case 'N':
387                         extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
388                         break;
389                 case 'm':
390                         mkntfs_args = optarg;
391                         break;
392                 default:
393                         usage(APPLY);
394                         return -1;
395                 }
396         }
397         argc -= optind;
398         argv += optind;
399         if (argc != 2 && argc != 3) {
400                 usage(APPLY);
401                 return -1;
402         }
403
404         wimfile = argv[0];
405         if (argc == 2) {
406                 image_num_or_name =  "1";
407                 dir = argv[1];
408         } else {
409                 image_num_or_name = argv[1];
410                 dir = argv[2];
411         }
412
413 #ifdef WITH_NTFS_3G
414         char tmpdir[strlen(dir) + 50];
415         tmpdir[0] = '\0';
416
417         /* Check to see if a block device file was specified.  If so, 
418          * create a NTFS filesystem on it. */
419         struct stat stbuf;
420
421         ret = stat(dir, &stbuf);
422         if (ret != 0)
423                 imagex_error_with_errno("Failed to stat `%s'", dir);
424         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
425                 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
426
427                 const char *dev = dir;
428                 printf("Making NTFS filesystem on `%s'\n", dev);
429
430                 char mkntfs_cmdline[sizeof("mkntfs ") + strlen(mkntfs_args) +
431                                     sizeof(" ") + strlen(dev)];
432                 sprintf(mkntfs_cmdline, "mkntfs %s %s", mkntfs_args, dev);
433                 puts(mkntfs_cmdline);
434                 ret = system(mkntfs_cmdline);
435                 if (ret == -1) {
436                         imagex_error_with_errno("Failed to execute the "
437                                                 "`mkntfs' program");
438                         return -1;
439                 } else if (ret > 0) {
440                         imagex_error("`mkntfs' exited with failure status");
441                         imagex_error("Note: You can pass additional arguments "
442                                      "to `mkntfs' using the --mkntfs-args "
443                                      "argument");
444                         return -1;
445                 }
446                 sprintf(tmpdir, "/tmp/imagex-%d-ntfsmount-%s-XXXXXX",
447                                 getpid(), dev);
448                 dir = mkdtemp(tmpdir);
449                 if (!dir) {
450                         imagex_error_with_errno("Failed to create "
451                                                 "temporary directory "
452                                                 "`%s'", tmpdir);
453                 }
454                 char ntfs_3g_cmdline[sizeof("ntfs-3g ") + strlen(dev) +
455                                      sizeof(" ") + strlen(dir)];
456                 sprintf(ntfs_3g_cmdline, "ntfs-3g %s %s", dev, dir);
457                 puts(ntfs_3g_cmdline);
458                 ret = system(ntfs_3g_cmdline);
459                 if (ret == -1) {
460                         imagex_error_with_errno("Failed to execute the "
461                                                 "`ntfs-3g' program");
462                         ret = -1;
463                         goto out_rm_tmpdir;
464                 } else if (ret > 0) {
465                         imagex_error("`ntfs-3g' exited with failure status");
466                         ret = -1;
467                         goto out_rm_tmpdir;
468                 }
469         }
470 #endif
471
472         ret = wimlib_open_wim(wimfile, open_flags, &w);
473         if (ret != 0)
474                 goto done;
475
476         image = wimlib_resolve_image(w, image_num_or_name);
477         ret = verify_image_exists(image);
478         if (ret != 0)
479                 goto done;
480
481         num_images = wimlib_get_num_images(w);
482         if (argc == 2 && num_images != 1) {
483                 imagex_error("`%s' contains %d images; Please select one "
484                              "(or all)", wimfile, num_images);
485                 usage(APPLY);
486                 ret = -1;
487                 goto done;
488         }
489         ret = wimlib_extract_image(w, image, dir, extract_flags);
490 done:
491         wimlib_free(w);
492 #ifdef WITH_NTFS_3G
493 out_rm_tmpdir:
494         if (tmpdir[0] != '\0') {
495                 /* Unmount and remove the NTFS-3g mounted directory */
496
497                 int pid = fork();
498                 int status;
499                 if (pid == -1) {
500                         imagex_error_with_errno("Failed to fork()");
501                         return -1;
502                 }
503                 if (pid == 0) {
504                         execlp("fusermount", "fusermount", "-u", dir, NULL);
505                         imagex_error_with_errno("Failed to execute `fusermount'");
506                         return -1;
507                 }
508
509                 if (waitpid(pid, &status, 0) == -1) {
510                         imagex_error_with_errno("Failed to wait for "
511                                                 "fusermount process to "
512                                                 "terminate");
513                         return -1;
514                 }
515
516                 if (status != 0) {
517                         imagex_error("fusermount exited with status %d",
518                                      status);
519                         return -1;
520                 }
521                 if (rmdir(tmpdir) != 0) {
522                         imagex_error_with_errno("Failed to remove temporary "
523                                                 "directory `%s'", tmpdir);
524                 }
525         }
526 #endif
527         return ret;
528 }
529
530
531 /* Create a WIM file from a directory. */
532 static int imagex_capture(int argc, const char **argv)
533 {
534         int c;
535         int add_image_flags = 0;
536         int write_flags = WIMLIB_WRITE_FLAG_SHOW_PROGRESS;
537         int compression_type = WIM_COMPRESSION_TYPE_NONE;
538         const char *flags_element = NULL;
539         const char *dir;
540         const char *wimfile;
541         const char *name;
542         const char *desc;
543         WIMStruct *w;
544         int ret;
545
546         for_opt(c, capture_options) {
547                 switch (c) {
548                 case 'b':
549                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
550                         break;
551                 case 'c':
552                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
553                         break;
554                 case 'x':
555                         compression_type = get_compression_type(optarg);
556                         if (compression_type == WIM_COMPRESSION_TYPE_INVALID)
557                                 return -1;
558                         break;
559                 case 'f':
560                         flags_element = optarg;
561                         break;
562                 case 'v':
563                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
564                         break;
565                 case 'N':
566                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
567                         break;
568                 case 'L':
569                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
570                         break;
571                 default:
572                         usage(CAPTURE);
573                         return -1;
574                 }
575         }
576
577         argc -= optind;
578         argv += optind;
579         if (argc < 2 || argc > 4) {
580                 usage(CAPTURE);
581                 return -1;
582         }
583         dir     = argv[0];
584         wimfile = argv[1];
585         name    = (argc >= 3) ? argv[2] : dir;
586         desc    = (argc >= 4) ? argv[3] : NULL;
587
588         ret = wimlib_create_new_wim(compression_type, &w);
589         if (ret != 0)
590                 return ret;
591
592         ret = wimlib_add_image(w, dir, name, desc, flags_element, 
593                                add_image_flags);
594         if (ret != 0) {
595                 imagex_error("Failed to add the image `%s'", dir);
596                 goto done;
597         }
598
599         ret = wimlib_write(w, wimfile, WIM_ALL_IMAGES, write_flags);
600         if (ret != 0)
601                 imagex_error("Failed to write the WIM file `%s'", wimfile);
602 done:
603         wimlib_free(w);
604         return ret;
605 }
606
607 /* Remove image(s) from a WIM. */
608 static int imagex_delete(int argc, const char **argv)
609 {
610         int c;
611         int open_flags = WIMLIB_OPEN_FLAG_SHOW_PROGRESS;
612         int write_flags = WIMLIB_WRITE_FLAG_SHOW_PROGRESS;
613         const char *wimfile;
614         const char *image_num_or_name;
615         WIMStruct *w;
616         int image;
617         int ret;
618
619         for_opt(c, delete_options) {
620                 switch (c) {
621                 case 'c':
622                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
623                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
624                         break;
625                 default:
626                         usage(DELETE);
627                         return -1;
628                 }
629         }
630         argc -= optind;
631         argv += optind;
632
633         if (argc != 2) {
634                 if (argc < 1)
635                         imagex_error("Must specify a WIM file");
636                 if (argc < 2)
637                         imagex_error("Must specify an image");
638                 usage(DELETE);
639                 return -1;
640         }
641         wimfile = argv[0];
642         image_num_or_name = argv[1];
643
644         ret = wimlib_open_wim(wimfile, open_flags, &w);
645         if (ret != 0)
646                 return ret;
647
648         image = wimlib_resolve_image(w, image_num_or_name);
649
650         ret = verify_image_exists(image);
651         if (ret != 0)
652                 goto done;
653
654         ret = wimlib_delete_image(w, image);
655         if (ret != 0) {
656                 imagex_error("Failed to delete image from `%s'", wimfile);
657                 goto done;
658         }
659
660         ret = wimlib_overwrite(w, write_flags);
661         if (ret != 0) {
662                 imagex_error("Failed to write the file `%s' with image "
663                              "deleted", wimfile);
664         }
665 done:
666         wimlib_free(w);
667         return ret;
668 }
669
670 /* Print the files contained in an image(s) in a WIM file. */
671 static int imagex_dir(int argc, const char **argv)
672 {
673         const char *wimfile;
674         WIMStruct *w;
675         int image;
676         int ret;
677         int num_images;
678         int part_number;
679
680         if (argc < 2) {
681                 imagex_error("Must specify a WIM file");
682                 usage(DIR);
683                 return -1;
684         }
685         if (argc > 3) {
686                 imagex_error("Too many arguments");
687                 usage(DIR);
688                 return -1;
689         }
690
691         wimfile = argv[1];
692         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w);
693         if (ret != 0)
694                 return ret;
695
696         part_number = wimlib_get_part_number(w, NULL);
697         if (part_number != 1) {
698                 imagex_error("`%s' is part %d of a split WIM!  Specify the "
699                              "first part to see the files",
700                              wimfile, part_number);
701                 ret = WIMLIB_ERR_SPLIT_UNSUPPORTED;
702                 goto done;
703         }
704
705         if (argc == 3) {
706                 image = wimlib_resolve_image(w, argv[2]);
707                 ret = verify_image_exists(image);
708                 if (ret != 0)
709                         goto done;
710         } else {
711                 /* Image was not specified.  If the WIM only contains one image,
712                  * choose that one; otherwise, print an error. */
713                 num_images = wimlib_get_num_images(w);
714                 if (num_images != 1) {
715                         imagex_error("The file `%s' contains %d images; Please "
716                                      "select one.", wimfile, num_images);
717                         usage(DIR);
718                         ret = -1;
719                         goto done;
720                 }
721                 image = 1;
722         }
723
724         ret = wimlib_print_files(w, image);
725 done:
726         wimlib_free(w);
727         return ret;
728 }
729
730 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
731  * WIM file. */
732 static int imagex_export(int argc, const char **argv)
733 {
734         int c;
735         int open_flags = WIMLIB_OPEN_FLAG_SHOW_PROGRESS;
736         int export_flags = 0;
737         int write_flags = WIMLIB_WRITE_FLAG_SHOW_PROGRESS;
738         int compression_type = WIM_COMPRESSION_TYPE_NONE;
739         bool compression_type_specified = false;
740         const char *src_wimfile;
741         const char *src_image_num_or_name;
742         const char *dest_wimfile;
743         const char *dest_name;
744         const char *dest_desc;
745         WIMStruct *src_w = NULL;
746         WIMStruct *dest_w = NULL;
747         int ret;
748         int image;
749         struct stat stbuf;
750         bool wim_is_new;
751
752         for_opt(c, export_options) {
753                 switch (c) {
754                 case 'b':
755                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
756                         break;
757                 case 'c':
758                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
759                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
760                         break;
761                 case 'x':
762                         compression_type = get_compression_type(optarg);
763                         if (compression_type == WIM_COMPRESSION_TYPE_INVALID)
764                                 return -1;
765                         compression_type_specified = true;
766                         break;
767                 default:
768                         usage(EXPORT);
769                         return -1;
770                 }
771         }
772         argc -= optind;
773         argv += optind;
774         if (argc < 3 || argc > 5) {
775                 usage(EXPORT);
776                 return -1;
777         }
778         src_wimfile           = argv[0];
779         src_image_num_or_name = argv[1];
780         dest_wimfile          = argv[2];
781         dest_name             = (argc >= 4) ? argv[3] : NULL;
782         dest_desc             = (argc >= 5) ? argv[4] : NULL;
783         ret = wimlib_open_wim(src_wimfile, open_flags, &src_w);
784         if (ret != 0)
785                 return ret;
786
787         /* Determine if the destination is an existing file or not.  
788          * If so, we try to append the exported image(s) to it; otherwise, we
789          * create a new WIM containing the exported image(s). */
790         if (stat(dest_wimfile, &stbuf) == 0) {
791                 wim_is_new = false;
792                 /* Destination file exists. */
793                 if (!S_ISREG(stbuf.st_mode)) {
794                         imagex_error("`%s' is not a regular file",
795                                         dest_wimfile);
796                         goto done;
797                 }
798                 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w);
799                 if (ret != 0)
800                         goto done;
801
802                 if (compression_type_specified && compression_type != 
803                                 wimlib_get_compression_type(dest_w)) {
804                         imagex_error("Cannot specify a compression type that is "
805                                      "not the same as that used in the "
806                                      "destination WIM");
807                         ret = -1;
808                         goto done;
809                 }
810                 compression_type = wimlib_get_compression_type(dest_w);
811         } else {
812                 wim_is_new = true;
813                 /* dest_wimfile is not an existing file, so create a new WIM. */
814                 if (errno == ENOENT) {
815                         ret = wimlib_create_new_wim(compression_type, &dest_w);
816                         if (ret != 0)
817                                 goto done;
818                 } else {
819                         imagex_error_with_errno("Cannot stat file `%s'",
820                                                 dest_wimfile);
821                         goto done;
822                 }
823         }
824
825         image = wimlib_resolve_image(src_w, src_image_num_or_name);
826         ret = verify_image_exists(image);
827         if (ret != 0)
828                 goto done;
829
830         ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc, 
831                                   export_flags);
832         if (ret != 0)
833                 goto done;
834
835
836         if (wim_is_new)
837                 ret = wimlib_write(dest_w, dest_wimfile, WIM_ALL_IMAGES, 
838                                    write_flags);
839         else
840                 ret = wimlib_overwrite(dest_w, write_flags);
841 done:
842         wimlib_free(src_w);
843         wimlib_free(dest_w);
844         return ret;
845 }
846
847 /* Prints information about a WIM file; also can mark an image as bootable,
848  * change the name of an image, or change the description of an image. */
849 static int imagex_info(int argc, const char **argv)
850 {
851         int c;
852         bool boot         = false;
853         bool check        = false;
854         bool header       = false;
855         bool lookup_table = false;
856         bool xml          = false;
857         bool metadata     = false;
858         bool short_header = true;
859         const char *xml_out_file = NULL;
860         const char *wimfile;
861         const char *image_num_or_name = "all";
862         const char *new_name = NULL;
863         const char *new_desc = NULL;
864         WIMStruct *w;
865         FILE *fp;
866         int image;
867         int ret;
868         int open_flags = WIMLIB_OPEN_FLAG_SHOW_PROGRESS | 
869                          WIMLIB_OPEN_FLAG_SPLIT_OK;
870         int part_number;
871         int total_parts;
872
873         for_opt(c, info_options) {
874                 switch (c) {
875                 case 'b':
876                         boot = true;
877                         break;
878                 case 'c':
879                         check = true;
880                         break;
881                 case 'h':
882                         header = true;
883                         short_header = false;
884                         break;
885                 case 'l':
886                         lookup_table = true;
887                         short_header = false;
888                         break;
889                 case 'x':
890                         xml = true;
891                         short_header = false;
892                         break;
893                 case 'X':
894                         xml_out_file = optarg;
895                         short_header = false;
896                         break;
897                 case 'm':
898                         metadata = true;
899                         short_header = false;
900                         break;
901                 default:
902                         usage(INFO);
903                         return -1;
904                 }
905         }
906
907         argc -= optind;
908         argv += optind;
909         if (argc == 0 || argc > 4) {
910                 usage(INFO);
911                 return -1;
912         }
913         wimfile = argv[0];
914         if (argc > 1) {
915                 image_num_or_name = argv[1];
916                 if (argc > 2) {
917                         new_name = argv[2];
918                         if (argc > 3) {
919                                 new_desc = argv[3];
920                         } 
921                 }
922         }
923
924         if (check)
925                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
926
927         ret = wimlib_open_wim(wimfile, open_flags, &w);
928         if (ret != 0)
929                 return ret;
930
931         part_number = wimlib_get_part_number(w, &total_parts);
932
933         /*if (total_parts > 1 && part_number > 1) {*/
934                 /*printf("Warning: this is part %d of a %d-part split WIM.\n"*/
935                        /*"         Select the first part if you want to see information\n"*/
936                        /*"         about images in the WIM.\n", */
937                        /*part_number, total_parts);*/
938         /*}*/
939
940         image = wimlib_resolve_image(w, image_num_or_name);
941         if (image == WIM_NO_IMAGE && strcmp(image_num_or_name, "0") != 0) {
942                 imagex_error("The image `%s' does not exist", 
943                                                 image_num_or_name);
944                 if (boot)
945                         imagex_error("If you would like to set the boot "
946                                      "index to 0, specify image \"0\" with "
947                                      "the --boot flag.");
948                 ret = WIMLIB_ERR_INVALID_IMAGE;
949                 goto done;
950         }
951
952         if (image == WIM_ALL_IMAGES && wimlib_get_num_images(w) > 1) {
953                 if (boot) {
954                         imagex_error("Cannot specify the --boot flag "
955                                      "without specifying a specific "
956                                      "image in a multi-image WIM");
957                         ret = WIMLIB_ERR_INVALID_IMAGE;
958                         goto done;
959                 }
960                 if (new_name) {
961                         imagex_error("Cannot specify the NEW_NAME "
962                                      "without specifying a specific "
963                                      "image in a multi-image WIM");
964                         ret = WIMLIB_ERR_INVALID_IMAGE;
965                         goto done;
966                 }
967         }
968
969         /* Operations that print information are separated from operations that
970          * recreate the WIM file. */
971         if (!new_name && !boot) {
972
973                 if (image == WIM_NO_IMAGE) {
974                         imagex_error("`%s' is not a valid image",
975                                      image_num_or_name);
976                         ret = WIMLIB_ERR_INVALID_IMAGE;
977                         goto done;
978                 }
979
980                 if (image == WIM_ALL_IMAGES && short_header)
981                         wimlib_print_wim_information(w);
982
983                 if (header)
984                         wimlib_print_header(w);
985
986                 if (lookup_table) {
987                         if (total_parts != 1) {
988                                 printf("Warning: Only showing the lookup table "
989                                        "for part %d of a %d-part WIM.\n",
990                                        part_number, total_parts);
991                         }
992                         wimlib_print_lookup_table(w);
993                 }
994
995                 if (xml) {
996                         ret = wimlib_extract_xml_data(w, stdout);
997                         if (ret != 0)
998                                 goto done;
999                 }
1000
1001                 if (xml_out_file) {
1002                         fp = fopen(xml_out_file, "wb");
1003                         if (!fp) {
1004                                 imagex_error_with_errno("Failed to open the "
1005                                                         "file `%s' for "
1006                                                         "writing ",
1007                                                         xml_out_file);
1008                                 goto done;
1009                         }
1010                         ret = wimlib_extract_xml_data(w, fp);
1011                         if (fclose(fp) != 0) {
1012                                 imagex_error("Failed to close the file `%s'",
1013                                              xml_out_file);
1014                                 goto done;
1015                         }
1016
1017                         if (ret != 0)
1018                                 goto done;
1019                 }
1020
1021                 if (short_header)
1022                         wimlib_print_available_images(w, image);
1023
1024                 if (metadata) {
1025                         if (total_parts != 1 && part_number != 1) {
1026                                 imagex_error("Select part 1 of this %d-part WIM "
1027                                              "to see the image metadata",
1028                                              total_parts);
1029                                 return WIMLIB_ERR_SPLIT_UNSUPPORTED;
1030                         }
1031                         ret = wimlib_print_metadata(w, image);
1032                         if (ret != 0)
1033                                 goto done;
1034                 }
1035         } else {
1036                 if (total_parts != 1) {
1037                         imagex_error("Modifying a split WIM is not supported.");
1038                         return -1;
1039                 }
1040                 if (image == WIM_ALL_IMAGES)
1041                         image = 1;
1042
1043                 if (image == WIM_NO_IMAGE && new_name) {
1044                         imagex_error("Cannot specify new_name (`%s') when "
1045                                      "using image 0", new_name);
1046                         return -1;
1047                 }
1048
1049                 if (boot) {
1050                         if (image == wimlib_get_boot_idx(w)) {
1051                                 printf("Image %d is already marked as "
1052                                        "bootable.\n", image);
1053                                 boot = false;
1054                         } else {
1055                                 printf("Marking image %d as bootable.\n",
1056                                        image);
1057                                 wimlib_set_boot_idx(w, image);
1058                         }
1059                 }
1060                 if (new_name) {
1061                         if (strcmp(wimlib_get_image_name(w, image), 
1062                                                 new_name) == 0) {
1063                                 printf("Image %d is already named \"%s\".\n",
1064                                        image, new_name);
1065                                 new_name = NULL;
1066                         } else {
1067                                 printf("Changing the name of image %d to "
1068                                        "\"%s\".\n", image, new_name);
1069                                 ret = wimlib_set_image_name(w, image, new_name);
1070                                 if (ret != 0)
1071                                         goto done;
1072                         }
1073                 }
1074                 if (new_desc) {
1075                         const char *old_desc;
1076                         old_desc = wimlib_get_image_description(w, image);
1077                         if (old_desc && strcmp(old_desc, new_desc) == 0) {
1078                                 printf("The description of image %d is already "
1079                                        "\"%s\".\n", image, new_desc);
1080                                 new_desc = NULL;
1081                         } else {
1082                                 printf("Changing the description of image %d "
1083                                        "to \"%s\".\n", image, new_desc);
1084                                 ret = wimlib_set_image_descripton(w, image, 
1085                                                                   new_desc);
1086                                 if (ret != 0)
1087                                         goto done;
1088                         }
1089                 }
1090
1091                 /* Only call wimlib_overwrite_xml_and_header() if something
1092                  * actually needs to be changed. */
1093                 if (boot || new_name || new_desc || 
1094                                 check != wimlib_has_integrity_table(w)) {
1095
1096                         ret = wimlib_overwrite_xml_and_header(w, check ? 
1097                                         WIMLIB_WRITE_FLAG_CHECK_INTEGRITY | 
1098                                         WIMLIB_WRITE_FLAG_SHOW_PROGRESS : 0);
1099                 } else {
1100                         printf("The file `%s' was not modified because nothing "
1101                                         "needed to be done.\n", wimfile);
1102                         ret = 0;
1103                 }
1104         }
1105
1106 done:
1107         wimlib_free(w);
1108         return ret;
1109 }
1110
1111 /* Join split WIMs into one part WIM */
1112 static int imagex_join(int argc, const char **argv)
1113 {
1114         int c;
1115         int flags = WIMLIB_OPEN_FLAG_SPLIT_OK | WIMLIB_OPEN_FLAG_SHOW_PROGRESS;
1116         const char *output_path;
1117
1118         for_opt(c, join_options) {
1119                 switch (c) {
1120                 case 'c':
1121                         flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1122                         break;
1123                 default:
1124                         goto err;
1125                 }
1126         }
1127         argc -= optind;
1128         argv += optind;
1129
1130         if (argc < 2) {
1131                 imagex_error("Must specify at least one split WIM (.swm) parts "
1132                              "to join");
1133                 goto err;
1134         }
1135         output_path = argv[0];
1136         return wimlib_join(++argv, --argc, output_path, flags);
1137 err:
1138         usage(JOIN);
1139         return -1;
1140 }
1141
1142 /* Mounts an image using a FUSE mount. */
1143 static int imagex_mount_rw_or_ro(int argc, const char **argv)
1144 {
1145         int c;
1146         int mount_flags = 0;
1147         int open_flags = WIMLIB_OPEN_FLAG_SHOW_PROGRESS;
1148         const char *wimfile;
1149         const char *dir;
1150         WIMStruct *w;
1151         int image;
1152         int num_images;
1153         int ret;
1154
1155         if (strcmp(argv[0], "mountrw") == 0)
1156                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
1157         for_opt(c, mount_options) {
1158                 switch (c) {
1159                 case 'c':
1160                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1161                         break;
1162                 case 'd':
1163                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
1164                         break;
1165                 case 's':
1166                         if (strcasecmp(optarg, "none") == 0)
1167                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
1168                         else if (strcasecmp(optarg, "xattr") == 0)
1169                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1170                         else if (strcasecmp(optarg, "windows") == 0)
1171                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
1172                         else {
1173                                 imagex_error("Unknown stream interface \"%s\"", optarg);
1174                                 goto mount_usage;
1175                         }
1176                         break;
1177                 default:
1178                         goto mount_usage;
1179                 }
1180         }
1181         argc -= optind;
1182         argv += optind;
1183         if (argc != 2 && argc != 3)
1184                 goto mount_usage;
1185
1186         wimfile = argv[0];
1187
1188         ret = wimlib_open_wim(wimfile, open_flags, &w);
1189         if (ret != 0)
1190                 return ret;
1191
1192         if (argc == 2) {
1193                 image = 1;
1194                 num_images = wimlib_get_num_images(w);
1195                 if (num_images != 1) {
1196                         imagex_error("The file `%s' contains %d images; Please "
1197                                      "select one", wimfile, num_images);
1198                         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)  
1199                                         ? MOUNTRW : MOUNT);
1200                         ret = WIMLIB_ERR_INVALID_IMAGE;
1201                         goto done;
1202                 }
1203                 dir = argv[1];
1204         } else {
1205                 image = wimlib_resolve_image(w, argv[1]);
1206                 dir = argv[2];
1207         }
1208
1209         ret = verify_image_exists_and_is_single(image);
1210         if (ret != 0)
1211                 goto done;
1212
1213         ret = wimlib_mount(w, image, dir, mount_flags);
1214         if (ret != 0) {
1215                 imagex_error("Failed to mount image %d from `%s' on `%s'",
1216                              image, wimfile, dir);
1217
1218         }
1219 done:
1220         wimlib_free(w);
1221         return ret;
1222 mount_usage:
1223         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)  
1224                         ? MOUNTRW : MOUNT);
1225         return -1;
1226 }
1227
1228 /* Split a WIM into a spanned set */
1229 static int imagex_split(int argc, const char **argv)
1230 {
1231         int c;
1232         int flags = WIMLIB_OPEN_FLAG_SHOW_PROGRESS;
1233         unsigned long part_size;
1234
1235         for_opt(c, split_options) {
1236                 switch (c) {
1237                 case 'c':
1238                         flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1239                         break;
1240                 default:
1241                         usage(SPLIT);
1242                         return -1;
1243                 }
1244         }
1245         argc -= optind;
1246         argv += optind;
1247
1248         if (argc != 3) {
1249                 usage(SPLIT);
1250                 return -1;
1251         }
1252         part_size = strtoul(argv[2], NULL, 10) * (1 << 20);
1253         return wimlib_split(argv[0], argv[1], part_size, flags);
1254 }
1255
1256 /* Unmounts an image. */
1257 static int imagex_unmount(int argc, const char **argv)
1258 {
1259         int c;
1260         int unmount_flags = 0;
1261         int ret;
1262
1263         for_opt(c, unmount_options) {
1264                 switch (c) {
1265                 case 'c':
1266                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
1267                         break;
1268                 case 'C':
1269                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
1270                         break;
1271                 default:
1272                         usage(UNMOUNT);
1273                         return -1;
1274                 }
1275         }
1276         argc -= optind;
1277         argv += optind;
1278         if (argc != 1) {
1279                 usage(UNMOUNT);
1280                 return -1;
1281         }
1282
1283         ret = wimlib_unmount(argv[0], unmount_flags);
1284         if (ret != 0)
1285                 imagex_error("Failed to unmount `%s'", argv[0]);
1286         return ret;
1287 }
1288
1289 struct imagex_command {
1290         const char *name;
1291         int (*func)(int , const char **);
1292         int cmd;
1293 };
1294
1295 static struct imagex_command imagex_commands[] = {
1296         {"append",  imagex_append,         APPEND},
1297         {"apply",   imagex_apply,          APPLY},
1298         {"capture", imagex_capture,        CAPTURE},
1299         {"delete",  imagex_delete,         DELETE},
1300         {"dir",     imagex_dir,            DIR},
1301         {"export",  imagex_export,         EXPORT},
1302         {"info",    imagex_info,           INFO},
1303         {"join",    imagex_join,           JOIN},
1304         {"mount",   imagex_mount_rw_or_ro, MOUNT},
1305         {"mountrw", imagex_mount_rw_or_ro, MOUNTRW},
1306         {"split",   imagex_split,          SPLIT},
1307         {"unmount", imagex_unmount,        UNMOUNT},
1308 };
1309
1310 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
1311                 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
1312
1313 static void help_or_version(int argc, const char **argv)
1314 {
1315         int i;
1316         const char *p;
1317         struct imagex_command *cmd;
1318
1319         for (i = 1; i < argc; i++) {
1320                 p = argv[i];
1321                 if (*p == '-')
1322                         p++;
1323                 else
1324                         continue;
1325                 if (*p == '-')
1326                         p++;
1327                 if (strcmp(p, "help") == 0 || (*p == '?' && *(p + 1) == '\0')) {
1328                         for_imagex_command(cmd) {
1329                                 if (strcmp(cmd->name, argv[1]) == 0) {
1330                                         usage(cmd->cmd);
1331                                         exit(0);
1332                                 }
1333                         }
1334                         usage_all();
1335                         exit(0);
1336                 }
1337                 if (strcmp(p, "version") == 0) {
1338                         version();
1339                         exit(0);
1340                 }
1341         }
1342 }
1343
1344
1345 int main(int argc, const char **argv)
1346 {
1347         struct imagex_command *cmd;
1348         int ret;
1349
1350         if (argc < 2) {
1351                 imagex_error("No command specified");
1352                 usage_all();
1353                 return 1;
1354         }
1355
1356         help_or_version(argc, argv);
1357         argc--;
1358         argv++;
1359
1360         wimlib_set_print_errors(true);
1361
1362         for_imagex_command(cmd) {
1363                 if (strcmp(cmd->name, *argv) == 0) {
1364                         ret = cmd->func(argc, argv);
1365                         if (ret > 0) {
1366                                 imagex_error("Exiting with error code %d:\n"
1367                                              "       %s.", ret,
1368                                              wimlib_get_error_string(ret));
1369                                 if (ret == WIMLIB_ERR_NTFS_3G)
1370                                         imagex_error_with_errno("errno");
1371                         }
1372                         return ret;
1373                 }
1374         }
1375
1376         imagex_error("Unrecognized command: `%s'", argv[0]);
1377         usage_all();
1378         return 1;
1379 }
1380 /*#ifndef WITH_NTFS_3G*/
1381                 /*ERROR("wimlib was not compiled with support for NTFS-3g, so we cannot extract");*/
1382                 /*ERROR("a WIM to a NTFS filesystem while preserving NTFS-specific metadata.");*/
1383                 /*ERROR("Please apply the WIM to a directory rather than a block device, ");*/
1384                 /*ERROR("and without the NTFS flag; or compile in support for NTFS-3g.");*/
1385                 /*return WIMLIB_ERR_UNSUPPORTED;*/
1386 /*#endif*/