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