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