c3ab4b737f08732adc534c2ee30f38da240720dd
[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 #include "wimlib_tchar.h"
27 #include "wimlib.h"
28
29 #include <ctype.h>
30 #include <errno.h>
31
32 #include <inttypes.h>
33 #include <libgen.h>
34 #include <limits.h>
35 #include <stdarg.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
40 #include <locale.h>
41
42 #ifdef HAVE_ALLOCA_H
43 #include <alloca.h>
44 #endif
45
46 #ifdef __WIN32__
47 #  include "imagex-win32.h"
48 #  define tbasename     win32_wbasename
49 #  define tglob         win32_wglob
50 #else /* __WIN32__ */
51 #  include <glob.h>
52 #  include <getopt.h>
53 #  include <langinfo.h>
54 #  define tbasename     basename
55 #  define tglob         glob
56 #endif /* !__WIN32 */
57
58
59 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
60
61 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (tchar**)argv, T(""), \
62                                 opts, NULL)) != -1)
63
64 enum imagex_op_type {
65         APPEND = 0,
66         APPLY,
67         CAPTURE,
68         DELETE,
69         DIR,
70         EXPORT,
71         INFO,
72         JOIN,
73         MOUNT,
74         MOUNTRW,
75         OPTIMIZE,
76         SPLIT,
77         UNMOUNT,
78 };
79
80 static void usage(int cmd_type);
81 static void usage_all();
82
83
84 static const tchar *usage_strings[] = {
85 [APPEND] =
86 T(
87 IMAGEX_PROGNAME" append (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
88 "                     [DESCRIPTION] [--boot] [--check] [--flags EDITION_ID]\n"
89 "                     [--verbose] [--dereference] [--config=FILE]\n"
90 "                     [--threads=NUM_THREADS] [--rebuild] [--unix-data]\n"
91 "                     [--source-list] [--no-acls] [--strict-acls]\n"
92 ),
93 [APPLY] =
94 T(
95 IMAGEX_PROGNAME" apply WIMFILE [IMAGE_NUM | IMAGE_NAME | all]\n"
96 "                    (DIRECTORY | NTFS_VOLUME) [--check] [--hardlink]\n"
97 "                    [--symlink] [--verbose] [--ref=\"GLOB\"] [--unix-data]\n"
98 "                    [--no-acls] [--strict-acls]\n"
99 ),
100 [CAPTURE] =
101 T(
102 IMAGEX_PROGNAME" capture (DIRECTORY | NTFS_VOLUME) WIMFILE [IMAGE_NAME]\n"
103 "                      [DESCRIPTION] [--boot] [--check] [--compress=TYPE]\n"
104 "                      [--flags EDITION_ID] [--verbose] [--dereference]\n"
105 "                      [--config=FILE] [--threads=NUM_THREADS] [--unix-data]\n"
106 "                      [--source-list] [--no-acls] [--strict-acls]\n"
107 ),
108 [DELETE] =
109 T(
110 IMAGEX_PROGNAME" delete WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check] [--soft]\n"
111 ),
112 [DIR] =
113 T(
114 IMAGEX_PROGNAME" dir WIMFILE (IMAGE_NUM | IMAGE_NAME | all)\n"
115 ),
116 [EXPORT] =
117 T(
118 IMAGEX_PROGNAME" export SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
119 "              DEST_WIMFILE [DEST_IMAGE_NAME] [DEST_IMAGE_DESCRIPTION]\n"
120 "              [--boot] [--check] [--compress=TYPE] [--ref=\"GLOB\"]\n"
121 "              [--threads=NUM_THREADS] [--rebuild]\n"
122 ),
123 [INFO] =
124 T(
125 IMAGEX_PROGNAME" info WIMFILE [IMAGE_NUM | IMAGE_NAME] [NEW_NAME]\n"
126 "                   [NEW_DESC] [--boot] [--check] [--header] [--lookup-table]\n"
127 "                   [--xml] [--extract-xml FILE] [--metadata]\n"
128 ),
129 [JOIN] =
130 T(
131 IMAGEX_PROGNAME" join [--check] WIMFILE SPLIT_WIM...\n"
132 ),
133 [MOUNT] =
134 T(
135 IMAGEX_PROGNAME" mount WIMFILE (IMAGE_NUM | IMAGE_NAME) DIRECTORY\n"
136 "                    [--check] [--debug] [--streams-interface=INTERFACE]\n"
137 "                    [--ref=\"GLOB\"] [--unix-data] [--allow-other]\n"
138 ),
139 [MOUNTRW] =
140 T(
141 IMAGEX_PROGNAME" mountrw WIMFILE [IMAGE_NUM | IMAGE_NAME] DIRECTORY\n"
142 "                      [--check] [--debug] [--streams-interface=INTERFACE]\n"
143 "                      [--staging-dir=DIR] [--unix-data] [--allow-other]\n"
144 ),
145 [OPTIMIZE] =
146 T(
147 IMAGEX_PROGNAME" optimize WIMFILE [--check] [--recompress]\n"
148 ),
149 [SPLIT] =
150 T(
151 IMAGEX_PROGNAME" split WIMFILE SPLIT_WIMFILE PART_SIZE_MB [--check]\n"
152 ),
153 [UNMOUNT] =
154 T(
155 IMAGEX_PROGNAME" unmount DIRECTORY [--commit] [--check] [--rebuild]\n"
156 ),
157 };
158
159 enum {
160         IMAGEX_ALLOW_OTHER_OPTION,
161         IMAGEX_BOOT_OPTION,
162         IMAGEX_CHECK_OPTION,
163         IMAGEX_COMMIT_OPTION,
164         IMAGEX_COMPRESS_OPTION,
165         IMAGEX_CONFIG_OPTION,
166         IMAGEX_DEBUG_OPTION,
167         IMAGEX_DEREFERENCE_OPTION,
168         IMAGEX_EXTRACT_XML_OPTION,
169         IMAGEX_FLAGS_OPTION,
170         IMAGEX_HARDLINK_OPTION,
171         IMAGEX_HEADER_OPTION,
172         IMAGEX_LOOKUP_TABLE_OPTION,
173         IMAGEX_METADATA_OPTION,
174         IMAGEX_NO_ACLS_OPTION,
175         IMAGEX_REBULID_OPTION,
176         IMAGEX_RECOMPRESS_OPTION,
177         IMAGEX_REF_OPTION,
178         IMAGEX_SOFT_OPTION,
179         IMAGEX_SOURCE_LIST_OPTION,
180         IMAGEX_STAGING_DIR_OPTION,
181         IMAGEX_STREAMS_INTERFACE_OPTION,
182         IMAGEX_STRICT_ACLS_OPTION,
183         IMAGEX_SYMLINK_OPTION,
184         IMAGEX_THREADS_OPTION,
185         IMAGEX_UNIX_DATA_OPTION,
186         IMAGEX_VERBOSE_OPTION,
187         IMAGEX_XML_OPTION,
188 };
189
190 static const struct option apply_options[] = {
191         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
192         {T("hardlink"),    no_argument,       NULL, IMAGEX_HARDLINK_OPTION},
193         {T("symlink"),     no_argument,       NULL, IMAGEX_SYMLINK_OPTION},
194         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
195         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
196         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
197         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
198         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
199         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
200         {NULL, 0, NULL, 0},
201 };
202 static const struct option capture_or_append_options[] = {
203         {T("boot"),        no_argument,       NULL, IMAGEX_BOOT_OPTION},
204         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
205         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
206         {T("config"),      required_argument, NULL, IMAGEX_CONFIG_OPTION},
207         {T("dereference"), no_argument,       NULL, IMAGEX_DEREFERENCE_OPTION},
208         {T("flags"),       required_argument, NULL, IMAGEX_FLAGS_OPTION},
209         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
210         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
211         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBULID_OPTION},
212         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
213         {T("source-list"), no_argument,       NULL, IMAGEX_SOURCE_LIST_OPTION},
214         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
215         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
216         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
217         {NULL, 0, NULL, 0},
218 };
219 static const struct option delete_options[] = {
220         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
221         {T("soft"),  no_argument, NULL, IMAGEX_SOFT_OPTION},
222         {NULL, 0, NULL, 0},
223 };
224
225 static const struct option export_options[] = {
226         {T("boot"),       no_argument,       NULL, IMAGEX_BOOT_OPTION},
227         {T("check"),      no_argument,       NULL, IMAGEX_CHECK_OPTION},
228         {T("compress"),   required_argument, NULL, IMAGEX_COMPRESS_OPTION},
229         {T("ref"),        required_argument, NULL, IMAGEX_REF_OPTION},
230         {T("threads"),    required_argument, NULL, IMAGEX_THREADS_OPTION},
231         {T("rebuild"),    no_argument,       NULL, IMAGEX_REBULID_OPTION},
232         {NULL, 0, NULL, 0},
233 };
234
235 static const struct option info_options[] = {
236         {T("boot"),         no_argument,       NULL, IMAGEX_BOOT_OPTION},
237         {T("check"),        no_argument,       NULL, IMAGEX_CHECK_OPTION},
238         {T("extract-xml"),  required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
239         {T("header"),       no_argument,       NULL, IMAGEX_HEADER_OPTION},
240         {T("lookup-table"), no_argument,       NULL, IMAGEX_LOOKUP_TABLE_OPTION},
241         {T("metadata"),     no_argument,       NULL, IMAGEX_METADATA_OPTION},
242         {T("xml"),          no_argument,       NULL, IMAGEX_XML_OPTION},
243         {NULL, 0, NULL, 0},
244 };
245
246 static const struct option join_options[] = {
247         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
248         {NULL, 0, NULL, 0},
249 };
250
251 static const struct option mount_options[] = {
252         {T("check"),             no_argument,       NULL, IMAGEX_CHECK_OPTION},
253         {T("debug"),             no_argument,       NULL, IMAGEX_DEBUG_OPTION},
254         {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
255         {T("ref"),               required_argument, NULL, IMAGEX_REF_OPTION},
256         {T("staging-dir"),       required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
257         {T("unix-data"),         no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
258         {T("allow-other"),       no_argument,       NULL, IMAGEX_ALLOW_OTHER_OPTION},
259         {NULL, 0, NULL, 0},
260 };
261
262 static const struct option optimize_options[] = {
263         {T("check"),      no_argument, NULL, IMAGEX_CHECK_OPTION},
264         {T("recompress"), no_argument, NULL, IMAGEX_RECOMPRESS_OPTION},
265         {NULL, 0, NULL, 0},
266 };
267
268 static const struct option split_options[] = {
269         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
270         {NULL, 0, NULL, 0},
271 };
272
273 static const struct option unmount_options[] = {
274         {T("commit"),  no_argument, NULL, IMAGEX_COMMIT_OPTION},
275         {T("check"),   no_argument, NULL, IMAGEX_CHECK_OPTION},
276         {T("rebuild"), no_argument, NULL, IMAGEX_REBULID_OPTION},
277         {NULL, 0, NULL, 0},
278 };
279
280
281
282 /* Print formatted error message to stderr. */
283 static void
284 imagex_error(const tchar *format, ...)
285 {
286         va_list va;
287         va_start(va, format);
288         tfputs(T("ERROR: "), stderr);
289         tvfprintf(stderr, format, va);
290         tputc(T('\n'), stderr);
291         va_end(va);
292 }
293
294 /* Print formatted error message to stderr. */
295 static void
296 imagex_error_with_errno(const tchar *format, ...)
297 {
298         int errno_save = errno;
299         va_list va;
300         va_start(va, format);
301         tfputs(T("ERROR: "), stderr);
302         tvfprintf(stderr, format, va);
303         tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
304         va_end(va);
305 }
306
307 static int
308 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
309 {
310         if (image == WIMLIB_NO_IMAGE) {
311                 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
312                              "       Please specify a 1-based image index or "
313                              "image name.\n"
314                              "       You may use `"IMAGEX_PROGNAME" info' to list the images "
315                              "contained in a WIM."),
316                              image_name, wim_name);
317                 return -1;
318         }
319         return 0;
320 }
321
322 static int
323 verify_image_is_single(int image)
324 {
325         if (image == WIMLIB_ALL_IMAGES) {
326                 imagex_error(T("Cannot specify all images for this action!"));
327                 return -1;
328         }
329         return 0;
330 }
331
332 static int
333 verify_image_exists_and_is_single(int image, const tchar *image_name,
334                                   const tchar *wim_name)
335 {
336         int ret;
337         ret = verify_image_exists(image, image_name, wim_name);
338         if (ret == 0)
339                 ret = verify_image_is_single(image);
340         return ret;
341 }
342
343 /* Parse the argument to --compress */
344 static int
345 get_compression_type(const tchar *optarg)
346 {
347         if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
348                 return WIMLIB_COMPRESSION_TYPE_LZX;
349         else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
350                 return WIMLIB_COMPRESSION_TYPE_XPRESS;
351         else if (!tstrcasecmp(optarg, T("none")))
352                 return WIMLIB_COMPRESSION_TYPE_NONE;
353         else {
354                 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
355                              "\"maximum\", \"fast\", or \"none\"."), optarg);
356                 return WIMLIB_COMPRESSION_TYPE_INVALID;
357         }
358 }
359
360 /* Returns the size of a file given its name, or -1 if the file does not exist
361  * or its size cannot be determined.  */
362 static off_t
363 file_get_size(const tchar *filename)
364 {
365         struct stat st;
366         if (tstat(filename, &st) == 0)
367                 return st.st_size;
368         else
369                 return (off_t)-1;
370 }
371
372 static const tchar *default_capture_config =
373 T(
374 "[ExclusionList]\n"
375 "\\$ntfs.log\n"
376 "\\hiberfil.sys\n"
377 "\\pagefile.sys\n"
378 "\\System Volume Information\n"
379 "\\RECYCLER\n"
380 "\\Windows\\CSC\n"
381 "\n"
382 "[CompressionExclusionList]\n"
383 "*.mp3\n"
384 "*.zip\n"
385 "*.cab\n"
386 "\\WINDOWS\\inf\\*.pnf\n"
387 );
388
389 enum {
390         PARSE_FILENAME_SUCCESS = 0,
391         PARSE_FILENAME_FAILURE = 1,
392         PARSE_FILENAME_NONE = 2,
393 };
394
395 /*
396  * Parses a filename in the source list file format.  (See the man page for
397  * 'wimlib-imagex capture' for details on this format and the meaning.)
398  * Accepted formats for filenames are an unquoted string (whitespace-delimited),
399  * or a double or single-quoted string.
400  *
401  * @line_p:  Pointer to the pointer to the line of data.  Will be updated
402  *           to point past the filename iff the return value is
403  *           PARSE_FILENAME_SUCCESS.  If *len_p > 0, (*line_p)[*len_p - 1] must
404  *           be '\0'.
405  *
406  * @len_p:   @len_p initially stores the length of the line of data, which may
407  *           be 0, and it will be updated to the number of bytes remaining in
408  *           the line iff the return value is PARSE_FILENAME_SUCCESS.
409  *
410  * @fn_ret:  Iff the return value is PARSE_FILENAME_SUCCESS, a pointer to the
411  *           parsed filename will be returned here.
412  *
413  * Returns: PARSE_FILENAME_SUCCESS if a filename was successfully parsed; or
414  *          PARSE_FILENAME_FAILURE if the data was invalid due to a missing
415  *          closing quote; or PARSE_FILENAME_NONE if the line ended before the
416  *          beginning of a filename was found.
417  */
418 static int
419 parse_filename(tchar **line_p, size_t *len_p, tchar **fn_ret)
420 {
421         size_t len = *len_p;
422         tchar *line = *line_p;
423         tchar *fn;
424         tchar quote_char;
425
426         /* Skip leading whitespace */
427         for (;;) {
428                 if (len == 0)
429                         return PARSE_FILENAME_NONE;
430                 if (!istspace(*line) && *line != T('\0'))
431                         break;
432                 line++;
433                 len--;
434         }
435         quote_char = *line;
436         if (quote_char == T('"') || quote_char == T('\'')) {
437                 /* Quoted filename */
438                 line++;
439                 len--;
440                 fn = line;
441                 line = tmemchr(line, quote_char, len);
442                 if (!line) {
443                         imagex_error(T("Missing closing quote: %"TS), fn - 1);
444                         return PARSE_FILENAME_FAILURE;
445                 }
446         } else {
447                 /* Unquoted filename.  Go until whitespace.  Line is terminated
448                  * by '\0', so no need to check 'len'. */
449                 fn = line;
450                 do {
451                         line++;
452                 } while (!istspace(*line) && *line != T('\0'));
453         }
454         *line = T('\0');
455         len -= line - fn;
456         *len_p = len;
457         *line_p = line;
458         *fn_ret = fn;
459         return PARSE_FILENAME_SUCCESS;
460 }
461
462 /* Parses a line of data (not an empty line or comment) in the source list file
463  * format.  (See the man page for 'wimlib-imagex capture' for details on this
464  * format and the meaning.)
465  *
466  * @line:  Line of data to be parsed.  line[len - 1] must be '\0', unless
467  *         len == 0.  The data in @line will be modified by this function call.
468  *
469  * @len:   Length of the line of data.
470  *
471  * @source:  On success, the capture source and target described by the line is
472  *           written into this destination.  Note that it will contain pointers
473  *           to data in the @line array.
474  *
475  * Returns true if the line was valid; false otherwise.  */
476 static bool
477 parse_source_list_line(tchar *line, size_t len,
478                        struct wimlib_capture_source *source)
479 {
480         /* SOURCE [DEST] */
481         int ret;
482         ret = parse_filename(&line, &len, &source->fs_source_path);
483         if (ret != PARSE_FILENAME_SUCCESS)
484                 return false;
485         ret = parse_filename(&line, &len, &source->wim_target_path);
486         if (ret == PARSE_FILENAME_NONE)
487                 source->wim_target_path = source->fs_source_path;
488         return ret != PARSE_FILENAME_FAILURE;
489 }
490
491 /* Returns %true if the given line of length @len > 0 is a comment or empty line
492  * in the source list file format. */
493 static bool
494 is_comment_line(const tchar *line, size_t len)
495 {
496         for (;;) {
497                 if (*line == T('#'))
498                         return true;
499                 if (!istspace(*line) && *line != T('\0'))
500                         return false;
501                 ++line;
502                 --len;
503                 if (len == 0)
504                         return true;
505         }
506 }
507
508 /* Parses a file in the source list format.  (See the man page for
509  * 'wimlib-imagex capture' for details on this format and the meaning.)
510  *
511  * @source_list_contents:  Contents of the source list file.  Note that this
512  *                         buffer will be modified to save memory allocations,
513  *                         and cannot be freed until the returned array of
514  *                         wimlib_capture_source's has also been freed.
515  *
516  * @source_list_nbytes:    Number of bytes of data in the @source_list_contents
517  *                         buffer.
518  *
519  * @nsources_ret:          On success, the length of the returned array is
520  *                         returned here.
521  *
522  * Returns:   An array of `struct wimlib_capture_source's that can be passed to
523  * the wimlib_add_image_multisource() function to specify how a WIM image is to
524  * be created.  */
525 static struct wimlib_capture_source *
526 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
527                   size_t *nsources_ret)
528 {
529         size_t nlines;
530         tchar *p;
531         struct wimlib_capture_source *sources;
532         size_t i, j;
533         tchar *source_list_contents = *source_list_contents_p;
534
535         nlines = 0;
536         for (i = 0; i < source_list_nchars; i++)
537                 if (source_list_contents[i] == T('\n'))
538                         nlines++;
539
540         /* Handle last line not terminated by a newline */
541         if (source_list_nchars != 0 &&
542             source_list_contents[source_list_nchars - 1] != T('\n'))
543         {
544                 source_list_contents = realloc(source_list_contents,
545                                                (source_list_nchars + 1) * sizeof(tchar));
546                 if (!source_list_contents)
547                         goto oom;
548                 source_list_contents[source_list_nchars] = T('\n');
549                 *source_list_contents_p = source_list_contents;
550                 source_list_nchars++;
551                 nlines++;
552         }
553
554         sources = calloc(nlines, sizeof(*sources));
555         if (!sources)
556                 goto oom;
557         p = source_list_contents;
558         j = 0;
559         for (i = 0; i < nlines; i++) {
560                 /* XXX: Could use rawmemchr() here instead, but it may not be
561                  * available on all platforms. */
562                 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
563                 size_t len = endp - p + 1;
564                 *endp = T('\0');
565                 if (!is_comment_line(p, len)) {
566                         if (!parse_source_list_line(p, len, &sources[j++])) {
567                                 free(sources);
568                                 return NULL;
569                         }
570                 }
571                 p = endp + 1;
572
573         }
574         *nsources_ret = j;
575         return sources;
576 oom:
577         imagex_error(T("out of memory"));
578         return NULL;
579 }
580
581 /* Reads the contents of a file into memory. */
582 static char *
583 file_get_contents(const tchar *filename, size_t *len_ret)
584 {
585         struct stat stbuf;
586         void *buf = NULL;
587         size_t len;
588         FILE *fp;
589
590         if (tstat(filename, &stbuf) != 0) {
591                 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
592                 goto out;
593         }
594         len = stbuf.st_size;
595
596         fp = tfopen(filename, T("rb"));
597         if (!fp) {
598                 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
599                 goto out;
600         }
601
602         buf = malloc(len);
603         if (!buf) {
604                 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
605                                "contents of file \"%"TS"\""), len, filename);
606                 goto out_fclose;
607         }
608         if (fread(buf, 1, len, fp) != len) {
609                 imagex_error_with_errno(T("Failed to read %zu bytes from the "
610                                           "file \"%"TS"\""), len, filename);
611                 goto out_free_buf;
612         }
613         *len_ret = len;
614         goto out_fclose;
615 out_free_buf:
616         free(buf);
617         buf = NULL;
618 out_fclose:
619         fclose(fp);
620 out:
621         return buf;
622 }
623
624 /* Read standard input until EOF and return the full contents in a malloc()ed
625  * buffer and the number of bytes of data in @len_ret.  Returns NULL on read
626  * error. */
627 static char *
628 stdin_get_contents(size_t *len_ret)
629 {
630         /* stdin can, of course, be a pipe or other non-seekable file, so the
631          * total length of the data cannot be pre-determined */
632         char *buf = NULL;
633         size_t newlen = 1024;
634         size_t pos = 0;
635         size_t inc = 1024;
636         for (;;) {
637                 char *p = realloc(buf, newlen);
638                 size_t bytes_read, bytes_to_read;
639                 if (!p) {
640                         imagex_error(T("out of memory while reading stdin"));
641                         break;
642                 }
643                 buf = p;
644                 bytes_to_read = newlen - pos;
645                 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
646                 pos += bytes_read;
647                 if (bytes_read != bytes_to_read) {
648                         if (feof(stdin)) {
649                                 *len_ret = pos;
650                                 return buf;
651                         } else {
652                                 imagex_error_with_errno(T("error reading stdin"));
653                                 break;
654                         }
655                 }
656                 newlen += inc;
657                 inc *= 3;
658                 inc /= 2;
659         }
660         free(buf);
661         return NULL;
662 }
663
664
665 static tchar *
666 translate_text_to_tstr(char *text, size_t num_bytes,
667                        size_t *num_tchars_ret)
668 {
669 #ifndef __WIN32__
670         /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
671          * */
672         *num_tchars_ret = num_bytes;
673         return text;
674 #else /* !__WIN32__ */
675         /* On Windows, translate the text to UTF-16LE */
676         wchar_t *text_wstr;
677         size_t num_wchars;
678
679         if (num_bytes >= 2 &&
680             ((text[0] == 0xff && text[1] == 0xfe) ||
681              (text[0] <= 0x7f && text[1] == 0x00)))
682         {
683                 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
684                  * with something that looks like an ASCII character encoded as
685                  * a UTF-16LE code unit.  Assume the file is encoded as
686                  * UTF-16LE.  This is not a 100% reliable check. */
687                 num_wchars = num_bytes / 2;
688                 text_wstr = (wchar_t*)text;
689         } else {
690                 /* File does not look like UTF-16LE.  Assume it is encoded in
691                  * the current Windows code page.  I think these are always
692                  * ASCII-compatible, so any so-called "plain-text" (ASCII) files
693                  * should work as expected. */
694                 text_wstr = win32_mbs_to_wcs(text,
695                                              num_bytes,
696                                              &num_wchars);
697                 free(text);
698         }
699         *num_tchars_ret = num_wchars;
700         return text_wstr;
701 #endif /* __WIN32__ */
702 }
703
704 static tchar *
705 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
706 {
707         char *contents;
708         size_t num_bytes;
709
710         contents = file_get_contents(filename, &num_bytes);
711         if (!contents)
712                 return NULL;
713         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
714 }
715
716 static tchar *
717 stdin_get_text_contents(size_t *num_tchars_ret)
718 {
719         char *contents;
720         size_t num_bytes;
721
722         contents = stdin_get_contents(&num_bytes);
723         if (!contents)
724                 return NULL;
725         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
726 }
727
728 /* Return 0 if a path names a file to which the current user has write access;
729  * -1 otherwise (and print an error message). */
730 static int
731 file_writable(const tchar *path)
732 {
733         int ret;
734         ret = taccess(path, W_OK);
735         if (ret != 0)
736                 imagex_error_with_errno(T("Can't modify \"%"TS"\""), path);
737         return ret;
738 }
739
740 #define TO_PERCENT(numerator, denominator) \
741         (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
742
743 /* Given an enumerated value for WIM compression type, return a descriptive
744  * string. */
745 static const tchar *
746 get_data_type(int ctype)
747 {
748         switch (ctype) {
749         case WIMLIB_COMPRESSION_TYPE_NONE:
750                 return T("uncompressed");
751         case WIMLIB_COMPRESSION_TYPE_LZX:
752                 return T("LZX-compressed");
753         case WIMLIB_COMPRESSION_TYPE_XPRESS:
754                 return T("XPRESS-compressed");
755         }
756         return NULL;
757 }
758
759 /* Progress callback function passed to various wimlib functions. */
760 static int
761 imagex_progress_func(enum wimlib_progress_msg msg,
762                      const union wimlib_progress_info *info)
763 {
764         unsigned percent_done;
765         switch (msg) {
766         case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
767                 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
768                                           info->write_streams.total_bytes);
769                 if (info->write_streams.completed_streams == 0) {
770                         const tchar *data_type;
771
772                         data_type = get_data_type(info->write_streams.compression_type);
773                         tprintf(T("Writing %"TS" data using %u thread%"TS"\n"),
774                                 data_type, info->write_streams.num_threads,
775                                 (info->write_streams.num_threads == 1) ? T("") : T("s"));
776                 }
777                 tprintf(T("\r%"PRIu64" MiB of %"PRIu64" MiB (uncompressed) "
778                         "written (%u%% done)"),
779                         info->write_streams.completed_bytes >> 20,
780                         info->write_streams.total_bytes >> 20,
781                         percent_done);
782                 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
783                         tputchar(T('\n'));
784                 break;
785         case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
786                 tprintf(T("Scanning \"%"TS"\""), info->scan.source);
787                 if (*info->scan.wim_target_path) {
788                         tprintf(T(" (loading as WIM path: \"/%"TS"\")...\n"),
789                                info->scan.wim_target_path);
790                 } else {
791                         tprintf(T(" (loading as root of WIM image)...\n"));
792                 }
793                 break;
794         case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
795                 if (info->scan.excluded)
796                         tprintf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
797                 else
798                         tprintf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
799                 break;
800         /*case WIMLIB_PROGRESS_MSG_SCAN_END:*/
801                 /*break;*/
802         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
803                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
804                                           info->integrity.total_bytes);
805                 tprintf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" MiB "
806                         "of %"PRIu64" MiB (%u%%) done"),
807                         info->integrity.filename,
808                         info->integrity.completed_bytes >> 20,
809                         info->integrity.total_bytes >> 20,
810                         percent_done);
811                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
812                         tputchar(T('\n'));
813                 break;
814         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
815                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
816                                           info->integrity.total_bytes);
817                 tprintf(T("\rCalculating integrity table for WIM: %"PRIu64" MiB "
818                           "of %"PRIu64" MiB (%u%%) done"),
819                         info->integrity.completed_bytes >> 20,
820                         info->integrity.total_bytes >> 20,
821                         percent_done);
822                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
823                         tputchar(T('\n'));
824                 break;
825         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
826                 tprintf(T("Applying image %d (%"TS") from \"%"TS"\" "
827                           "to %"TS" \"%"TS"\"\n"),
828                         info->extract.image,
829                         info->extract.image_name,
830                         info->extract.wimfile_name,
831                         ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
832                          T("NTFS volume") : T("directory")),
833                         info->extract.target);
834                 break;
835         /*case WIMLIB_PROGRESS_MSG_EXTRACT_DIR_STRUCTURE_BEGIN:*/
836                 /*tprintf(T("Applying directory structure to %"TS"\n"),*/
837                         /*info->extract.target);*/
838                 /*break;*/
839         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
840                 percent_done = TO_PERCENT(info->extract.completed_bytes,
841                                           info->extract.total_bytes);
842                 tprintf(T("\rExtracting files: "
843                           "%"PRIu64" MiB of %"PRIu64" MiB (%u%%) done"),
844                         info->extract.completed_bytes >> 20,
845                         info->extract.total_bytes >> 20,
846                         percent_done);
847                 if (info->extract.completed_bytes >= info->extract.total_bytes)
848                         tputchar(T('\n'));
849                 break;
850         case WIMLIB_PROGRESS_MSG_EXTRACT_DENTRY:
851                 tprintf(T("%"TS"\n"), info->extract.cur_path);
852                 break;
853         case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
854                 tprintf(T("Setting timestamps on all extracted files...\n"));
855                 break;
856         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
857                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
858                         tprintf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
859                                 info->extract.target);
860                 }
861                 break;
862         case WIMLIB_PROGRESS_MSG_JOIN_STREAMS:
863                 percent_done = TO_PERCENT(info->join.completed_bytes,
864                                           info->join.total_bytes);
865                 tprintf(T("Writing resources from part %u of %u: "
866                           "%"PRIu64 " MiB of %"PRIu64" MiB (%u%%) written\n"),
867                         (info->join.completed_parts == info->join.total_parts) ?
868                         info->join.completed_parts : info->join.completed_parts + 1,
869                         info->join.total_parts,
870                         info->join.completed_bytes >> 20,
871                         info->join.total_bytes >> 20,
872                         percent_done);
873                 break;
874         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
875                 percent_done = TO_PERCENT(info->split.completed_bytes,
876                                           info->split.total_bytes);
877                 tprintf(T("Writing \"%"TS"\": %"PRIu64" MiB of "
878                           "%"PRIu64" MiB (%u%%) written\n"),
879                         info->split.part_name,
880                         info->split.completed_bytes >> 20,
881                         info->split.total_bytes >> 20,
882                         percent_done);
883                 break;
884         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
885                 if (info->split.completed_bytes == info->split.total_bytes) {
886                         tprintf(T("Finished writing %u split WIM parts\n"),
887                                 info->split.cur_part_number);
888                 }
889                 break;
890         default:
891                 break;
892         }
893         fflush(stdout);
894         return 0;
895 }
896
897 /* Open all the split WIM parts that correspond to a file glob.
898  *
899  * @first_part specifies the first part of the split WIM and it may be either
900  * included or omitted from the glob. */
901 static int
902 open_swms_from_glob(const tchar *swm_glob,
903                     const tchar *first_part,
904                     int open_flags,
905                     WIMStruct ***additional_swms_ret,
906                     unsigned *num_additional_swms_ret)
907 {
908         unsigned num_additional_swms = 0;
909         WIMStruct **additional_swms = NULL;
910         glob_t globbuf;
911         int ret;
912
913         /* Warning: glob() is replaced in Windows native builds */
914         ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
915         if (ret != 0) {
916                 if (ret == GLOB_NOMATCH) {
917                         imagex_error(T("Found no files for glob \"%"TS"\""),
918                                      swm_glob);
919                 } else {
920                         imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
921                                                 swm_glob);
922                 }
923                 ret = -1;
924                 goto out;
925         }
926         num_additional_swms = globbuf.gl_pathc;
927         additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
928         if (!additional_swms) {
929                 imagex_error(T("Out of memory"));
930                 ret = -1;
931                 goto out_globfree;
932         }
933         unsigned offset = 0;
934         for (unsigned i = 0; i < num_additional_swms; i++) {
935                 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
936                         offset++;
937                         continue;
938                 }
939                 ret = wimlib_open_wim(globbuf.gl_pathv[i],
940                                       open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
941                                       &additional_swms[i - offset],
942                                       imagex_progress_func);
943                 if (ret != 0)
944                         goto out_close_swms;
945         }
946         *additional_swms_ret = additional_swms;
947         *num_additional_swms_ret = num_additional_swms - offset;
948         ret = 0;
949         goto out_globfree;
950 out_close_swms:
951         for (unsigned i = 0; i < num_additional_swms; i++)
952                 wimlib_free(additional_swms[i]);
953         free(additional_swms);
954 out_globfree:
955         globfree(&globbuf);
956 out:
957         return ret;
958 }
959
960
961 static unsigned
962 parse_num_threads(const tchar *optarg)
963 {
964         tchar *tmp;
965         unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
966         if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
967                 imagex_error(T("Number of threads must be a non-negative integer!"));
968                 return UINT_MAX;
969         } else {
970                 return ul_nthreads;
971         }
972 }
973
974
975 /* Apply one image, or all images, from a WIM file into a directory, OR apply
976  * one image from a WIM file to a NTFS volume. */
977 static int
978 imagex_apply(int argc, tchar **argv)
979 {
980         int c;
981         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
982         int image;
983         int num_images;
984         WIMStruct *w;
985         int ret;
986         const tchar *wimfile;
987         const tchar *target;
988         const tchar *image_num_or_name;
989         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
990
991         const tchar *swm_glob = NULL;
992         WIMStruct **additional_swms = NULL;
993         unsigned num_additional_swms = 0;
994
995         for_opt(c, apply_options) {
996                 switch (c) {
997                 case IMAGEX_CHECK_OPTION:
998                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
999                         break;
1000                 case IMAGEX_HARDLINK_OPTION:
1001                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1002                         break;
1003                 case IMAGEX_SYMLINK_OPTION:
1004                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1005                         break;
1006                 case IMAGEX_VERBOSE_OPTION:
1007                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1008                         break;
1009                 case IMAGEX_REF_OPTION:
1010                         swm_glob = optarg;
1011                         break;
1012                 case IMAGEX_UNIX_DATA_OPTION:
1013                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1014                         break;
1015                 case IMAGEX_NO_ACLS_OPTION:
1016                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1017                         break;
1018                 case IMAGEX_STRICT_ACLS_OPTION:
1019                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1020                         break;
1021                 default:
1022                         usage(APPLY);
1023                         return -1;
1024                 }
1025         }
1026         argc -= optind;
1027         argv += optind;
1028         if (argc != 2 && argc != 3) {
1029                 usage(APPLY);
1030                 return -1;
1031         }
1032
1033         wimfile = argv[0];
1034         if (argc == 2) {
1035                 image_num_or_name = T("1");
1036                 target = argv[1];
1037         } else {
1038                 image_num_or_name = argv[1];
1039                 target = argv[2];
1040         }
1041
1042         ret = wimlib_open_wim(wimfile, open_flags, &w, imagex_progress_func);
1043         if (ret != 0)
1044                 return ret;
1045
1046         image = wimlib_resolve_image(w, image_num_or_name);
1047         ret = verify_image_exists(image, image_num_or_name, wimfile);
1048         if (ret != 0)
1049                 goto out;
1050
1051         num_images = wimlib_get_num_images(w);
1052         if (argc == 2 && num_images != 1) {
1053                 imagex_error(T("\"%"TS"\" contains %d images; Please select one "
1054                                "(or all)"), wimfile, num_images);
1055                 usage(APPLY);
1056                 ret = -1;
1057                 goto out;
1058         }
1059
1060         if (swm_glob) {
1061                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1062                                           &additional_swms,
1063                                           &num_additional_swms);
1064                 if (ret != 0)
1065                         goto out;
1066         }
1067
1068         struct stat stbuf;
1069
1070         ret = tstat(target, &stbuf);
1071         if (ret == 0) {
1072                 if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1073                         extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1074         } else {
1075                 if (errno != ENOENT) {
1076                         imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1077                                                 target);
1078                         ret = -1;
1079                         goto out;
1080                 }
1081         }
1082
1083 #ifdef __WIN32__
1084         win32_acquire_restore_privileges();
1085 #endif
1086         ret = wimlib_extract_image(w, image, target, extract_flags,
1087                                    additional_swms, num_additional_swms,
1088                                    imagex_progress_func);
1089         if (ret == 0)
1090                 tprintf(T("Done applying WIM image.\n"));
1091 #ifdef __WIN32__
1092         win32_release_restore_privileges();
1093 #endif
1094 out:
1095         wimlib_free(w);
1096         if (additional_swms) {
1097                 for (unsigned i = 0; i < num_additional_swms; i++)
1098                         wimlib_free(additional_swms[i]);
1099                 free(additional_swms);
1100         }
1101         return ret;
1102 }
1103
1104 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1105  * directory trees.  'wimlib-imagex capture': create a new WIM file containing
1106  * the desired image.  'wimlib-imagex append': add a new image to an existing
1107  * WIM file. */
1108 static int
1109 imagex_capture_or_append(int argc, tchar **argv)
1110 {
1111         int c;
1112         int open_flags = 0;
1113         int add_image_flags = 0;
1114         int write_flags = 0;
1115         int compression_type = WIMLIB_COMPRESSION_TYPE_XPRESS;
1116         const tchar *wimfile;
1117         const tchar *name;
1118         const tchar *desc;
1119         const tchar *flags_element = NULL;
1120         WIMStruct *w = NULL;
1121         int ret;
1122         int cur_image;
1123         int cmd = tstrcmp(argv[0], T("append")) ? CAPTURE : APPEND;
1124         unsigned num_threads = 0;
1125
1126         tchar *source;
1127         size_t source_name_len;
1128         tchar *source_copy;
1129
1130         const tchar *config_file = NULL;
1131         tchar *config_str = NULL;
1132         size_t config_len;
1133
1134         bool source_list = false;
1135         size_t source_list_nchars;
1136         tchar *source_list_contents = NULL;
1137         bool capture_sources_malloced = false;
1138         struct wimlib_capture_source *capture_sources;
1139         size_t num_sources;
1140
1141         for_opt(c, capture_or_append_options) {
1142                 switch (c) {
1143                 case IMAGEX_BOOT_OPTION:
1144                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1145                         break;
1146                 case IMAGEX_CHECK_OPTION:
1147                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1148                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1149                         break;
1150                 case IMAGEX_CONFIG_OPTION:
1151                         config_file = optarg;
1152                         break;
1153                 case IMAGEX_COMPRESS_OPTION:
1154                         compression_type = get_compression_type(optarg);
1155                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1156                                 return -1;
1157                         break;
1158                 case IMAGEX_FLAGS_OPTION:
1159                         flags_element = optarg;
1160                         break;
1161                 case IMAGEX_DEREFERENCE_OPTION:
1162                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1163                         break;
1164                 case IMAGEX_VERBOSE_OPTION:
1165                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1166                         break;
1167                 case IMAGEX_THREADS_OPTION:
1168                         num_threads = parse_num_threads(optarg);
1169                         if (num_threads == UINT_MAX)
1170                                 return -1;
1171                         break;
1172                 case IMAGEX_REBULID_OPTION:
1173                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1174                         break;
1175                 case IMAGEX_UNIX_DATA_OPTION:
1176                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1177                         break;
1178                 case IMAGEX_SOURCE_LIST_OPTION:
1179                         source_list = true;
1180                         break;
1181                 case IMAGEX_NO_ACLS_OPTION:
1182                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1183                         break;
1184                 case IMAGEX_STRICT_ACLS_OPTION:
1185                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1186                         break;
1187                 default:
1188                         usage(cmd);
1189                         return -1;
1190                 }
1191         }
1192         argc -= optind;
1193         argv += optind;
1194
1195         if (argc < 2 || argc > 4) {
1196                 usage(cmd);
1197                 return -1;
1198         }
1199
1200         source = argv[0];
1201         wimfile = argv[1];
1202
1203         if (argc >= 3) {
1204                 name = argv[2];
1205         } else {
1206                 /* Set default name to SOURCE argument, omitting any directory
1207                  * prefixes and trailing slashes.  This requires making a copy
1208                  * of @source. */
1209                 source_name_len = tstrlen(source);
1210                 source_copy = alloca((source_name_len + 1) * sizeof(tchar));
1211                 name = tbasename(tstrcpy(source_copy, source));
1212         }
1213         /* Image description defaults to NULL if not given. */
1214         desc = (argc >= 4) ? argv[3] : NULL;
1215
1216         if (source_list) {
1217                 /* Set up capture sources in source list mode */
1218                 if (source[0] == T('-') && source[1] == T('\0')) {
1219                         source_list_contents = stdin_get_text_contents(&source_list_nchars);
1220                 } else {
1221                         source_list_contents = file_get_text_contents(source,
1222                                                                       &source_list_nchars);
1223                 }
1224                 if (!source_list_contents)
1225                         return -1;
1226
1227                 capture_sources = parse_source_list(&source_list_contents,
1228                                                     source_list_nchars,
1229                                                     &num_sources);
1230                 if (!capture_sources) {
1231                         ret = -1;
1232                         goto out;
1233                 }
1234                 capture_sources_malloced = true;
1235         } else {
1236                 /* Set up capture source in non-source-list mode (could be
1237                  * either "normal" mode or "NTFS mode"--- see the man page). */
1238                 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1239                 capture_sources[0].fs_source_path = source;
1240                 capture_sources[0].wim_target_path = NULL;
1241                 capture_sources[0].reserved = 0;
1242                 num_sources = 1;
1243         }
1244
1245         if (config_file) {
1246                 config_str = file_get_text_contents(config_file, &config_len);
1247                 if (!config_str) {
1248                         ret = -1;
1249                         goto out;
1250                 }
1251         }
1252
1253         if (cmd == APPEND)
1254                 ret = wimlib_open_wim(wimfile, open_flags, &w,
1255                                       imagex_progress_func);
1256         else
1257                 ret = wimlib_create_new_wim(compression_type, &w);
1258         if (ret != 0)
1259                 goto out;
1260
1261         if (!source_list) {
1262                 struct stat stbuf;
1263                 ret = tstat(source, &stbuf);
1264                 if (ret == 0) {
1265                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1266                                 tprintf(T("Capturing WIM image from NTFS "
1267                                           "filesystem on \"%"TS"\"\n"), source);
1268                                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1269                         }
1270                 } else {
1271                         if (errno != ENOENT) {
1272                                 imagex_error_with_errno(T("Failed to stat "
1273                                                           "\"%"TS"\""), source);
1274                                 ret = -1;
1275                                 goto out;
1276                         }
1277                 }
1278         }
1279 #ifdef __WIN32__
1280         win32_acquire_capture_privileges();
1281 #endif
1282
1283         ret = wimlib_add_image_multisource(w, capture_sources,
1284                                            num_sources, name,
1285                                            (config_str ? config_str :
1286                                                 default_capture_config),
1287                                            (config_str ? config_len :
1288                                                 tstrlen(default_capture_config)),
1289                                            add_image_flags,
1290                                            imagex_progress_func);
1291         if (ret != 0)
1292                 goto out_release_privs;
1293         cur_image = wimlib_get_num_images(w);
1294         if (desc) {
1295                 ret = wimlib_set_image_descripton(w, cur_image, desc);
1296                 if (ret != 0)
1297                         goto out_release_privs;
1298         }
1299         if (flags_element) {
1300                 ret = wimlib_set_image_flags(w, cur_image, flags_element);
1301                 if (ret != 0)
1302                         goto out_release_privs;
1303         }
1304         if (cmd == APPEND) {
1305                 ret = wimlib_overwrite(w, write_flags, num_threads,
1306                                        imagex_progress_func);
1307         } else {
1308                 ret = wimlib_write(w, wimfile, WIMLIB_ALL_IMAGES, write_flags,
1309                                    num_threads, imagex_progress_func);
1310         }
1311         if (ret == WIMLIB_ERR_REOPEN)
1312                 ret = 0;
1313         if (ret != 0)
1314                 imagex_error(T("Failed to write the WIM file \"%"TS"\""),
1315                              wimfile);
1316 out_release_privs:
1317 #ifdef __WIN32__
1318         win32_release_capture_privileges();
1319 #endif
1320 out:
1321         wimlib_free(w);
1322         free(config_str);
1323         free(source_list_contents);
1324         if (capture_sources_malloced)
1325                 free(capture_sources);
1326         return ret;
1327 }
1328
1329 /* Remove image(s) from a WIM. */
1330 static int
1331 imagex_delete(int argc, tchar **argv)
1332 {
1333         int c;
1334         int open_flags = 0;
1335         int write_flags = 0;
1336         const tchar *wimfile;
1337         const tchar *image_num_or_name;
1338         WIMStruct *w;
1339         int image;
1340         int ret;
1341
1342         for_opt(c, delete_options) {
1343                 switch (c) {
1344                 case IMAGEX_CHECK_OPTION:
1345                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1346                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1347                         break;
1348                 case IMAGEX_SOFT_OPTION:
1349                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1350                         break;
1351                 default:
1352                         usage(DELETE);
1353                         return -1;
1354                 }
1355         }
1356         argc -= optind;
1357         argv += optind;
1358
1359         if (argc != 2) {
1360                 if (argc < 1)
1361                         imagex_error(T("Must specify a WIM file"));
1362                 if (argc < 2)
1363                         imagex_error(T("Must specify an image"));
1364                 usage(DELETE);
1365                 return -1;
1366         }
1367         wimfile = argv[0];
1368         image_num_or_name = argv[1];
1369
1370         ret = file_writable(wimfile);
1371         if (ret != 0)
1372                 return ret;
1373
1374         ret = wimlib_open_wim(wimfile, open_flags, &w,
1375                               imagex_progress_func);
1376         if (ret != 0)
1377                 return ret;
1378
1379         image = wimlib_resolve_image(w, image_num_or_name);
1380
1381         ret = verify_image_exists(image, image_num_or_name, wimfile);
1382         if (ret != 0)
1383                 goto out;
1384
1385         ret = wimlib_delete_image(w, image);
1386         if (ret != 0) {
1387                 imagex_error(T("Failed to delete image from \"%"TS"\""), wimfile);
1388                 goto out;
1389         }
1390
1391         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
1392         if (ret == WIMLIB_ERR_REOPEN)
1393                 ret = 0;
1394         if (ret != 0) {
1395                 imagex_error(T("Failed to write the file \"%"TS"\" with image "
1396                                "deleted"), wimfile);
1397         }
1398 out:
1399         wimlib_free(w);
1400         return ret;
1401 }
1402
1403 /* Print the files contained in an image(s) in a WIM file. */
1404 static int
1405 imagex_dir(int argc, tchar **argv)
1406 {
1407         const tchar *wimfile;
1408         WIMStruct *w;
1409         int image;
1410         int ret;
1411         int num_images;
1412
1413         if (argc < 2) {
1414                 imagex_error(T("Must specify a WIM file"));
1415                 usage(DIR);
1416                 return -1;
1417         }
1418         if (argc > 3) {
1419                 imagex_error(T("Too many arguments"));
1420                 usage(DIR);
1421                 return -1;
1422         }
1423
1424         wimfile = argv[1];
1425         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &w,
1426                               imagex_progress_func);
1427         if (ret != 0)
1428                 return ret;
1429
1430         if (argc == 3) {
1431                 image = wimlib_resolve_image(w, argv[2]);
1432                 ret = verify_image_exists(image, argv[2], wimfile);
1433                 if (ret != 0)
1434                         goto out;
1435         } else {
1436                 /* Image was not specified.  If the WIM only contains one image,
1437                  * choose that one; otherwise, print an error. */
1438                 num_images = wimlib_get_num_images(w);
1439                 if (num_images != 1) {
1440                         imagex_error(T("The file \"%"TS"\" contains %d images; Please "
1441                                        "select one."), wimfile, num_images);
1442                         usage(DIR);
1443                         ret = -1;
1444                         goto out;
1445                 }
1446                 image = 1;
1447         }
1448
1449         ret = wimlib_print_files(w, image);
1450 out:
1451         wimlib_free(w);
1452         return ret;
1453 }
1454
1455 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
1456  * WIM file. */
1457 static int
1458 imagex_export(int argc, tchar **argv)
1459 {
1460         int c;
1461         int open_flags = 0;
1462         int export_flags = 0;
1463         int write_flags = 0;
1464         int compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1465         bool compression_type_specified = false;
1466         const tchar *src_wimfile;
1467         const tchar *src_image_num_or_name;
1468         const tchar *dest_wimfile;
1469         const tchar *dest_name;
1470         const tchar *dest_desc;
1471         WIMStruct *src_w = NULL;
1472         WIMStruct *dest_w = NULL;
1473         int ret;
1474         int image;
1475         struct stat stbuf;
1476         bool wim_is_new;
1477         const tchar *swm_glob = NULL;
1478         WIMStruct **additional_swms = NULL;
1479         unsigned num_additional_swms = 0;
1480         unsigned num_threads = 0;
1481
1482         for_opt(c, export_options) {
1483                 switch (c) {
1484                 case IMAGEX_BOOT_OPTION:
1485                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
1486                         break;
1487                 case IMAGEX_CHECK_OPTION:
1488                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1489                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1490                         break;
1491                 case IMAGEX_COMPRESS_OPTION:
1492                         compression_type = get_compression_type(optarg);
1493                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1494                                 return -1;
1495                         compression_type_specified = true;
1496                         break;
1497                 case IMAGEX_REF_OPTION:
1498                         swm_glob = optarg;
1499                         break;
1500                 case IMAGEX_THREADS_OPTION:
1501                         num_threads = parse_num_threads(optarg);
1502                         if (num_threads == UINT_MAX)
1503                                 return -1;
1504                         break;
1505                 case IMAGEX_REBULID_OPTION:
1506                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1507                         break;
1508                 default:
1509                         usage(EXPORT);
1510                         return -1;
1511                 }
1512         }
1513         argc -= optind;
1514         argv += optind;
1515         if (argc < 3 || argc > 5) {
1516                 usage(EXPORT);
1517                 return -1;
1518         }
1519         src_wimfile           = argv[0];
1520         src_image_num_or_name = argv[1];
1521         dest_wimfile          = argv[2];
1522         dest_name             = (argc >= 4) ? argv[3] : NULL;
1523         dest_desc             = (argc >= 5) ? argv[4] : NULL;
1524         ret = wimlib_open_wim(src_wimfile,
1525                               open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_w,
1526                               imagex_progress_func);
1527         if (ret != 0)
1528                 return ret;
1529
1530         /* Determine if the destination is an existing file or not.
1531          * If so, we try to append the exported image(s) to it; otherwise, we
1532          * create a new WIM containing the exported image(s). */
1533         if (tstat(dest_wimfile, &stbuf) == 0) {
1534                 int dest_ctype;
1535
1536                 wim_is_new = false;
1537                 /* Destination file exists. */
1538
1539                 if (!S_ISREG(stbuf.st_mode)) {
1540                         imagex_error(T("\"%"TS"\" is not a regular file"),
1541                                      dest_wimfile);
1542                         ret = -1;
1543                         goto out;
1544                 }
1545                 ret = wimlib_open_wim(dest_wimfile, open_flags, &dest_w,
1546                                       imagex_progress_func);
1547                 if (ret != 0)
1548                         goto out;
1549
1550                 ret = file_writable(dest_wimfile);
1551                 if (ret != 0)
1552                         goto out;
1553
1554                 dest_ctype = wimlib_get_compression_type(dest_w);
1555                 if (compression_type_specified
1556                     && compression_type != dest_ctype)
1557                 {
1558                         imagex_error(T("Cannot specify a compression type that is "
1559                                        "not the same as that used in the "
1560                                        "destination WIM"));
1561                         ret = -1;
1562                         goto out;
1563                 }
1564         } else {
1565                 wim_is_new = true;
1566                 /* dest_wimfile is not an existing file, so create a new WIM. */
1567                 if (!compression_type_specified)
1568                         compression_type = wimlib_get_compression_type(src_w);
1569                 if (errno == ENOENT) {
1570                         ret = wimlib_create_new_wim(compression_type, &dest_w);
1571                         if (ret != 0)
1572                                 goto out;
1573                 } else {
1574                         imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
1575                                                 dest_wimfile);
1576                         ret = -1;
1577                         goto out;
1578                 }
1579         }
1580
1581         image = wimlib_resolve_image(src_w, src_image_num_or_name);
1582         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
1583         if (ret != 0)
1584                 goto out;
1585
1586         if (swm_glob) {
1587                 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
1588                                           &additional_swms,
1589                                           &num_additional_swms);
1590                 if (ret != 0)
1591                         goto out;
1592         }
1593
1594         ret = wimlib_export_image(src_w, image, dest_w, dest_name, dest_desc,
1595                                   export_flags, additional_swms,
1596                                   num_additional_swms, imagex_progress_func);
1597         if (ret != 0)
1598                 goto out;
1599
1600
1601         if (wim_is_new)
1602                 ret = wimlib_write(dest_w, dest_wimfile, WIMLIB_ALL_IMAGES,
1603                                    write_flags, num_threads,
1604                                    imagex_progress_func);
1605         else
1606                 ret = wimlib_overwrite(dest_w, write_flags, num_threads,
1607                                        imagex_progress_func);
1608 out:
1609         if (ret == WIMLIB_ERR_REOPEN)
1610                 ret = 0;
1611         wimlib_free(src_w);
1612         wimlib_free(dest_w);
1613         if (additional_swms) {
1614                 for (unsigned i = 0; i < num_additional_swms; i++)
1615                         wimlib_free(additional_swms[i]);
1616                 free(additional_swms);
1617         }
1618         return ret;
1619 }
1620
1621 /* Prints information about a WIM file; also can mark an image as bootable,
1622  * change the name of an image, or change the description of an image. */
1623 static int
1624 imagex_info(int argc, tchar **argv)
1625 {
1626         int c;
1627         bool boot         = false;
1628         bool check        = false;
1629         bool header       = false;
1630         bool lookup_table = false;
1631         bool xml          = false;
1632         bool metadata     = false;
1633         bool short_header = true;
1634         const tchar *xml_out_file = NULL;
1635         const tchar *wimfile;
1636         const tchar *image_num_or_name = T("all");
1637         const tchar *new_name = NULL;
1638         const tchar *new_desc = NULL;
1639         WIMStruct *w;
1640         FILE *fp;
1641         int image;
1642         int ret;
1643         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1644         int part_number;
1645         int total_parts;
1646         int num_images;
1647
1648         for_opt(c, info_options) {
1649                 switch (c) {
1650                 case IMAGEX_BOOT_OPTION:
1651                         boot = true;
1652                         break;
1653                 case IMAGEX_CHECK_OPTION:
1654                         check = true;
1655                         break;
1656                 case IMAGEX_HEADER_OPTION:
1657                         header = true;
1658                         short_header = false;
1659                         break;
1660                 case IMAGEX_LOOKUP_TABLE_OPTION:
1661                         lookup_table = true;
1662                         short_header = false;
1663                         break;
1664                 case IMAGEX_XML_OPTION:
1665                         xml = true;
1666                         short_header = false;
1667                         break;
1668                 case IMAGEX_EXTRACT_XML_OPTION:
1669                         xml_out_file = optarg;
1670                         short_header = false;
1671                         break;
1672                 case IMAGEX_METADATA_OPTION:
1673                         metadata = true;
1674                         short_header = false;
1675                         break;
1676                 default:
1677                         usage(INFO);
1678                         return -1;
1679                 }
1680         }
1681
1682         argc -= optind;
1683         argv += optind;
1684         if (argc == 0 || argc > 4) {
1685                 usage(INFO);
1686                 return -1;
1687         }
1688         wimfile = argv[0];
1689         if (argc > 1) {
1690                 image_num_or_name = argv[1];
1691                 if (argc > 2) {
1692                         new_name = argv[2];
1693                         if (argc > 3) {
1694                                 new_desc = argv[3];
1695                         }
1696                 }
1697         }
1698
1699         if (check)
1700                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1701
1702         ret = wimlib_open_wim(wimfile, open_flags, &w,
1703                               imagex_progress_func);
1704         if (ret != 0)
1705                 return ret;
1706
1707         part_number = wimlib_get_part_number(w, &total_parts);
1708
1709         image = wimlib_resolve_image(w, image_num_or_name);
1710         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
1711                 imagex_error(T("The image \"%"TS"\" does not exist"),
1712                              image_num_or_name);
1713                 if (boot) {
1714                         imagex_error(T("If you would like to set the boot "
1715                                        "index to 0, specify image \"0\" with "
1716                                        "the --boot flag."));
1717                 }
1718                 ret = WIMLIB_ERR_INVALID_IMAGE;
1719                 goto out;
1720         }
1721
1722         num_images = wimlib_get_num_images(w);
1723
1724         if (num_images == 0) {
1725                 if (boot) {
1726                         imagex_error(T("--boot is meaningless on a WIM with no "
1727                                        "images"));
1728                         ret = WIMLIB_ERR_INVALID_IMAGE;
1729                         goto out;
1730                 }
1731         }
1732
1733         if (image == WIMLIB_ALL_IMAGES && num_images > 1) {
1734                 if (boot) {
1735                         imagex_error(T("Cannot specify the --boot flag "
1736                                        "without specifying a specific "
1737                                        "image in a multi-image WIM"));
1738                         ret = WIMLIB_ERR_INVALID_IMAGE;
1739                         goto out;
1740                 }
1741                 if (new_name) {
1742                         imagex_error(T("Cannot specify the NEW_NAME "
1743                                        "without specifying a specific "
1744                                        "image in a multi-image WIM"));
1745                         ret = WIMLIB_ERR_INVALID_IMAGE;
1746                         goto out;
1747                 }
1748         }
1749
1750         /* Operations that print information are separated from operations that
1751          * recreate the WIM file. */
1752         if (!new_name && !boot) {
1753
1754                 /* Read-only operations */
1755
1756                 if (image == WIMLIB_NO_IMAGE) {
1757                         imagex_error(T("\"%"TS"\" is not a valid image"),
1758                                      image_num_or_name);
1759                         ret = WIMLIB_ERR_INVALID_IMAGE;
1760                         goto out;
1761                 }
1762
1763                 if (image == WIMLIB_ALL_IMAGES && short_header)
1764                         wimlib_print_wim_information(w);
1765
1766                 if (header)
1767                         wimlib_print_header(w);
1768
1769                 if (lookup_table) {
1770                         if (total_parts != 1) {
1771                                 tprintf(T("Warning: Only showing the lookup table "
1772                                           "for part %d of a %d-part WIM.\n"),
1773                                         part_number, total_parts);
1774                         }
1775                         wimlib_print_lookup_table(w);
1776                 }
1777
1778                 if (xml) {
1779                         ret = wimlib_extract_xml_data(w, stdout);
1780                         if (ret != 0)
1781                                 goto out;
1782                 }
1783
1784                 if (xml_out_file) {
1785                         fp = tfopen(xml_out_file, T("wb"));
1786                         if (!fp) {
1787                                 imagex_error_with_errno(T("Failed to open the "
1788                                                           "file \"%"TS"\" for "
1789                                                           "writing "),
1790                                                         xml_out_file);
1791                                 ret = -1;
1792                                 goto out;
1793                         }
1794                         ret = wimlib_extract_xml_data(w, fp);
1795                         if (fclose(fp) != 0) {
1796                                 imagex_error(T("Failed to close the file "
1797                                                "\"%"TS"\""),
1798                                              xml_out_file);
1799                                 ret = -1;
1800                         }
1801
1802                         if (ret != 0)
1803                                 goto out;
1804                 }
1805
1806                 if (short_header)
1807                         wimlib_print_available_images(w, image);
1808
1809                 if (metadata) {
1810                         ret = wimlib_print_metadata(w, image);
1811                         if (ret != 0)
1812                                 goto out;
1813                 }
1814         } else {
1815
1816                 /* Modification operations */
1817                 if (total_parts != 1) {
1818                         imagex_error(T("Modifying a split WIM is not supported."));
1819                         ret = -1;
1820                         goto out;
1821                 }
1822                 if (image == WIMLIB_ALL_IMAGES)
1823                         image = 1;
1824
1825                 if (image == WIMLIB_NO_IMAGE && new_name) {
1826                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
1827                                        "when using image 0"), new_name);
1828                         ret = -1;
1829                         goto out;
1830                 }
1831
1832                 if (boot) {
1833                         if (image == wimlib_get_boot_idx(w)) {
1834                                 tprintf(T("Image %d is already marked as "
1835                                           "bootable.\n"), image);
1836                                 boot = false;
1837                         } else {
1838                                 tprintf(T("Marking image %d as bootable.\n"),
1839                                         image);
1840                                 wimlib_set_boot_idx(w, image);
1841                         }
1842                 }
1843                 if (new_name) {
1844                         if (!tstrcmp(wimlib_get_image_name(w, image), new_name))
1845                         {
1846                                 tprintf(T("Image %d is already named \"%"TS"\".\n"),
1847                                         image, new_name);
1848                                 new_name = NULL;
1849                         } else {
1850                                 tprintf(T("Changing the name of image %d to "
1851                                           "\"%"TS"\".\n"), image, new_name);
1852                                 ret = wimlib_set_image_name(w, image, new_name);
1853                                 if (ret != 0)
1854                                         goto out;
1855                         }
1856                 }
1857                 if (new_desc) {
1858                         const tchar *old_desc;
1859                         old_desc = wimlib_get_image_description(w, image);
1860                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
1861                                 tprintf(T("The description of image %d is already "
1862                                           "\"%"TS"\".\n"), image, new_desc);
1863                                 new_desc = NULL;
1864                         } else {
1865                                 tprintf(T("Changing the description of image %d "
1866                                           "to \"%"TS"\".\n"), image, new_desc);
1867                                 ret = wimlib_set_image_descripton(w, image,
1868                                                                   new_desc);
1869                                 if (ret != 0)
1870                                         goto out;
1871                         }
1872                 }
1873
1874                 /* Only call wimlib_overwrite() if something actually needs to
1875                  * be changed. */
1876                 if (boot || new_name || new_desc ||
1877                     (check && !wimlib_has_integrity_table(w)))
1878                 {
1879                         int write_flags;
1880
1881                         ret = file_writable(wimfile);
1882                         if (ret != 0)
1883                                 return ret;
1884
1885                         if (check)
1886                                 write_flags = WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1887                         else
1888                                 write_flags = 0;
1889
1890                         ret = wimlib_overwrite(w, write_flags, 1,
1891                                                imagex_progress_func);
1892                         if (ret == WIMLIB_ERR_REOPEN)
1893                                 ret = 0;
1894                 } else {
1895                         tprintf(T("The file \"%"TS"\" was not modified because nothing "
1896                                   "needed to be done.\n"), wimfile);
1897                         ret = 0;
1898                 }
1899         }
1900 out:
1901         wimlib_free(w);
1902         return ret;
1903 }
1904
1905 /* Join split WIMs into one part WIM */
1906 static int
1907 imagex_join(int argc, tchar **argv)
1908 {
1909         int c;
1910         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1911         int wim_write_flags = 0;
1912         const tchar *output_path;
1913
1914         for_opt(c, join_options) {
1915                 switch (c) {
1916                 case IMAGEX_CHECK_OPTION:
1917                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1918                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1919                         break;
1920                 default:
1921                         goto err;
1922                 }
1923         }
1924         argc -= optind;
1925         argv += optind;
1926
1927         if (argc < 2) {
1928                 imagex_error(T("Must specify one or more split WIM (.swm) "
1929                                "parts to join"));
1930                 goto err;
1931         }
1932         output_path = argv[0];
1933         return wimlib_join((const tchar * const *)++argv,
1934                            --argc,
1935                            output_path,
1936                            swm_open_flags,
1937                            wim_write_flags,
1938                            imagex_progress_func);
1939 err:
1940         usage(JOIN);
1941         return -1;
1942 }
1943
1944 /* Mounts an image using a FUSE mount. */
1945 static int
1946 imagex_mount_rw_or_ro(int argc, tchar **argv)
1947 {
1948         int c;
1949         int mount_flags = 0;
1950         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1951         const tchar *wimfile;
1952         const tchar *dir;
1953         WIMStruct *w;
1954         int image;
1955         int num_images;
1956         int ret;
1957         const tchar *swm_glob = NULL;
1958         WIMStruct **additional_swms = NULL;
1959         unsigned num_additional_swms = 0;
1960         const tchar *staging_dir = NULL;
1961
1962         if (!tstrcmp(argv[0], T("mountrw")))
1963                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
1964
1965         for_opt(c, mount_options) {
1966                 switch (c) {
1967                 case IMAGEX_ALLOW_OTHER_OPTION:
1968                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
1969                         break;
1970                 case IMAGEX_CHECK_OPTION:
1971                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1972                         break;
1973                 case IMAGEX_DEBUG_OPTION:
1974                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
1975                         break;
1976                 case IMAGEX_STREAMS_INTERFACE_OPTION:
1977                         if (!tstrcasecmp(optarg, T("none")))
1978                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
1979                         else if (!tstrcasecmp(optarg, T("xattr")))
1980                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
1981                         else if (!tstrcasecmp(optarg, T("windows")))
1982                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
1983                         else {
1984                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
1985                                              optarg);
1986                                 goto mount_usage;
1987                         }
1988                         break;
1989                 case IMAGEX_REF_OPTION:
1990                         swm_glob = optarg;
1991                         break;
1992                 case IMAGEX_STAGING_DIR_OPTION:
1993                         staging_dir = optarg;
1994                         break;
1995                 case IMAGEX_UNIX_DATA_OPTION:
1996                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
1997                         break;
1998                 default:
1999                         goto mount_usage;
2000                 }
2001         }
2002         argc -= optind;
2003         argv += optind;
2004         if (argc != 2 && argc != 3)
2005                 goto mount_usage;
2006
2007         wimfile = argv[0];
2008
2009         ret = wimlib_open_wim(wimfile, open_flags, &w,
2010                               imagex_progress_func);
2011         if (ret != 0)
2012                 return ret;
2013
2014         if (swm_glob) {
2015                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2016                                           &additional_swms,
2017                                           &num_additional_swms);
2018                 if (ret != 0)
2019                         goto out;
2020         }
2021
2022         if (argc == 2) {
2023                 image = 1;
2024                 num_images = wimlib_get_num_images(w);
2025                 if (num_images != 1) {
2026                         imagex_error(T("The file \"%"TS"\" contains %d images; Please "
2027                                        "select one."), wimfile, num_images);
2028                         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2029                                         ? MOUNTRW : MOUNT);
2030                         ret = -1;
2031                         goto out;
2032                 }
2033                 dir = argv[1];
2034         } else {
2035                 image = wimlib_resolve_image(w, argv[1]);
2036                 dir = argv[2];
2037                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2038                 if (ret != 0)
2039                         goto out;
2040         }
2041
2042         if (mount_flags & WIMLIB_MOUNT_FLAG_READWRITE) {
2043                 ret = file_writable(wimfile);
2044                 if (ret != 0)
2045                         goto out;
2046         }
2047
2048         ret = wimlib_mount_image(w, image, dir, mount_flags, additional_swms,
2049                                  num_additional_swms, staging_dir);
2050         if (ret != 0) {
2051                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
2052                                "on \"%"TS"\""),
2053                              image, wimfile, dir);
2054
2055         }
2056 out:
2057         wimlib_free(w);
2058         if (additional_swms) {
2059                 for (unsigned i = 0; i < num_additional_swms; i++)
2060                         wimlib_free(additional_swms[i]);
2061                 free(additional_swms);
2062         }
2063         return ret;
2064 mount_usage:
2065         usage((mount_flags & WIMLIB_MOUNT_FLAG_READWRITE)
2066                         ? MOUNTRW : MOUNT);
2067         return -1;
2068 }
2069
2070 /* Rebuild a WIM file */
2071 static int
2072 imagex_optimize(int argc, tchar **argv)
2073 {
2074         int c;
2075         int open_flags = 0;
2076         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
2077         int ret;
2078         WIMStruct *w;
2079         const tchar *wimfile;
2080         off_t old_size;
2081         off_t new_size;
2082
2083         for_opt(c, optimize_options) {
2084                 switch (c) {
2085                 case IMAGEX_CHECK_OPTION:
2086                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2087                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2088                         break;
2089                 case IMAGEX_RECOMPRESS_OPTION:
2090                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
2091                         break;
2092                 default:
2093                         usage(OPTIMIZE);
2094                         return -1;
2095                 }
2096         }
2097         argc -= optind;
2098         argv += optind;
2099
2100         if (argc != 1) {
2101                 usage(OPTIMIZE);
2102                 return -1;
2103         }
2104
2105         wimfile = argv[0];
2106
2107         ret = wimlib_open_wim(wimfile, open_flags, &w,
2108                               imagex_progress_func);
2109         if (ret != 0)
2110                 return ret;
2111
2112         old_size = file_get_size(argv[0]);
2113         tprintf(T("\"%"TS"\" original size: "), wimfile);
2114         if (old_size == -1)
2115                 tfputs(T("Unknown\n"), stdout);
2116         else
2117                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
2118
2119         ret = wimlib_overwrite(w, write_flags, 0, imagex_progress_func);
2120
2121         if (ret == 0) {
2122                 new_size = file_get_size(argv[0]);
2123                 tprintf(T("\"%"TS"\" optimized size: "), wimfile);
2124                 if (new_size == -1)
2125                         tfputs(T("Unknown\n"), stdout);
2126                 else
2127                         tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
2128
2129                 tfputs(T("Space saved: "), stdout);
2130                 if (new_size != -1 && old_size != -1) {
2131                         tprintf(T("%lld KiB\n"),
2132                                ((long long)old_size - (long long)new_size) >> 10);
2133                 } else {
2134                         tfputs(T("Unknown\n"), stdout);
2135                 }
2136         }
2137
2138         wimlib_free(w);
2139         return ret;
2140 }
2141
2142 /* Split a WIM into a spanned set */
2143 static int
2144 imagex_split(int argc, tchar **argv)
2145 {
2146         int c;
2147         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2148         int write_flags = 0;
2149         unsigned long part_size;
2150         tchar *tmp;
2151         int ret;
2152         WIMStruct *w;
2153
2154         for_opt(c, split_options) {
2155                 switch (c) {
2156                 case IMAGEX_CHECK_OPTION:
2157                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2158                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2159                         break;
2160                 default:
2161                         usage(SPLIT);
2162                         return -1;
2163                 }
2164         }
2165         argc -= optind;
2166         argv += optind;
2167
2168         if (argc != 3) {
2169                 usage(SPLIT);
2170                 return -1;
2171         }
2172         part_size = tstrtod(argv[2], &tmp) * (1 << 20);
2173         if (tmp == argv[2] || *tmp) {
2174                 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
2175                 imagex_error(T("The part size must be an integer or "
2176                                "floating-point number of megabytes."));
2177                 return -1;
2178         }
2179         ret = wimlib_open_wim(argv[0], open_flags, &w, imagex_progress_func);
2180         if (ret != 0)
2181                 return ret;
2182         ret = wimlib_split(w, argv[1], part_size, write_flags, imagex_progress_func);
2183         wimlib_free(w);
2184         return ret;
2185 }
2186
2187 /* Unmounts a mounted WIM image. */
2188 static int
2189 imagex_unmount(int argc, tchar **argv)
2190 {
2191         int c;
2192         int unmount_flags = 0;
2193         int ret;
2194
2195         for_opt(c, unmount_options) {
2196                 switch (c) {
2197                 case IMAGEX_COMMIT_OPTION:
2198                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
2199                         break;
2200                 case IMAGEX_CHECK_OPTION:
2201                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
2202                         break;
2203                 case IMAGEX_REBULID_OPTION:
2204                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
2205                         break;
2206                 default:
2207                         usage(UNMOUNT);
2208                         return -1;
2209                 }
2210         }
2211         argc -= optind;
2212         argv += optind;
2213         if (argc != 1) {
2214                 usage(UNMOUNT);
2215                 return -1;
2216         }
2217
2218         ret = wimlib_unmount_image(argv[0], unmount_flags,
2219                                    imagex_progress_func);
2220         if (ret != 0)
2221                 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
2222         return ret;
2223 }
2224
2225 struct imagex_command {
2226         const tchar *name;
2227         int (*func)(int , tchar **);
2228         int cmd;
2229 };
2230
2231
2232 #define for_imagex_command(p) for (p = &imagex_commands[0]; \
2233                 p != &imagex_commands[ARRAY_LEN(imagex_commands)]; p++)
2234
2235 static const struct imagex_command imagex_commands[] = {
2236         {T("append"),  imagex_capture_or_append, APPEND},
2237         {T("apply"),   imagex_apply,             APPLY},
2238         {T("capture"), imagex_capture_or_append, CAPTURE},
2239         {T("delete"),  imagex_delete,            DELETE},
2240         {T("dir"),     imagex_dir,               DIR},
2241         {T("export"),  imagex_export,            EXPORT},
2242         {T("info"),    imagex_info,              INFO},
2243         {T("join"),    imagex_join,              JOIN},
2244         {T("mount"),   imagex_mount_rw_or_ro,    MOUNT},
2245         {T("mountrw"), imagex_mount_rw_or_ro,    MOUNTRW},
2246         {T("optimize"),imagex_optimize,          OPTIMIZE},
2247         {T("split"),   imagex_split,             SPLIT},
2248         {T("unmount"), imagex_unmount,           UNMOUNT},
2249 };
2250
2251 static void
2252 version()
2253 {
2254         static const tchar *s =
2255         T(
2256 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
2257 "Copyright (C) 2012, 2013 Eric Biggers\n"
2258 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
2259 "This is free software: you are free to change and redistribute it.\n"
2260 "There is NO WARRANTY, to the extent permitted by law.\n"
2261 "\n"
2262 "Report bugs to "PACKAGE_BUGREPORT".\n"
2263         );
2264         tfputs(s, stdout);
2265 }
2266
2267
2268 static void
2269 help_or_version(int argc, tchar **argv)
2270 {
2271         int i;
2272         const tchar *p;
2273         const struct imagex_command *cmd;
2274
2275         for (i = 1; i < argc; i++) {
2276                 p = argv[i];
2277                 if (*p == T('-'))
2278                         p++;
2279                 else
2280                         continue;
2281                 if (*p == T('-'))
2282                         p++;
2283                 if (!tstrcmp(p, T("help"))) {
2284                         for_imagex_command(cmd) {
2285                                 if (!tstrcmp(cmd->name, argv[1])) {
2286                                         usage(cmd->cmd);
2287                                         exit(0);
2288                                 }
2289                         }
2290                         usage_all();
2291                         exit(0);
2292                 }
2293                 if (!tstrcmp(p, T("version"))) {
2294                         version();
2295                         exit(0);
2296                 }
2297         }
2298 }
2299
2300
2301 static void
2302 usage(int cmd_type)
2303 {
2304         const struct imagex_command *cmd;
2305         tprintf(T("Usage:\n%"TS), usage_strings[cmd_type]);
2306         for_imagex_command(cmd) {
2307                 if (cmd->cmd == cmd_type) {
2308                         tprintf(T("\nTry `man "IMAGEX_PROGNAME"-%"TS"' "
2309                                   "for more details.\n"), cmd->name);
2310                 }
2311         }
2312 }
2313
2314 static void
2315 usage_all()
2316 {
2317         tfputs(T("Usage:\n"), stdout);
2318         for (int i = 0; i < ARRAY_LEN(usage_strings); i++)
2319                 tprintf(T("    %"TS), usage_strings[i]);
2320         static const tchar *extra =
2321         T(
2322 "    "IMAGEX_PROGNAME" --help\n"
2323 "    "IMAGEX_PROGNAME" --version\n"
2324 "\n"
2325 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
2326 "\n"
2327 "    Try `man "IMAGEX_PROGNAME"' for more information.\n"
2328         );
2329         tfputs(extra, stdout);
2330 }
2331
2332 /* Entry point for wimlib's ImageX implementation.  On UNIX the command
2333  * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
2334  * something else), while an Windows the command arguments will be UTF-16LE
2335  * encoded 'wchar_t' strings. */
2336 int
2337 #ifdef __WIN32__
2338 wmain(int argc, wchar_t **argv, wchar_t **envp)
2339 #else
2340 main(int argc, char **argv)
2341 #endif
2342 {
2343         const struct imagex_command *cmd;
2344         int ret;
2345
2346 #ifndef __WIN32__
2347         setlocale(LC_ALL, "");
2348         {
2349                 char *codeset = nl_langinfo(CODESET);
2350                 if (!strstr(codeset, "UTF-8") &&
2351                     !strstr(codeset, "UTF8") &&
2352                     !strstr(codeset, "utf-8") &&
2353                     !strstr(codeset, "utf8"))
2354                 {
2355                         fputs(
2356 "WARNING: Running "IMAGEX_PROGNAME" in a UTF-8 locale is recommended!\n"
2357 "         (Maybe try: `export LANG=en_US.UTF-8'?\n", stderr);
2358
2359                 }
2360         }
2361 #endif /* !__WIN32__ */
2362
2363         if (argc < 2) {
2364                 imagex_error(T("No command specified"));
2365                 usage_all();
2366                 ret = 2;
2367                 goto out;
2368         }
2369
2370         /* Handle --help and --version for all commands.  Note that this will
2371          * not return if either of these arguments are present. */
2372         help_or_version(argc, argv);
2373         argc--;
2374         argv++;
2375
2376         /* The user may like to see more informative error messages. */
2377         wimlib_set_print_errors(true);
2378
2379         /* Do any initializations that the library needs */
2380         ret = wimlib_global_init();
2381         if (ret)
2382                 goto out_check_status;
2383
2384         /* Search for the function to handle the ImageX subcommand. */
2385         for_imagex_command(cmd) {
2386                 if (!tstrcmp(cmd->name, *argv)) {
2387                         ret = cmd->func(argc, argv);
2388                         goto out_check_write_error;
2389                 }
2390         }
2391
2392         imagex_error(T("Unrecognized command: `%"TS"'"), argv[0]);
2393         usage_all();
2394         ret = 2;
2395         goto out_cleanup;
2396 out_check_write_error:
2397         /* For 'wimlib-imagex info' and 'wimlib-imagex dir', data printed to
2398          * standard output is part of the program's actual behavior and not just
2399          * for informational purposes, so we should set a failure exit status if
2400          * there was a write error. */
2401         if (cmd == &imagex_commands[INFO] || cmd == &imagex_commands[DIR]) {
2402                 if (ferror(stdout) || fclose(stdout)) {
2403                         imagex_error_with_errno(T("error writing to standard output"));
2404                         if (ret == 0)
2405                                 ret = -1;
2406                 }
2407         }
2408 out_check_status:
2409         /* Exit status (ret):  -1 indicates an error found by 'wimlib-imagex'
2410          * outside of the wimlib library code.  0 indicates success.  > 0
2411          * indicates a wimlib error code from which an error message can be
2412          * printed. */
2413         if (ret > 0) {
2414                 imagex_error(T("Exiting with error code %d:\n"
2415                                "       %"TS"."), ret,
2416                              wimlib_get_error_string(ret));
2417                 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
2418                         imagex_error_with_errno(T("errno"));
2419         }
2420 out_cleanup:
2421         /* Make the library free any resources it's holding (not strictly
2422          * necessary because the process is ending anyway). */
2423         wimlib_global_cleanup();
2424 out:
2425         return ret;
2426 }