]> wimlib.net Git - wimlib/blob - programs/imagex.c
f7a3620bd049fe43d31ad20af2bb3b322b7aa29e
[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 #ifdef HAVE_CONFIG_H
26 #  include "config.h" /* Need for PACKAGE_VERSION, etc. */
27 #endif
28
29 #include "wimlib.h"
30 #include "wimlib_tchar.h"
31
32 #include <ctype.h>
33 #include <errno.h>
34
35 #include <inttypes.h>
36 #include <libgen.h>
37 #include <limits.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/stat.h>
42 #include <unistd.h>
43 #include <locale.h>
44
45 #ifdef HAVE_ALLOCA_H
46 #  include <alloca.h>
47 #endif
48
49 #ifdef __WIN32__
50 #  include "imagex-win32.h"
51 #  define tbasename     win32_wbasename
52 #  define tglob         win32_wglob
53 #  define OS_PREFERRED_PATH_SEPARATOR L'\\'
54 #  define OS_PREFERRED_PATH_SEPARATOR_STRING L"\\"
55 #else /* __WIN32__ */
56 #  include <glob.h>
57 #  include <getopt.h>
58 #  include <langinfo.h>
59 #  define tbasename     basename
60 #  define tglob         glob
61 #  define OS_PREFERRED_PATH_SEPARATOR '/'
62 #  define OS_PREFERRED_PATH_SEPARATOR_STRING "/"
63 static inline void set_fd_to_binary_mode(int fd)
64 {
65 }
66 #endif /* !__WIN32 */
67
68 /* Don't confuse the user by presenting the mounting commands on Windows when
69  * they will never work.  However on UNIX-like systems we always present them,
70  * even if WITH_FUSE is not defined at this point, as to not tie the build of
71  * wimlib-imagex to a specific build of wimlib.  */
72 #ifdef __WIN32__
73 #  define WIM_MOUNTING_SUPPORTED 0
74 #else
75 #  define WIM_MOUNTING_SUPPORTED 1
76 #endif
77
78 #define ARRAY_LEN(array) (sizeof(array) / sizeof(array[0]))
79
80 #define for_opt(c, opts) while ((c = getopt_long_only(argc, (tchar**)argv, T(""), \
81                                 opts, NULL)) != -1)
82
83
84 enum {
85         CMD_NONE = -1,
86         CMD_APPEND = 0,
87         CMD_APPLY,
88         CMD_CAPTURE,
89         CMD_DELETE,
90         CMD_DIR,
91         CMD_EXPORT,
92         CMD_EXTRACT,
93         CMD_INFO,
94         CMD_JOIN,
95 #if WIM_MOUNTING_SUPPORTED
96         CMD_MOUNT,
97         CMD_MOUNTRW,
98 #endif
99         CMD_OPTIMIZE,
100         CMD_SPLIT,
101 #if WIM_MOUNTING_SUPPORTED
102         CMD_UNMOUNT,
103 #endif
104         CMD_UPDATE,
105         CMD_MAX,
106 };
107
108 static void usage(int cmd, FILE *fp);
109 static void usage_all(FILE *fp);
110 static void recommend_man_page(int cmd, FILE *fp);
111 static const tchar *get_cmd_string(int cmd, bool nospace);
112
113 static bool imagex_be_quiet = false;
114 static FILE *imagex_info_file;
115
116 #define imagex_printf(format, ...) \
117                 tfprintf(imagex_info_file, format, ##__VA_ARGS__)
118
119 enum {
120         IMAGEX_ALLOW_OTHER_OPTION,
121         IMAGEX_BOOT_OPTION,
122         IMAGEX_CHECK_OPTION,
123         IMAGEX_COMMAND_OPTION,
124         IMAGEX_COMMIT_OPTION,
125         IMAGEX_COMPRESS_OPTION,
126         IMAGEX_CONFIG_OPTION,
127         IMAGEX_DEBUG_OPTION,
128         IMAGEX_DELTA_FROM_OPTION,
129         IMAGEX_DEREFERENCE_OPTION,
130         IMAGEX_DEST_DIR_OPTION,
131         IMAGEX_EXTRACT_XML_OPTION,
132         IMAGEX_FLAGS_OPTION,
133         IMAGEX_FORCE_OPTION,
134         IMAGEX_HARDLINK_OPTION,
135         IMAGEX_HEADER_OPTION,
136         IMAGEX_INCLUDE_INVALID_NAMES_OPTION,
137         IMAGEX_LAZY_OPTION,
138         IMAGEX_LOOKUP_TABLE_OPTION,
139         IMAGEX_METADATA_OPTION,
140         IMAGEX_NORPFIX_OPTION,
141         IMAGEX_NOCHECK_OPTION,
142         IMAGEX_NO_ACLS_OPTION,
143         IMAGEX_NOT_PIPABLE_OPTION,
144         IMAGEX_PATH_OPTION,
145         IMAGEX_PIPABLE_OPTION,
146         IMAGEX_REBUILD_OPTION,
147         IMAGEX_RECOMPRESS_OPTION,
148         IMAGEX_RECURSIVE_OPTION,
149         IMAGEX_REF_OPTION,
150         IMAGEX_RESUME_OPTION,
151         IMAGEX_RPFIX_OPTION,
152         IMAGEX_SOFT_OPTION,
153         IMAGEX_SOURCE_LIST_OPTION,
154         IMAGEX_STAGING_DIR_OPTION,
155         IMAGEX_STREAMS_INTERFACE_OPTION,
156         IMAGEX_STRICT_ACLS_OPTION,
157         IMAGEX_SYMLINK_OPTION,
158         IMAGEX_THREADS_OPTION,
159         IMAGEX_TO_STDOUT_OPTION,
160         IMAGEX_UNIX_DATA_OPTION,
161         IMAGEX_VERBOSE_OPTION,
162         IMAGEX_XML_OPTION,
163 };
164
165 static const struct option apply_options[] = {
166         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
167         {T("hardlink"),    no_argument,       NULL, IMAGEX_HARDLINK_OPTION},
168         {T("symlink"),     no_argument,       NULL, IMAGEX_SYMLINK_OPTION},
169         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
170         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
171         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
172         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
173         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
174         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
175         {T("rpfix"),       no_argument,       NULL, IMAGEX_RPFIX_OPTION},
176         {T("norpfix"),     no_argument,       NULL, IMAGEX_NORPFIX_OPTION},
177         {T("include-invalid-names"), no_argument,       NULL, IMAGEX_INCLUDE_INVALID_NAMES_OPTION},
178
179         /* --resume is undocumented for now as it needs improvement.  */
180         {T("resume"),      no_argument,       NULL, IMAGEX_RESUME_OPTION},
181         {NULL, 0, NULL, 0},
182 };
183
184 static const struct option capture_or_append_options[] = {
185         {T("boot"),        no_argument,       NULL, IMAGEX_BOOT_OPTION},
186         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
187         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
188         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
189         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
190         {T("config"),      required_argument, NULL, IMAGEX_CONFIG_OPTION},
191         {T("dereference"), no_argument,       NULL, IMAGEX_DEREFERENCE_OPTION},
192         {T("flags"),       required_argument, NULL, IMAGEX_FLAGS_OPTION},
193         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
194         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
195         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
196         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
197         {T("source-list"), no_argument,       NULL, IMAGEX_SOURCE_LIST_OPTION},
198         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
199         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
200         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
201         {T("rpfix"),       no_argument,       NULL, IMAGEX_RPFIX_OPTION},
202         {T("norpfix"),     no_argument,       NULL, IMAGEX_NORPFIX_OPTION},
203         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
204         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
205         {T("delta-from"),  required_argument, NULL, IMAGEX_DELTA_FROM_OPTION},
206         {NULL, 0, NULL, 0},
207 };
208
209 static const struct option delete_options[] = {
210         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
211         {T("soft"),  no_argument, NULL, IMAGEX_SOFT_OPTION},
212         {NULL, 0, NULL, 0},
213 };
214
215 static const struct option dir_options[] = {
216         {T("path"), required_argument, NULL, IMAGEX_PATH_OPTION},
217         {NULL, 0, NULL, 0},
218 };
219
220 static const struct option export_options[] = {
221         {T("boot"),        no_argument,       NULL, IMAGEX_BOOT_OPTION},
222         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
223         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
224         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
225         {T("compress"),    required_argument, NULL, IMAGEX_COMPRESS_OPTION},
226         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
227         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
228         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
229         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
230         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
231         {NULL, 0, NULL, 0},
232 };
233
234 static const struct option extract_options[] = {
235         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
236         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
237         {T("ref"),         required_argument, NULL, IMAGEX_REF_OPTION},
238         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
239         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
240         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
241         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
242         {T("dest-dir"),    required_argument, NULL, IMAGEX_DEST_DIR_OPTION},
243         {T("to-stdout"),   no_argument,       NULL, IMAGEX_TO_STDOUT_OPTION},
244         {T("include-invalid-names"), no_argument, NULL, IMAGEX_INCLUDE_INVALID_NAMES_OPTION},
245         {NULL, 0, NULL, 0},
246 };
247
248 static const struct option info_options[] = {
249         {T("boot"),         no_argument,       NULL, IMAGEX_BOOT_OPTION},
250         {T("check"),        no_argument,       NULL, IMAGEX_CHECK_OPTION},
251         {T("nocheck"),      no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
252         {T("no-check"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
253         {T("extract-xml"),  required_argument, NULL, IMAGEX_EXTRACT_XML_OPTION},
254         {T("header"),       no_argument,       NULL, IMAGEX_HEADER_OPTION},
255         {T("lookup-table"), no_argument,       NULL, IMAGEX_LOOKUP_TABLE_OPTION},
256         {T("metadata"),     no_argument,       NULL, IMAGEX_METADATA_OPTION},
257         {T("xml"),          no_argument,       NULL, IMAGEX_XML_OPTION},
258         {NULL, 0, NULL, 0},
259 };
260
261 static const struct option join_options[] = {
262         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
263         {NULL, 0, NULL, 0},
264 };
265
266 static const struct option mount_options[] = {
267         {T("check"),             no_argument,       NULL, IMAGEX_CHECK_OPTION},
268         {T("debug"),             no_argument,       NULL, IMAGEX_DEBUG_OPTION},
269         {T("streams-interface"), required_argument, NULL, IMAGEX_STREAMS_INTERFACE_OPTION},
270         {T("ref"),               required_argument, NULL, IMAGEX_REF_OPTION},
271         {T("staging-dir"),       required_argument, NULL, IMAGEX_STAGING_DIR_OPTION},
272         {T("unix-data"),         no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
273         {T("allow-other"),       no_argument,       NULL, IMAGEX_ALLOW_OTHER_OPTION},
274         {NULL, 0, NULL, 0},
275 };
276
277 static const struct option optimize_options[] = {
278         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
279         {T("nocheck"),     no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
280         {T("no-check"),    no_argument,       NULL, IMAGEX_NOCHECK_OPTION},
281         {T("recompress"),  no_argument,       NULL, IMAGEX_RECOMPRESS_OPTION},
282         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
283         {T("pipable"),     no_argument,       NULL, IMAGEX_PIPABLE_OPTION},
284         {T("not-pipable"), no_argument,       NULL, IMAGEX_NOT_PIPABLE_OPTION},
285         {NULL, 0, NULL, 0},
286 };
287
288 static const struct option split_options[] = {
289         {T("check"), no_argument, NULL, IMAGEX_CHECK_OPTION},
290         {NULL, 0, NULL, 0},
291 };
292
293 static const struct option unmount_options[] = {
294         {T("commit"),  no_argument, NULL, IMAGEX_COMMIT_OPTION},
295         {T("check"),   no_argument, NULL, IMAGEX_CHECK_OPTION},
296         {T("rebuild"), no_argument, NULL, IMAGEX_REBUILD_OPTION},
297         {T("lazy"),    no_argument, NULL, IMAGEX_LAZY_OPTION},
298         {NULL, 0, NULL, 0},
299 };
300
301 static const struct option update_options[] = {
302         /* Careful: some of the options here set the defaults for update
303          * commands, but the flags given to an actual update command (and not to
304          * `imagex update' itself are also handled in
305          * update_command_add_option().  */
306         {T("threads"),     required_argument, NULL, IMAGEX_THREADS_OPTION},
307         {T("check"),       no_argument,       NULL, IMAGEX_CHECK_OPTION},
308         {T("rebuild"),     no_argument,       NULL, IMAGEX_REBUILD_OPTION},
309         {T("command"),     required_argument, NULL, IMAGEX_COMMAND_OPTION},
310
311         /* Default delete options */
312         {T("force"),       no_argument,       NULL, IMAGEX_FORCE_OPTION},
313         {T("recursive"),   no_argument,       NULL, IMAGEX_RECURSIVE_OPTION},
314
315         /* Global add option */
316         {T("config"),      required_argument, NULL, IMAGEX_CONFIG_OPTION},
317
318         /* Default add options */
319         {T("verbose"),     no_argument,       NULL, IMAGEX_VERBOSE_OPTION},
320         {T("dereference"), no_argument,       NULL, IMAGEX_DEREFERENCE_OPTION},
321         {T("unix-data"),   no_argument,       NULL, IMAGEX_UNIX_DATA_OPTION},
322         {T("noacls"),      no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
323         {T("no-acls"),     no_argument,       NULL, IMAGEX_NO_ACLS_OPTION},
324         {T("strict-acls"), no_argument,       NULL, IMAGEX_STRICT_ACLS_OPTION},
325
326         {NULL, 0, NULL, 0},
327 };
328
329 #if 0
330 #       define _format_attribute(type, format_str, args_start) \
331                         __attribute__((format(type, format_str, args_start)))
332 #else
333 #       define _format_attribute(type, format_str, args_start)
334 #endif
335
336 /* Print formatted error message to stderr. */
337 static void _format_attribute(printf, 1, 2)
338 imagex_error(const tchar *format, ...)
339 {
340         va_list va;
341         va_start(va, format);
342         tfputs(T("ERROR: "), stderr);
343         tvfprintf(stderr, format, va);
344         tputc(T('\n'), stderr);
345         va_end(va);
346 }
347
348 /* Print formatted error message to stderr. */
349 static void _format_attribute(printf, 1, 2)
350 imagex_error_with_errno(const tchar *format, ...)
351 {
352         int errno_save = errno;
353         va_list va;
354         va_start(va, format);
355         tfputs(T("ERROR: "), stderr);
356         tvfprintf(stderr, format, va);
357         tfprintf(stderr, T(": %"TS"\n"), tstrerror(errno_save));
358         va_end(va);
359 }
360
361 static int
362 verify_image_exists(int image, const tchar *image_name, const tchar *wim_name)
363 {
364         if (image == WIMLIB_NO_IMAGE) {
365                 imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\"!\n"
366                              "       Please specify a 1-based image index or "
367                              "image name.\n"
368                              "       You may use `%"TS"' to list the images "
369                              "contained in a WIM."),
370                              image_name, wim_name, get_cmd_string(CMD_INFO, false));
371                 return -1;
372         }
373         return 0;
374 }
375
376 static int
377 verify_image_is_single(int image)
378 {
379         if (image == WIMLIB_ALL_IMAGES) {
380                 imagex_error(T("Cannot specify all images for this action!"));
381                 return -1;
382         }
383         return 0;
384 }
385
386 static int
387 verify_image_exists_and_is_single(int image, const tchar *image_name,
388                                   const tchar *wim_name)
389 {
390         int ret;
391         ret = verify_image_exists(image, image_name, wim_name);
392         if (ret == 0)
393                 ret = verify_image_is_single(image);
394         return ret;
395 }
396
397 /* Parse the argument to --compress */
398 static int
399 get_compression_type(const tchar *optarg)
400 {
401         if (!tstrcasecmp(optarg, T("maximum")) || !tstrcasecmp(optarg, T("lzx")))
402                 return WIMLIB_COMPRESSION_TYPE_LZX;
403         else if (!tstrcasecmp(optarg, T("fast")) || !tstrcasecmp(optarg, T("xpress")))
404                 return WIMLIB_COMPRESSION_TYPE_XPRESS;
405         else if (!tstrcasecmp(optarg, T("none")))
406                 return WIMLIB_COMPRESSION_TYPE_NONE;
407         else {
408                 imagex_error(T("Invalid compression type \"%"TS"\"! Must be "
409                              "\"maximum\", \"fast\", or \"none\"."), optarg);
410                 return WIMLIB_COMPRESSION_TYPE_INVALID;
411         }
412 }
413
414 /* Returns the size of a file given its name, or -1 if the file does not exist
415  * or its size cannot be determined.  */
416 static off_t
417 file_get_size(const tchar *filename)
418 {
419         struct stat st;
420         if (tstat(filename, &st) == 0)
421                 return st.st_size;
422         else
423                 return (off_t)-1;
424 }
425
426 enum {
427         PARSE_STRING_SUCCESS = 0,
428         PARSE_STRING_FAILURE = 1,
429         PARSE_STRING_NONE = 2,
430 };
431
432 /*
433  * Parses a string token from an array of characters.
434  *
435  * Tokens are either whitespace-delimited, or double or single-quoted.
436  *
437  * @line_p:  Pointer to the pointer to the line of data.  Will be updated
438  *           to point past the string token iff the return value is
439  *           PARSE_STRING_SUCCESS.  If *len_p > 0, (*line_p)[*len_p - 1] must
440  *           be '\0'.
441  *
442  * @len_p:   @len_p initially stores the length of the line of data, which may
443  *           be 0, and it will be updated to the number of bytes remaining in
444  *           the line iff the return value is PARSE_STRING_SUCCESS.
445  *
446  * @fn_ret:  Iff the return value is PARSE_STRING_SUCCESS, a pointer to the
447  *           parsed string token will be returned here.
448  *
449  * Returns: PARSE_STRING_SUCCESS if a string token was successfully parsed; or
450  *          PARSE_STRING_FAILURE if the data was invalid due to a missing
451  *          closing quote; or PARSE_STRING_NONE if the line ended before the
452  *          beginning of a string token was found.
453  */
454 static int
455 parse_string(tchar **line_p, size_t *len_p, tchar **fn_ret)
456 {
457         size_t len = *len_p;
458         tchar *line = *line_p;
459         tchar *fn;
460         tchar quote_char;
461
462         /* Skip leading whitespace */
463         for (;;) {
464                 if (len == 0)
465                         return PARSE_STRING_NONE;
466                 if (!istspace(*line) && *line != T('\0'))
467                         break;
468                 line++;
469                 len--;
470         }
471         quote_char = *line;
472         if (quote_char == T('"') || quote_char == T('\'')) {
473                 /* Quoted string */
474                 line++;
475                 len--;
476                 fn = line;
477                 line = tmemchr(line, quote_char, len);
478                 if (!line) {
479                         imagex_error(T("Missing closing quote: %"TS), fn - 1);
480                         return PARSE_STRING_FAILURE;
481                 }
482         } else {
483                 /* Unquoted string.  Go until whitespace.  Line is terminated
484                  * by '\0', so no need to check 'len'. */
485                 fn = line;
486                 do {
487                         line++;
488                 } while (!istspace(*line) && *line != T('\0'));
489         }
490         *line = T('\0');
491         len -= line - fn;
492         *len_p = len;
493         *line_p = line;
494         *fn_ret = fn;
495         return PARSE_STRING_SUCCESS;
496 }
497
498 /* Parses a line of data (not an empty line or comment) in the source list file
499  * format.  (See the man page for 'wimlib-imagex capture' for details on this
500  * format and the meaning.)
501  *
502  * @line:  Line of data to be parsed.  line[len - 1] must be '\0', unless
503  *         len == 0.  The data in @line will be modified by this function call.
504  *
505  * @len:   Length of the line of data.
506  *
507  * @source:  On success, the capture source and target described by the line is
508  *           written into this destination.  Note that it will contain pointers
509  *           to data in the @line array.
510  *
511  * Returns true if the line was valid; false otherwise.  */
512 static bool
513 parse_source_list_line(tchar *line, size_t len,
514                        struct wimlib_capture_source *source)
515 {
516         /* SOURCE [DEST] */
517         int ret;
518         ret = parse_string(&line, &len, &source->fs_source_path);
519         if (ret != PARSE_STRING_SUCCESS)
520                 return false;
521         ret = parse_string(&line, &len, &source->wim_target_path);
522         if (ret == PARSE_STRING_NONE)
523                 source->wim_target_path = source->fs_source_path;
524         return ret != PARSE_STRING_FAILURE;
525 }
526
527 /* Returns %true if the given line of length @len > 0 is a comment or empty line
528  * in the source list file format. */
529 static bool
530 is_comment_line(const tchar *line, size_t len)
531 {
532         for (;;) {
533                 if (*line == T('#'))
534                         return true;
535                 if (!istspace(*line) && *line != T('\0'))
536                         return false;
537                 ++line;
538                 --len;
539                 if (len == 0)
540                         return true;
541         }
542 }
543
544 static ssize_t
545 text_file_count_lines(tchar **contents_p, size_t *nchars_p)
546 {
547         ssize_t nlines = 0;
548         tchar *contents = *contents_p;
549         size_t nchars = *nchars_p;
550         size_t i;
551
552         for (i = 0; i < nchars; i++)
553                 if (contents[i] == T('\n'))
554                         nlines++;
555
556         /* Handle last line not terminated by a newline */
557         if (nchars != 0 && contents[nchars - 1] != T('\n')) {
558                 contents = realloc(contents, (nchars + 1) * sizeof(tchar));
559                 if (!contents) {
560                         imagex_error(T("Out of memory!"));
561                         return -1;
562                 }
563                 contents[nchars] = T('\n');
564                 *contents_p = contents;
565                 nchars++;
566                 nlines++;
567         }
568         *nchars_p = nchars;
569         return nlines;
570 }
571
572 /* Parses a file in the source list format.  (See the man page for
573  * 'wimlib-imagex capture' for details on this format and the meaning.)
574  *
575  * @source_list_contents:  Contents of the source list file.  Note that this
576  *                         buffer will be modified to save memory allocations,
577  *                         and cannot be freed until the returned array of
578  *                         wimlib_capture_source's has also been freed.
579  *
580  * @source_list_nbytes:    Number of bytes of data in the @source_list_contents
581  *                         buffer.
582  *
583  * @nsources_ret:          On success, the length of the returned array is
584  *                         returned here.
585  *
586  * Returns:   An array of `struct wimlib_capture_source's that can be passed to
587  * the wimlib_add_image_multisource() function to specify how a WIM image is to
588  * be created.  */
589 static struct wimlib_capture_source *
590 parse_source_list(tchar **source_list_contents_p, size_t source_list_nchars,
591                   size_t *nsources_ret)
592 {
593         ssize_t nlines;
594         tchar *p;
595         struct wimlib_capture_source *sources;
596         size_t i, j;
597
598         nlines = text_file_count_lines(source_list_contents_p,
599                                        &source_list_nchars);
600         if (nlines < 0)
601                 return NULL;
602
603         /* Always allocate at least 1 slot, just in case the implementation of
604          * calloc() returns NULL if 0 bytes are requested. */
605         sources = calloc(nlines ?: 1, sizeof(*sources));
606         if (!sources) {
607                 imagex_error(T("out of memory"));
608                 return NULL;
609         }
610         p = *source_list_contents_p;
611         j = 0;
612         for (i = 0; i < nlines; i++) {
613                 /* XXX: Could use rawmemchr() here instead, but it may not be
614                  * available on all platforms. */
615                 tchar *endp = tmemchr(p, T('\n'), source_list_nchars);
616                 size_t len = endp - p + 1;
617                 *endp = T('\0');
618                 if (!is_comment_line(p, len)) {
619                         if (!parse_source_list_line(p, len, &sources[j++])) {
620                                 free(sources);
621                                 return NULL;
622                         }
623                 }
624                 p = endp + 1;
625
626         }
627         *nsources_ret = j;
628         return sources;
629 }
630
631
632 enum capture_config_section {
633         CAPTURE_CONFIG_NO_SECTION,
634         CAPTURE_CONFIG_EXCLUSION_SECTION,
635         CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION,
636         CAPTURE_CONFIG_IGNORE_SECTION,
637 };
638
639 enum {
640         CAPTURE_CONFIG_INVALID_SECTION,
641         CAPTURE_CONFIG_CHANGED_SECTION,
642         CAPTURE_CONFIG_SAME_SECTION,
643 };
644
645 static int
646 check_config_section(tchar *line, size_t len,
647                      enum capture_config_section *cur_section)
648 {
649         while (istspace(*line))
650                 line++;
651
652         if (*line != T('['))
653                 return CAPTURE_CONFIG_SAME_SECTION;
654
655         line++;
656         tchar *endbrace = tstrrchr(line, T(']'));
657         if (!endbrace)
658                 return CAPTURE_CONFIG_SAME_SECTION;
659
660         if (!tmemcmp(line, T("ExclusionList"), endbrace - line)) {
661                 *cur_section = CAPTURE_CONFIG_EXCLUSION_SECTION;
662         } else if (!tmemcmp(line, T("ExclusionException"), endbrace - line)) {
663                 *cur_section = CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION;
664         } else if (!tmemcmp(line, T("CompressionExclusionList"), endbrace - line)) {
665                 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
666                 tfputs(T("WARNING: Ignoring [CompressionExclusionList] section "
667                          "of capture config file\n"),
668                        stderr);
669         } else if (!tmemcmp(line, T("AlignmentList"), endbrace - line)) {
670                 *cur_section = CAPTURE_CONFIG_IGNORE_SECTION;
671                 tfputs(T("WARNING: Ignoring [AlignmentList] section "
672                          "of capture config file\n"),
673                        stderr);
674         } else {
675                 imagex_error(T("Invalid capture config file section \"%"TS"\""),
676                              line - 1);
677                 return CAPTURE_CONFIG_INVALID_SECTION;
678         }
679         return CAPTURE_CONFIG_CHANGED_SECTION;
680 }
681
682
683 static bool
684 pattern_list_add_pattern(struct wimlib_pattern_list *pat_list,
685                          tchar *pat)
686 {
687         if (pat_list->num_pats == pat_list->num_allocated_pats) {
688                 tchar **pats;
689                 size_t num_allocated_pats = pat_list->num_pats + 8;
690
691                 pats = realloc(pat_list->pats,
692                                num_allocated_pats * sizeof(pat_list->pats[0]));
693                 if (!pats) {
694                         imagex_error(T("Out of memory!"));
695                         return false;
696                 }
697                 pat_list->pats = pats;
698                 pat_list->num_allocated_pats = num_allocated_pats;
699         }
700         pat_list->pats[pat_list->num_pats++] = pat;
701         return true;
702 }
703
704 static bool
705 parse_capture_config_line(tchar *line, size_t len,
706                           enum capture_config_section *cur_section,
707                           struct wimlib_capture_config *config)
708 {
709         tchar *filename;
710         int ret;
711
712         ret = check_config_section(line, len, cur_section);
713         if (ret == CAPTURE_CONFIG_INVALID_SECTION)
714                 return false;
715         if (ret == CAPTURE_CONFIG_CHANGED_SECTION)
716                 return true;
717
718         switch (*cur_section) {
719         case CAPTURE_CONFIG_NO_SECTION:
720                 imagex_error(T("Line \"%"TS"\" is not in a section "
721                                "(such as [ExclusionList]"), line);
722                 return false;
723         case CAPTURE_CONFIG_EXCLUSION_SECTION:
724                 if (parse_string(&line, &len, &filename) != PARSE_STRING_SUCCESS)
725                         return false;
726                 return pattern_list_add_pattern(&config->exclusion_pats,
727                                                 filename);
728         case CAPTURE_CONFIG_EXCLUSION_EXCEPTION_SECTION:
729                 if (parse_string(&line, &len, &filename) != PARSE_STRING_SUCCESS)
730                         return false;
731                 return pattern_list_add_pattern(&config->exclusion_exception_pats,
732                                                 filename);
733         case CAPTURE_CONFIG_IGNORE_SECTION:
734                 return true;
735         }
736         return false;
737 }
738
739 static int
740 parse_capture_config(tchar **contents_p, size_t nchars,
741                      struct wimlib_capture_config *config)
742 {
743         ssize_t nlines;
744         tchar *p;
745         size_t i;
746         enum capture_config_section cur_section;
747
748         memset(config, 0, sizeof(*config));
749
750         nlines = text_file_count_lines(contents_p, &nchars);
751         if (nlines < 0)
752                 return -1;
753
754         cur_section = CAPTURE_CONFIG_NO_SECTION;
755         p = *contents_p;
756         for (i = 0; i < nlines; i++) {
757                 tchar *endp = tmemchr(p, T('\n'), nchars);
758                 size_t len = endp - p + 1;
759                 *endp = T('\0');
760                 if (!is_comment_line(p, len))
761                         if (!parse_capture_config_line(p, len, &cur_section, config))
762                                 return -1;
763                 p = endp + 1;
764
765         }
766         return 0;
767 }
768
769 /* Reads the contents of a file into memory. */
770 static char *
771 file_get_contents(const tchar *filename, size_t *len_ret)
772 {
773         struct stat stbuf;
774         void *buf = NULL;
775         size_t len;
776         FILE *fp;
777
778         if (tstat(filename, &stbuf) != 0) {
779                 imagex_error_with_errno(T("Failed to stat the file \"%"TS"\""), filename);
780                 goto out;
781         }
782         len = stbuf.st_size;
783
784         fp = tfopen(filename, T("rb"));
785         if (!fp) {
786                 imagex_error_with_errno(T("Failed to open the file \"%"TS"\""), filename);
787                 goto out;
788         }
789
790         buf = malloc(len ? len : 1);
791         if (!buf) {
792                 imagex_error(T("Failed to allocate buffer of %zu bytes to hold "
793                                "contents of file \"%"TS"\""), len, filename);
794                 goto out_fclose;
795         }
796         if (fread(buf, 1, len, fp) != len) {
797                 imagex_error_with_errno(T("Failed to read %zu bytes from the "
798                                           "file \"%"TS"\""), len, filename);
799                 goto out_free_buf;
800         }
801         *len_ret = len;
802         goto out_fclose;
803 out_free_buf:
804         free(buf);
805         buf = NULL;
806 out_fclose:
807         fclose(fp);
808 out:
809         return buf;
810 }
811
812 /* Read standard input until EOF and return the full contents in a malloc()ed
813  * buffer and the number of bytes of data in @len_ret.  Returns NULL on read
814  * error. */
815 static char *
816 stdin_get_contents(size_t *len_ret)
817 {
818         /* stdin can, of course, be a pipe or other non-seekable file, so the
819          * total length of the data cannot be pre-determined */
820         char *buf = NULL;
821         size_t newlen = 1024;
822         size_t pos = 0;
823         size_t inc = 1024;
824         for (;;) {
825                 char *p = realloc(buf, newlen);
826                 size_t bytes_read, bytes_to_read;
827                 if (!p) {
828                         imagex_error(T("out of memory while reading stdin"));
829                         break;
830                 }
831                 buf = p;
832                 bytes_to_read = newlen - pos;
833                 bytes_read = fread(&buf[pos], 1, bytes_to_read, stdin);
834                 pos += bytes_read;
835                 if (bytes_read != bytes_to_read) {
836                         if (feof(stdin)) {
837                                 *len_ret = pos;
838                                 return buf;
839                         } else {
840                                 imagex_error_with_errno(T("error reading stdin"));
841                                 break;
842                         }
843                 }
844                 newlen += inc;
845                 inc *= 3;
846                 inc /= 2;
847         }
848         free(buf);
849         return NULL;
850 }
851
852
853 static tchar *
854 translate_text_to_tstr(char *text, size_t num_bytes, size_t *num_tchars_ret)
855 {
856 #ifndef __WIN32__
857         /* On non-Windows, assume an ASCII-compatible encoding, such as UTF-8.
858          * */
859         *num_tchars_ret = num_bytes;
860         return text;
861 #else /* !__WIN32__ */
862         /* On Windows, translate the text to UTF-16LE */
863         wchar_t *text_wstr;
864         size_t num_wchars;
865
866         if (num_bytes >= 2 &&
867             ((text[0] == 0xff && text[1] == 0xfe) ||
868              (text[0] <= 0x7f && text[1] == 0x00)))
869         {
870                 /* File begins with 0xfeff, the BOM for UTF-16LE, or it begins
871                  * with something that looks like an ASCII character encoded as
872                  * a UTF-16LE code unit.  Assume the file is encoded as
873                  * UTF-16LE.  This is not a 100% reliable check. */
874                 num_wchars = num_bytes / 2;
875                 text_wstr = (wchar_t*)text;
876         } else {
877                 /* File does not look like UTF-16LE.  Assume it is encoded in
878                  * the current Windows code page.  I think these are always
879                  * ASCII-compatible, so any so-called "plain-text" (ASCII) files
880                  * should work as expected. */
881                 text_wstr = win32_mbs_to_wcs(text,
882                                              num_bytes,
883                                              &num_wchars);
884                 free(text);
885         }
886         *num_tchars_ret = num_wchars;
887         return text_wstr;
888 #endif /* __WIN32__ */
889 }
890
891 static tchar *
892 file_get_text_contents(const tchar *filename, size_t *num_tchars_ret)
893 {
894         char *contents;
895         size_t num_bytes;
896
897         contents = file_get_contents(filename, &num_bytes);
898         if (!contents)
899                 return NULL;
900         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
901 }
902
903 static tchar *
904 stdin_get_text_contents(size_t *num_tchars_ret)
905 {
906         char *contents;
907         size_t num_bytes;
908
909         contents = stdin_get_contents(&num_bytes);
910         if (!contents)
911                 return NULL;
912         return translate_text_to_tstr(contents, num_bytes, num_tchars_ret);
913 }
914
915 #define TO_PERCENT(numerator, denominator) \
916         (((denominator) == 0) ? 0 : ((numerator) * 100 / (denominator)))
917
918 /* Given an enumerated value for WIM compression type, return a descriptive
919  * string. */
920 static const tchar *
921 get_data_type(int ctype)
922 {
923         switch (ctype) {
924         case WIMLIB_COMPRESSION_TYPE_NONE:
925                 return T("uncompressed");
926         case WIMLIB_COMPRESSION_TYPE_LZX:
927                 return T("LZX-compressed");
928         case WIMLIB_COMPRESSION_TYPE_XPRESS:
929                 return T("XPRESS-compressed");
930         }
931         return NULL;
932 }
933
934 #define GIBIBYTE_MIN_NBYTES 10000000000ULL
935 #define MEBIBYTE_MIN_NBYTES 10000000ULL
936 #define KIBIBYTE_MIN_NBYTES 10000ULL
937
938 static unsigned
939 get_unit(uint64_t total_bytes, const tchar **name_ret)
940 {
941         if (total_bytes >= GIBIBYTE_MIN_NBYTES) {
942                 *name_ret = T("GiB");
943                 return 30;
944         } else if (total_bytes >= MEBIBYTE_MIN_NBYTES) {
945                 *name_ret = T("MiB");
946                 return 20;
947         } else if (total_bytes >= KIBIBYTE_MIN_NBYTES) {
948                 *name_ret = T("KiB");
949                 return 10;
950         } else {
951                 *name_ret = T("bytes");
952                 return 0;
953         }
954 }
955
956 /* Progress callback function passed to various wimlib functions. */
957 static int
958 imagex_progress_func(enum wimlib_progress_msg msg,
959                      const union wimlib_progress_info *info)
960 {
961         unsigned percent_done;
962         unsigned unit_shift;
963         const tchar *unit_name;
964         if (imagex_be_quiet)
965                 return 0;
966         switch (msg) {
967         case WIMLIB_PROGRESS_MSG_WRITE_STREAMS:
968                 unit_shift = get_unit(info->write_streams.total_bytes, &unit_name);
969                 percent_done = TO_PERCENT(info->write_streams.completed_bytes,
970                                           info->write_streams.total_bytes);
971
972                 if (info->write_streams.completed_streams == 0) {
973                         const tchar *data_type;
974
975                         data_type = get_data_type(info->write_streams.compression_type);
976                         imagex_printf(T("Writing %"TS" data using %u thread%"TS"\n"),
977                                 data_type, info->write_streams.num_threads,
978                                 (info->write_streams.num_threads == 1) ? T("") : T("s"));
979                 }
980                 if (info->write_streams.total_parts <= 1) {
981                         imagex_printf(T("\r%"PRIu64" %"TS" of %"PRIu64" %"TS" (uncompressed) "
982                                 "written (%u%% done)"),
983                                 info->write_streams.completed_bytes >> unit_shift,
984                                 unit_name,
985                                 info->write_streams.total_bytes >> unit_shift,
986                                 unit_name,
987                                 percent_done);
988                 } else {
989                         imagex_printf(T("\rWriting resources from part %u of %u: "
990                                   "%"PRIu64 " %"TS" of %"PRIu64" %"TS" (%u%%) written"),
991                                 (info->write_streams.completed_parts ==
992                                         info->write_streams.total_parts) ?
993                                                 info->write_streams.completed_parts :
994                                                 info->write_streams.completed_parts + 1,
995                                 info->write_streams.total_parts,
996                                 info->write_streams.completed_bytes >> unit_shift,
997                                 unit_name,
998                                 info->write_streams.total_bytes >> unit_shift,
999                                 unit_name,
1000                                 percent_done);
1001                 }
1002                 if (info->write_streams.completed_bytes >= info->write_streams.total_bytes)
1003                         imagex_printf(T("\n"));
1004                 break;
1005         case WIMLIB_PROGRESS_MSG_SCAN_BEGIN:
1006                 imagex_printf(T("Scanning \"%"TS"\""), info->scan.source);
1007                 if (*info->scan.wim_target_path) {
1008                         imagex_printf(T(" (loading as WIM path: "
1009                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING"%"TS"\")...\n"),
1010                                info->scan.wim_target_path);
1011                 } else {
1012                         imagex_printf(T(" (loading as root of WIM image)...\n"));
1013                 }
1014                 break;
1015         case WIMLIB_PROGRESS_MSG_SCAN_DENTRY:
1016                 switch (info->scan.status) {
1017                 case WIMLIB_SCAN_DENTRY_OK:
1018                         imagex_printf(T("Scanning \"%"TS"\"\n"), info->scan.cur_path);
1019                         break;
1020                 case WIMLIB_SCAN_DENTRY_EXCLUDED:
1021                         imagex_printf(T("Excluding \"%"TS"\" from capture\n"), info->scan.cur_path);
1022                         break;
1023                 case WIMLIB_SCAN_DENTRY_UNSUPPORTED:
1024                         imagex_printf(T("WARNING: Excluding unsupported file or directory\n"
1025                                         "         \"%"TS"\" from capture\n"), info->scan.cur_path);
1026                         break;
1027                 }
1028                 break;
1029         case WIMLIB_PROGRESS_MSG_VERIFY_INTEGRITY:
1030                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1031                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1032                                           info->integrity.total_bytes);
1033                 imagex_printf(T("\rVerifying integrity of \"%"TS"\": %"PRIu64" %"TS" "
1034                         "of %"PRIu64" %"TS" (%u%%) done"),
1035                         info->integrity.filename,
1036                         info->integrity.completed_bytes >> unit_shift,
1037                         unit_name,
1038                         info->integrity.total_bytes >> unit_shift,
1039                         unit_name,
1040                         percent_done);
1041                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1042                         imagex_printf(T("\n"));
1043                 break;
1044         case WIMLIB_PROGRESS_MSG_CALC_INTEGRITY:
1045                 unit_shift = get_unit(info->integrity.total_bytes, &unit_name);
1046                 percent_done = TO_PERCENT(info->integrity.completed_bytes,
1047                                           info->integrity.total_bytes);
1048                 imagex_printf(T("\rCalculating integrity table for WIM: %"PRIu64" %"TS" "
1049                           "of %"PRIu64" %"TS" (%u%%) done"),
1050                         info->integrity.completed_bytes >> unit_shift,
1051                         unit_name,
1052                         info->integrity.total_bytes >> unit_shift,
1053                         unit_name,
1054                         percent_done);
1055                 if (info->integrity.completed_bytes == info->integrity.total_bytes)
1056                         imagex_printf(T("\n"));
1057                 break;
1058         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_BEGIN:
1059                 imagex_printf(T("Applying image %d (\"%"TS"\") from \"%"TS"\" "
1060                           "to %"TS" \"%"TS"\"\n"),
1061                         info->extract.image,
1062                         info->extract.image_name,
1063                         info->extract.wimfile_name,
1064                         ((info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) ?
1065                          T("NTFS volume") : T("directory")),
1066                         info->extract.target);
1067                 break;
1068         case WIMLIB_PROGRESS_MSG_EXTRACT_TREE_BEGIN:
1069                 imagex_printf(T("Extracting "
1070                           "\""WIMLIB_WIM_PATH_SEPARATOR_STRING"%"TS"\" from image %d (\"%"TS"\") "
1071                           "in \"%"TS"\" to \"%"TS"\"\n"),
1072                         info->extract.extract_root_wim_source_path,
1073                         info->extract.image,
1074                         info->extract.image_name,
1075                         info->extract.wimfile_name,
1076                         info->extract.target);
1077                 break;
1078         case WIMLIB_PROGRESS_MSG_EXTRACT_STREAMS:
1079                 percent_done = TO_PERCENT(info->extract.completed_bytes,
1080                                           info->extract.total_bytes);
1081                 unit_shift = get_unit(info->extract.total_bytes, &unit_name);
1082                 imagex_printf(T("\rExtracting files: "
1083                           "%"PRIu64" %"TS" of %"PRIu64" %"TS" (%u%%) done"),
1084                         info->extract.completed_bytes >> unit_shift,
1085                         unit_name,
1086                         info->extract.total_bytes >> unit_shift,
1087                         unit_name,
1088                         percent_done);
1089                 if (info->extract.completed_bytes >= info->extract.total_bytes)
1090                         imagex_printf(T("\n"));
1091                 break;
1092         case WIMLIB_PROGRESS_MSG_EXTRACT_SPWM_PART_BEGIN:
1093                 if (info->extract.total_parts != 1) {
1094                         imagex_printf(T("\nReading split pipable WIM part %u of %u\n"),
1095                                       info->extract.part_number,
1096                                       info->extract.total_parts);
1097                 }
1098                 break;
1099         case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1100                 if (info->extract.extract_root_wim_source_path[0] == T('\0'))
1101                         imagex_printf(T("Setting timestamps on all extracted files...\n"));
1102                 break;
1103         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1104                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1105                         imagex_printf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1106                                 info->extract.target);
1107                 }
1108                 break;
1109         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1110                 percent_done = TO_PERCENT(info->split.completed_bytes,
1111                                           info->split.total_bytes);
1112                 unit_shift = get_unit(info->split.total_bytes, &unit_name);
1113                 imagex_printf(T("Writing \"%"TS"\" (part %u of %u): %"PRIu64" %"TS" of "
1114                           "%"PRIu64" %"TS" (%u%%) written\n"),
1115                         info->split.part_name,
1116                         info->split.cur_part_number,
1117                         info->split.total_parts,
1118                         info->split.completed_bytes >> unit_shift,
1119                         unit_name,
1120                         info->split.total_bytes >> unit_shift,
1121                         unit_name,
1122                         percent_done);
1123                 break;
1124         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1125                 if (info->split.completed_bytes == info->split.total_bytes) {
1126                         imagex_printf(T("Finished writing split WIM part %u of %u\n"),
1127                                 info->split.cur_part_number,
1128                                 info->split.total_parts);
1129                 }
1130                 break;
1131         case WIMLIB_PROGRESS_MSG_UPDATE_END_COMMAND:
1132                 switch (info->update.command->op) {
1133                 case WIMLIB_UPDATE_OP_DELETE:
1134                         imagex_printf(T("Deleted WIM path "
1135                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1136                                 info->update.command->delete.wim_path);
1137                         break;
1138                 case WIMLIB_UPDATE_OP_RENAME:
1139                         imagex_printf(T("Renamed WIM path "
1140                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\" => "
1141                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1142                                 info->update.command->rename.wim_source_path,
1143                                 info->update.command->rename.wim_target_path);
1144                         break;
1145                 case WIMLIB_UPDATE_OP_ADD:
1146                 default:
1147                         break;
1148                 }
1149                 break;
1150         default:
1151                 break;
1152         }
1153         fflush(imagex_info_file);
1154         return 0;
1155 }
1156
1157 /* Open all the split WIM parts that correspond to a file glob.
1158  *
1159  * @first_part specifies the first part of the split WIM and it may be either
1160  * included or omitted from the glob. */
1161 static int
1162 open_swms_from_glob(const tchar *swm_glob,
1163                     const tchar *first_part,
1164                     int open_flags,
1165                     WIMStruct ***additional_swms_ret,
1166                     unsigned *num_additional_swms_ret)
1167 {
1168         unsigned num_additional_swms = 0;
1169         WIMStruct **additional_swms = NULL;
1170         glob_t globbuf;
1171         int ret;
1172
1173         /* Warning: glob() is replaced in Windows native builds */
1174         ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1175         if (ret) {
1176                 if (ret == GLOB_NOMATCH) {
1177                         imagex_error(T("Found no files for glob \"%"TS"\""),
1178                                      swm_glob);
1179                 } else {
1180                         imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
1181                                                 swm_glob);
1182                 }
1183                 ret = -1;
1184                 goto out;
1185         }
1186         num_additional_swms = globbuf.gl_pathc;
1187         additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
1188         if (!additional_swms) {
1189                 imagex_error(T("Out of memory"));
1190                 ret = -1;
1191                 goto out_globfree;
1192         }
1193         unsigned offset = 0;
1194         for (unsigned i = 0; i < num_additional_swms; i++) {
1195                 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
1196                         offset++;
1197                         continue;
1198                 }
1199                 ret = wimlib_open_wim(globbuf.gl_pathv[i],
1200                                       open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
1201                                       &additional_swms[i - offset],
1202                                       imagex_progress_func);
1203                 if (ret)
1204                         goto out_close_swms;
1205         }
1206         *additional_swms_ret = additional_swms;
1207         *num_additional_swms_ret = num_additional_swms - offset;
1208         ret = 0;
1209         goto out_globfree;
1210 out_close_swms:
1211         for (unsigned i = 0; i < num_additional_swms; i++)
1212                 wimlib_free(additional_swms[i]);
1213         free(additional_swms);
1214 out_globfree:
1215         globfree(&globbuf);
1216 out:
1217         return ret;
1218 }
1219
1220
1221 static unsigned
1222 parse_num_threads(const tchar *optarg)
1223 {
1224         tchar *tmp;
1225         unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1226         if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1227                 imagex_error(T("Number of threads must be a non-negative integer!"));
1228                 return UINT_MAX;
1229         } else {
1230                 return ul_nthreads;
1231         }
1232 }
1233
1234 /*
1235  * Parse an option passed to an update command.
1236  *
1237  * @op:         One of WIMLIB_UPDATE_OP_* that indicates the command being
1238  *              parsed.
1239  *
1240  * @option:     Text string for the option (beginning with --)
1241  *
1242  * @cmd:        `struct wimlib_update_command' that is being constructed for
1243  *              this command.
1244  *
1245  * Returns true if the option was recognized; false if not.
1246  */
1247 static bool
1248 update_command_add_option(int op, const tchar *option,
1249                           struct wimlib_update_command *cmd)
1250 {
1251         bool recognized = true;
1252         switch (op) {
1253         case WIMLIB_UPDATE_OP_ADD:
1254                 if (!tstrcmp(option, T("--verbose")))
1255                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_VERBOSE;
1256                 else if (!tstrcmp(option, T("--unix-data")))
1257                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_UNIX_DATA;
1258                 else if (!tstrcmp(option, T("--no-acls")) || !tstrcmp(option, T("--noacls")))
1259                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_NO_ACLS;
1260                 else if (!tstrcmp(option, T("--strict-acls")))
1261                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_STRICT_ACLS;
1262                 else if (!tstrcmp(option, T("--dereference")))
1263                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_DEREFERENCE;
1264                 else
1265                         recognized = false;
1266                 break;
1267         case WIMLIB_UPDATE_OP_DELETE:
1268                 if (!tstrcmp(option, T("--force")))
1269                         cmd->delete.delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
1270                 else if (!tstrcmp(option, T("--recursive")))
1271                         cmd->delete.delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
1272                 else
1273                         recognized = false;
1274                 break;
1275         default:
1276                 recognized = false;
1277                 break;
1278         }
1279         return recognized;
1280 }
1281
1282 /* How many nonoption arguments each `imagex update' command expects */
1283 static const unsigned update_command_num_nonoptions[] = {
1284         [WIMLIB_UPDATE_OP_ADD] = 2,
1285         [WIMLIB_UPDATE_OP_DELETE] = 1,
1286         [WIMLIB_UPDATE_OP_RENAME] = 2,
1287 };
1288
1289 static void
1290 update_command_add_nonoption(int op, const tchar *nonoption,
1291                              struct wimlib_update_command *cmd,
1292                              unsigned num_nonoptions)
1293 {
1294         switch (op) {
1295         case WIMLIB_UPDATE_OP_ADD:
1296                 if (num_nonoptions == 0)
1297                         cmd->add.fs_source_path = (tchar*)nonoption;
1298                 else
1299                         cmd->add.wim_target_path = (tchar*)nonoption;
1300                 break;
1301         case WIMLIB_UPDATE_OP_DELETE:
1302                 cmd->delete.wim_path = (tchar*)nonoption;
1303                 break;
1304         case WIMLIB_UPDATE_OP_RENAME:
1305                 if (num_nonoptions == 0)
1306                         cmd->rename.wim_source_path = (tchar*)nonoption;
1307                 else
1308                         cmd->rename.wim_target_path = (tchar*)nonoption;
1309                 break;
1310         }
1311 }
1312
1313 /*
1314  * Parse a command passed on stdin to `imagex update'.
1315  *
1316  * @line:       Text of the command.
1317  * @len:        Length of the line, including a null terminator
1318  *              at line[len - 1].
1319  *
1320  * @command:    A `struct wimlib_update_command' to fill in from the parsed
1321  *              line.
1322  *
1323  * @line_number: Line number of the command, for diagnostics.
1324  *
1325  * Returns true on success; returns false on parse error.
1326  */
1327 static bool
1328 parse_update_command(tchar *line, size_t len,
1329                      struct wimlib_update_command *command,
1330                      size_t line_number)
1331 {
1332         int ret;
1333         tchar *command_name;
1334         int op;
1335         size_t num_nonoptions;
1336
1337         /* Get the command name ("add", "delete", "rename") */
1338         ret = parse_string(&line, &len, &command_name);
1339         if (ret != PARSE_STRING_SUCCESS)
1340                 return false;
1341
1342         if (!tstrcasecmp(command_name, T("add"))) {
1343                 op = WIMLIB_UPDATE_OP_ADD;
1344         } else if (!tstrcasecmp(command_name, T("delete"))) {
1345                 op = WIMLIB_UPDATE_OP_DELETE;
1346         } else if (!tstrcasecmp(command_name, T("rename"))) {
1347                 op = WIMLIB_UPDATE_OP_RENAME;
1348         } else {
1349                 imagex_error(T("Unknown update command \"%"TS"\" on line %zu"),
1350                              command_name, line_number);
1351                 return false;
1352         }
1353         command->op = op;
1354
1355         /* Parse additional options and non-options as needed */
1356         num_nonoptions = 0;
1357         for (;;) {
1358                 tchar *next_string;
1359
1360                 ret = parse_string(&line, &len, &next_string);
1361                 if (ret == PARSE_STRING_NONE) /* End of line */
1362                         break;
1363                 else if (ret != PARSE_STRING_SUCCESS) /* Parse failure */
1364                         return false;
1365                 if (next_string[0] == T('-') && next_string[1] == T('-')) {
1366                         /* Option */
1367                         if (!update_command_add_option(op, next_string, command))
1368                         {
1369                                 imagex_error(T("Unrecognized option \"%"TS"\" to "
1370                                                "update command \"%"TS"\" on line %zu"),
1371                                              next_string, command_name, line_number);
1372
1373                                 return false;
1374                         }
1375                 } else {
1376                         /* Nonoption */
1377                         if (num_nonoptions == update_command_num_nonoptions[op])
1378                         {
1379                                 imagex_error(T("Unexpected argument \"%"TS"\" in "
1380                                                "update command on line %zu\n"
1381                                                "       (The \"%"TS"\" command only "
1382                                                "takes %zu nonoption arguments!)\n"),
1383                                              next_string, line_number,
1384                                              command_name, num_nonoptions);
1385                                 return false;
1386                         }
1387                         update_command_add_nonoption(op, next_string,
1388                                                      command, num_nonoptions);
1389                         num_nonoptions++;
1390                 }
1391         }
1392
1393         if (num_nonoptions != update_command_num_nonoptions[op]) {
1394                 imagex_error(T("Not enough arguments to update command "
1395                                "\"%"TS"\" on line %zu"), command_name, line_number);
1396                 return false;
1397         }
1398         return true;
1399 }
1400
1401 static struct wimlib_update_command *
1402 parse_update_command_file(tchar **cmd_file_contents_p, size_t cmd_file_nchars,
1403                           size_t *num_cmds_ret)
1404 {
1405         ssize_t nlines;
1406         tchar *p;
1407         struct wimlib_update_command *cmds;
1408         size_t i, j;
1409
1410         nlines = text_file_count_lines(cmd_file_contents_p,
1411                                        &cmd_file_nchars);
1412         if (nlines < 0)
1413                 return NULL;
1414
1415         /* Always allocate at least 1 slot, just in case the implementation of
1416          * calloc() returns NULL if 0 bytes are requested. */
1417         cmds = calloc(nlines ?: 1, sizeof(struct wimlib_update_command));
1418         if (!cmds) {
1419                 imagex_error(T("out of memory"));
1420                 return NULL;
1421         }
1422         p = *cmd_file_contents_p;
1423         j = 0;
1424         for (i = 0; i < nlines; i++) {
1425                 /* XXX: Could use rawmemchr() here instead, but it may not be
1426                  * available on all platforms. */
1427                 tchar *endp = tmemchr(p, T('\n'), cmd_file_nchars);
1428                 size_t len = endp - p + 1;
1429                 *endp = T('\0');
1430                 if (!is_comment_line(p, len)) {
1431                         if (!parse_update_command(p, len, &cmds[j++], i + 1)) {
1432                                 free(cmds);
1433                                 return NULL;
1434                         }
1435                 }
1436                 p = endp + 1;
1437         }
1438         *num_cmds_ret = j;
1439         return cmds;
1440 }
1441
1442 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1443  * one image from a WIM file to a NTFS volume.  */
1444 static int
1445 imagex_apply(int argc, tchar **argv, int cmd)
1446 {
1447         int c;
1448         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1449         int image;
1450         WIMStruct *wim;
1451         int ret;
1452         const tchar *wimfile;
1453         const tchar *target;
1454         const tchar *image_num_or_name;
1455         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1456
1457         const tchar *swm_glob = NULL;
1458         WIMStruct **additional_swms;
1459         unsigned num_additional_swms;
1460
1461         for_opt(c, apply_options) {
1462                 switch (c) {
1463                 case IMAGEX_CHECK_OPTION:
1464                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1465                         break;
1466                 case IMAGEX_HARDLINK_OPTION:
1467                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1468                         break;
1469                 case IMAGEX_SYMLINK_OPTION:
1470                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1471                         break;
1472                 case IMAGEX_VERBOSE_OPTION:
1473                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1474                         break;
1475                 case IMAGEX_REF_OPTION:
1476                         swm_glob = optarg;
1477                         break;
1478                 case IMAGEX_UNIX_DATA_OPTION:
1479                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1480                         break;
1481                 case IMAGEX_NO_ACLS_OPTION:
1482                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1483                         break;
1484                 case IMAGEX_STRICT_ACLS_OPTION:
1485                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1486                         break;
1487                 case IMAGEX_NORPFIX_OPTION:
1488                         extract_flags |= WIMLIB_EXTRACT_FLAG_NORPFIX;
1489                         break;
1490                 case IMAGEX_RPFIX_OPTION:
1491                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1492                         break;
1493                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
1494                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
1495                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
1496                         break;
1497                 case IMAGEX_RESUME_OPTION:
1498                         extract_flags |= WIMLIB_EXTRACT_FLAG_RESUME;
1499                         break;
1500                 default:
1501                         goto out_usage;
1502                 }
1503         }
1504         argc -= optind;
1505         argv += optind;
1506         if (argc != 2 && argc != 3)
1507                 goto out_usage;
1508
1509         wimfile = argv[0];
1510
1511         if (!tstrcmp(wimfile, T("-"))) {
1512                 /* Attempt to apply pipable WIM from standard input.  */
1513                 if (argc == 2) {
1514                         image_num_or_name = NULL;
1515                         target = argv[1];
1516                 } else {
1517                         image_num_or_name = argv[1];
1518                         target = argv[2];
1519                 }
1520                 wim = NULL;
1521                 num_additional_swms = 0;
1522                 additional_swms = NULL;
1523         } else {
1524                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
1525                                       imagex_progress_func);
1526                 if (ret)
1527                         goto out;
1528
1529                 if (argc >= 3) {
1530                         /* Image explicitly specified.  */
1531                         image_num_or_name = argv[1];
1532                         image = wimlib_resolve_image(wim, image_num_or_name);
1533                         ret = verify_image_exists(image, image_num_or_name, wimfile);
1534                         if (ret)
1535                                 goto out_wimlib_free;
1536                         target = argv[2];
1537                 } else {
1538                         /* No image specified; default to image 1, but only if the WIM
1539                          * contains exactly one image.  */
1540                         struct wimlib_wim_info info;
1541
1542                         wimlib_get_wim_info(wim, &info);
1543                         if (info.image_count != 1) {
1544                                 imagex_error(T("\"%"TS"\" contains %d images; "
1545                                                "Please select one (or all)."),
1546                                              wimfile, info.image_count);
1547                                 wimlib_free(wim);
1548                                 goto out_usage;
1549                         }
1550                         image = 1;
1551                         target = argv[1];
1552                 }
1553
1554                 if (swm_glob) {
1555                         ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1556                                                   &additional_swms,
1557                                                   &num_additional_swms);
1558                         if (ret)
1559                                 goto out_wimlib_free;
1560                 } else {
1561                         additional_swms = NULL;
1562                         num_additional_swms = 0;
1563                 }
1564         }
1565
1566 #ifndef __WIN32__
1567         {
1568                 /* Interpret a regular file or block device target as a NTFS
1569                  * volume.  */
1570                 struct stat stbuf;
1571
1572                 if (tstat(target, &stbuf)) {
1573                         if (errno != ENOENT) {
1574                                 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1575                                                         target);
1576                                 ret = -1;
1577                                 goto out_free_swms;
1578                         }
1579                 } else {
1580                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1581                                 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1582                 }
1583         }
1584 #endif
1585
1586         if (wim) {
1587                 ret = wimlib_extract_image(wim, image, target, extract_flags,
1588                                            additional_swms, num_additional_swms,
1589                                            imagex_progress_func);
1590         } else {
1591                 set_fd_to_binary_mode(STDIN_FILENO);
1592                 ret = wimlib_extract_image_from_pipe(STDIN_FILENO,
1593                                                      image_num_or_name,
1594                                                      target, extract_flags,
1595                                                      imagex_progress_func);
1596         }
1597         if (ret == 0)
1598                 imagex_printf(T("Done applying WIM image.\n"));
1599 out_free_swms:
1600         for (unsigned i = 0; i < num_additional_swms; i++)
1601                 wimlib_free(additional_swms[i]);
1602         free(additional_swms);
1603 out_wimlib_free:
1604         wimlib_free(wim);
1605 out:
1606         return ret;
1607
1608 out_usage:
1609         usage(CMD_APPLY, stderr);
1610         ret = -1;
1611         goto out;
1612 }
1613
1614 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1615  * directory trees.  'wimlib-imagex capture': create a new WIM file containing
1616  * the desired image.  'wimlib-imagex append': add a new image to an existing
1617  * WIM file. */
1618 static int
1619 imagex_capture_or_append(int argc, tchar **argv, int cmd)
1620 {
1621         int c;
1622         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
1623         int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE |
1624                               WIMLIB_ADD_IMAGE_FLAG_WINCONFIG;
1625         int write_flags = 0;
1626         int compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
1627         const tchar *wimfile;
1628         int wim_fd;
1629         const tchar *name;
1630         const tchar *desc;
1631         const tchar *flags_element = NULL;
1632         const tchar *template_image_name_or_num = NULL;
1633         int template_image;
1634         WIMStruct *wim;
1635         int ret;
1636         unsigned num_threads = 0;
1637
1638         tchar *source;
1639         tchar *source_copy;
1640
1641         const tchar *config_file = NULL;
1642         tchar *config_str;
1643         struct wimlib_capture_config *config;
1644
1645         bool source_list = false;
1646         size_t source_list_nchars;
1647         tchar *source_list_contents;
1648         bool capture_sources_malloced;
1649         struct wimlib_capture_source *capture_sources;
1650         size_t num_sources;
1651         bool name_defaulted;
1652
1653         for_opt(c, capture_or_append_options) {
1654                 switch (c) {
1655                 case IMAGEX_BOOT_OPTION:
1656                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1657                         break;
1658                 case IMAGEX_CHECK_OPTION:
1659                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1660                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1661                         break;
1662                 case IMAGEX_NOCHECK_OPTION:
1663                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
1664                         break;
1665                 case IMAGEX_CONFIG_OPTION:
1666                         config_file = optarg;
1667                         add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_WINCONFIG;
1668                         break;
1669                 case IMAGEX_COMPRESS_OPTION:
1670                         compression_type = get_compression_type(optarg);
1671                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1672                                 goto out_err;
1673                         break;
1674                 case IMAGEX_FLAGS_OPTION:
1675                         flags_element = optarg;
1676                         break;
1677                 case IMAGEX_DEREFERENCE_OPTION:
1678                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1679                         break;
1680                 case IMAGEX_VERBOSE_OPTION:
1681                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1682                         break;
1683                 case IMAGEX_THREADS_OPTION:
1684                         num_threads = parse_num_threads(optarg);
1685                         if (num_threads == UINT_MAX)
1686                                 goto out_err;
1687                         break;
1688                 case IMAGEX_REBUILD_OPTION:
1689                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1690                         break;
1691                 case IMAGEX_UNIX_DATA_OPTION:
1692                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1693                         break;
1694                 case IMAGEX_SOURCE_LIST_OPTION:
1695                         source_list = true;
1696                         break;
1697                 case IMAGEX_NO_ACLS_OPTION:
1698                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1699                         break;
1700                 case IMAGEX_STRICT_ACLS_OPTION:
1701                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1702                         break;
1703                 case IMAGEX_RPFIX_OPTION:
1704                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
1705                         break;
1706                 case IMAGEX_NORPFIX_OPTION:
1707                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NORPFIX;
1708                         break;
1709                 case IMAGEX_PIPABLE_OPTION:
1710                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1711                         break;
1712                 case IMAGEX_NOT_PIPABLE_OPTION:
1713                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
1714                         break;
1715                 case IMAGEX_DELTA_FROM_OPTION:
1716                         if (cmd == CMD_CAPTURE) {
1717                                 imagex_error(T("--delta-from=IMAGE is only "
1718                                                "valid for append."));
1719                                 goto out_usage;
1720                         }
1721                         template_image_name_or_num = optarg;
1722                         break;
1723                 default:
1724                         goto out_usage;
1725                 }
1726         }
1727         argc -= optind;
1728         argv += optind;
1729
1730         if (argc < 2 || argc > 4)
1731                 goto out_usage;
1732
1733         source = argv[0];
1734         wimfile = argv[1];
1735
1736         if (!tstrcmp(wimfile, T("-"))) {
1737                 /* Writing captured WIM to standard output.  */
1738         #if 0
1739                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
1740                         imagex_error("Can't write a non-pipable WIM to "
1741                                      "standard output!  Specify --pipable\n"
1742                                      "       if you want to create a pipable WIM "
1743                                      "(but read the docs first).");
1744                         goto out_err;
1745                 }
1746         #else
1747                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1748         #endif
1749                 if (cmd == CMD_APPEND) {
1750                         imagex_error(T("Using standard output for append does "
1751                                        "not make sense."));
1752                         goto out_err;
1753                 }
1754                 wim_fd = STDOUT_FILENO;
1755                 wimfile = NULL;
1756                 imagex_info_file = stderr;
1757                 set_fd_to_binary_mode(wim_fd);
1758         }
1759
1760         if (argc >= 3) {
1761                 name = argv[2];
1762                 name_defaulted = false;
1763         } else {
1764                 /* Set default name to SOURCE argument, omitting any directory
1765                  * prefixes and trailing slashes.  This requires making a copy
1766                  * of @source.  Leave some free characters at the end in case we
1767                  * append a number to keep the name unique. */
1768                 size_t source_name_len;
1769
1770                 source_name_len = tstrlen(source);
1771                 source_copy = alloca((source_name_len + 1 + 25) * sizeof(tchar));
1772                 name = tbasename(tstrcpy(source_copy, source));
1773                 name_defaulted = true;
1774         }
1775         /* Image description defaults to NULL if not given. */
1776         if (argc >= 4)
1777                 desc = argv[3];
1778         else
1779                 desc = NULL;
1780
1781         if (source_list) {
1782                 /* Set up capture sources in source list mode */
1783                 if (source[0] == T('-') && source[1] == T('\0')) {
1784                         source_list_contents = stdin_get_text_contents(&source_list_nchars);
1785                 } else {
1786                         source_list_contents = file_get_text_contents(source,
1787                                                                       &source_list_nchars);
1788                 }
1789                 if (!source_list_contents)
1790                         goto out_err;
1791
1792                 capture_sources = parse_source_list(&source_list_contents,
1793                                                     source_list_nchars,
1794                                                     &num_sources);
1795                 if (!capture_sources) {
1796                         ret = -1;
1797                         goto out_free_source_list_contents;
1798                 }
1799                 capture_sources_malloced = true;
1800         } else {
1801                 /* Set up capture source in non-source-list mode (could be
1802                  * either "normal" mode or "NTFS mode"--- see the man page). */
1803                 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1804                 capture_sources[0].fs_source_path = source;
1805                 capture_sources[0].wim_target_path = NULL;
1806                 capture_sources[0].reserved = 0;
1807                 num_sources = 1;
1808                 capture_sources_malloced = false;
1809                 source_list_contents = NULL;
1810         }
1811
1812         if (config_file) {
1813                 size_t config_len;
1814
1815                 config_str = file_get_text_contents(config_file, &config_len);
1816                 if (!config_str) {
1817                         ret = -1;
1818                         goto out_free_capture_sources;
1819                 }
1820
1821                 config = alloca(sizeof(*config));
1822                 ret = parse_capture_config(&config_str, config_len, config);
1823                 if (ret)
1824                         goto out_free_config;
1825         } else {
1826                 config = NULL;
1827         }
1828
1829         if (cmd == CMD_APPEND)
1830                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
1831                                       imagex_progress_func);
1832         else
1833                 ret = wimlib_create_new_wim(compression_type, &wim);
1834         if (ret)
1835                 goto out_free_config;
1836
1837 #ifndef __WIN32__
1838         if (!source_list) {
1839                 struct stat stbuf;
1840
1841                 if (tstat(source, &stbuf) == 0) {
1842                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1843                                 imagex_printf(T("Capturing WIM image from NTFS "
1844                                           "filesystem on \"%"TS"\"\n"), source);
1845                                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1846                         }
1847                 } else {
1848                         if (errno != ENOENT) {
1849                                 imagex_error_with_errno(T("Failed to stat "
1850                                                           "\"%"TS"\""), source);
1851                                 ret = -1;
1852                                 goto out_wimlib_free;
1853                         }
1854                 }
1855         }
1856 #endif
1857
1858         if (cmd == CMD_APPEND && name_defaulted) {
1859                 /* If the user did not specify an image name, and the basename
1860                  * of the source already exists as an image name in the WIM
1861                  * file, append a suffix to make it unique. */
1862                 unsigned long conflict_idx;
1863                 tchar *name_end = tstrchr(name, T('\0'));
1864                 for (conflict_idx = 1;
1865                      wimlib_image_name_in_use(wim, name);
1866                      conflict_idx++)
1867                 {
1868                         tsprintf(name_end, T(" (%lu)"), conflict_idx);
1869                 }
1870         }
1871
1872         if (template_image_name_or_num) {
1873                 template_image = wimlib_resolve_image(wim, template_image_name_or_num);
1874                 if (template_image_name_or_num[0] == T('-')) {
1875                         tchar *tmp;
1876                         unsigned long n;
1877                         struct wimlib_wim_info info;
1878
1879                         wimlib_get_wim_info(wim, &info);
1880                         n = tstrtoul(template_image_name_or_num + 1, &tmp, 10);
1881                         if (n >= 1 && n <= info.image_count &&
1882                             *tmp == T('\0') &&
1883                             tmp != template_image_name_or_num + 1)
1884                         {
1885                                 template_image = info.image_count - (n - 1);
1886                         }
1887                 }
1888                 ret = verify_image_exists_and_is_single(template_image,
1889                                                         template_image_name_or_num,
1890                                                         wimfile);
1891                 if (ret)
1892                         goto out_wimlib_free;
1893         }
1894
1895         ret = wimlib_add_image_multisource(wim,
1896                                            capture_sources,
1897                                            num_sources,
1898                                            name,
1899                                            config,
1900                                            add_image_flags,
1901                                            imagex_progress_func);
1902         if (ret)
1903                 goto out_wimlib_free;
1904
1905         if (desc || flags_element || template_image_name_or_num) {
1906                 /* User provided <DESCRIPTION> or <FLAGS> element, or an image
1907                  * on which the added one is to be based has been specified with
1908                  * --delta-from=IMAGE.  Get the index of the image we just
1909                  *  added, then use it to call the appropriate functions.  */
1910                 struct wimlib_wim_info info;
1911
1912                 wimlib_get_wim_info(wim, &info);
1913
1914                 if (desc) {
1915                         ret = wimlib_set_image_descripton(wim,
1916                                                           info.image_count,
1917                                                           desc);
1918                         if (ret)
1919                                 goto out_wimlib_free;
1920                 }
1921
1922                 if (flags_element) {
1923                         ret = wimlib_set_image_flags(wim, info.image_count,
1924                                                      flags_element);
1925                         if (ret)
1926                                 goto out_wimlib_free;
1927                 }
1928
1929                 if (template_image_name_or_num) {
1930                         ret = wimlib_reference_template_image(wim,
1931                                                               info.image_count,
1932                                                               template_image,
1933                                                               0, NULL);
1934                         if (ret)
1935                                 goto out_wimlib_free;
1936                 }
1937         }
1938
1939         /* Write the new WIM or overwrite the existing WIM with the new image
1940          * appended.  */
1941         if (cmd == CMD_APPEND) {
1942                 ret = wimlib_overwrite(wim, write_flags, num_threads,
1943                                        imagex_progress_func);
1944         } else if (wimfile) {
1945                 ret = wimlib_write(wim, wimfile, WIMLIB_ALL_IMAGES,
1946                                    write_flags, num_threads,
1947                                    imagex_progress_func);
1948         } else {
1949                 ret = wimlib_write_to_fd(wim, wim_fd, WIMLIB_ALL_IMAGES,
1950                                          write_flags, num_threads,
1951                                          imagex_progress_func);
1952         }
1953 out_wimlib_free:
1954         wimlib_free(wim);
1955 out_free_config:
1956         if (config) {
1957                 free(config->exclusion_pats.pats);
1958                 free(config->exclusion_exception_pats.pats);
1959                 free(config_str);
1960         }
1961 out_free_capture_sources:
1962         if (capture_sources_malloced)
1963                 free(capture_sources);
1964 out_free_source_list_contents:
1965         free(source_list_contents);
1966 out:
1967         return ret;
1968
1969 out_usage:
1970         usage(cmd, stderr);
1971 out_err:
1972         ret = -1;
1973         goto out;
1974 }
1975
1976 /* Remove image(s) from a WIM. */
1977 static int
1978 imagex_delete(int argc, tchar **argv, int cmd)
1979 {
1980         int c;
1981         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
1982         int write_flags = 0;
1983         const tchar *wimfile;
1984         const tchar *image_num_or_name;
1985         WIMStruct *wim;
1986         int image;
1987         int ret;
1988
1989         for_opt(c, delete_options) {
1990                 switch (c) {
1991                 case IMAGEX_CHECK_OPTION:
1992                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1993                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1994                         break;
1995                 case IMAGEX_SOFT_OPTION:
1996                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1997                         break;
1998                 default:
1999                         goto out_usage;
2000                 }
2001         }
2002         argc -= optind;
2003         argv += optind;
2004
2005         if (argc != 2) {
2006                 if (argc < 1)
2007                         imagex_error(T("Must specify a WIM file"));
2008                 if (argc < 2)
2009                         imagex_error(T("Must specify an image"));
2010                 goto out_usage;
2011         }
2012         wimfile = argv[0];
2013         image_num_or_name = argv[1];
2014
2015         ret = wimlib_open_wim(wimfile, open_flags, &wim,
2016                               imagex_progress_func);
2017         if (ret)
2018                 goto out;
2019
2020         image = wimlib_resolve_image(wim, image_num_or_name);
2021
2022         ret = verify_image_exists(image, image_num_or_name, wimfile);
2023         if (ret)
2024                 goto out_wimlib_free;
2025
2026         ret = wimlib_delete_image(wim, image);
2027         if (ret) {
2028                 imagex_error(T("Failed to delete image from \"%"TS"\""),
2029                              wimfile);
2030                 goto out_wimlib_free;
2031         }
2032
2033         ret = wimlib_overwrite(wim, write_flags, 0, imagex_progress_func);
2034         if (ret) {
2035                 imagex_error(T("Failed to write the file \"%"TS"\" with image "
2036                                "deleted"), wimfile);
2037         }
2038 out_wimlib_free:
2039         wimlib_free(wim);
2040 out:
2041         return ret;
2042
2043 out_usage:
2044         usage(CMD_DELETE, stderr);
2045         ret = -1;
2046         goto out;
2047 }
2048
2049 static int
2050 print_full_path(const struct wimlib_dir_entry *wdentry, void *_ignore)
2051 {
2052         int ret = tprintf(T("%"TS"\n"), wdentry->full_path);
2053         return (ret >= 0) ? 0 : -1;
2054 }
2055
2056 /* Print the files contained in an image(s) in a WIM file. */
2057 static int
2058 imagex_dir(int argc, tchar **argv, int cmd)
2059 {
2060         const tchar *wimfile;
2061         WIMStruct *wim = NULL;
2062         int image;
2063         int ret;
2064         const tchar *path = T("");
2065         int c;
2066
2067         for_opt(c, dir_options) {
2068                 switch (c) {
2069                 case IMAGEX_PATH_OPTION:
2070                         path = optarg;
2071                         break;
2072                 default:
2073                         goto out_usage;
2074                 }
2075         }
2076         argc -= optind;
2077         argv += optind;
2078
2079         if (argc < 1) {
2080                 imagex_error(T("Must specify a WIM file"));
2081                 goto out_usage;
2082         }
2083         if (argc > 2) {
2084                 imagex_error(T("Too many arguments"));
2085                 goto out_usage;
2086         }
2087
2088         wimfile = argv[0];
2089         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &wim,
2090                               imagex_progress_func);
2091         if (ret)
2092                 goto out;
2093
2094         if (argc >= 2) {
2095                 image = wimlib_resolve_image(wim, argv[1]);
2096                 ret = verify_image_exists(image, argv[1], wimfile);
2097                 if (ret)
2098                         goto out_wimlib_free;
2099         } else {
2100                 /* No image specified; default to image 1, but only if the WIM
2101                  * contains exactly one image.  */
2102
2103                 struct wimlib_wim_info info;
2104
2105                 wimlib_get_wim_info(wim, &info);
2106                 if (info.image_count != 1) {
2107                         imagex_error(T("\"%"TS"\" contains %d images; Please "
2108                                        "select one (or all)."),
2109                                      wimfile, info.image_count);
2110                         wimlib_free(wim);
2111                         goto out_usage;
2112                 }
2113                 image = 1;
2114         }
2115
2116         ret = wimlib_iterate_dir_tree(wim, image, path,
2117                                       WIMLIB_ITERATE_DIR_TREE_FLAG_RECURSIVE,
2118                                       print_full_path, NULL);
2119 out_wimlib_free:
2120         wimlib_free(wim);
2121 out:
2122         return ret;
2123
2124 out_usage:
2125         usage(CMD_DIR, stderr);
2126         ret = -1;
2127         goto out;
2128 }
2129
2130 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
2131  * WIM file. */
2132 static int
2133 imagex_export(int argc, tchar **argv, int cmd)
2134 {
2135         int c;
2136         int open_flags = 0;
2137         int export_flags = 0;
2138         int write_flags = 0;
2139         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
2140         const tchar *src_wimfile;
2141         const tchar *src_image_num_or_name;
2142         const tchar *dest_wimfile;
2143         int dest_wim_fd;
2144         const tchar *dest_name;
2145         const tchar *dest_desc;
2146         WIMStruct *src_wim;
2147         WIMStruct *dest_wim;
2148         int ret;
2149         int image;
2150         struct stat stbuf;
2151         bool wim_is_new;
2152         const tchar *swm_glob = NULL;
2153         WIMStruct **additional_swms;
2154         unsigned num_additional_swms;
2155         unsigned num_threads = 0;
2156
2157         for_opt(c, export_options) {
2158                 switch (c) {
2159                 case IMAGEX_BOOT_OPTION:
2160                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
2161                         break;
2162                 case IMAGEX_CHECK_OPTION:
2163                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2164                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2165                         break;
2166                 case IMAGEX_NOCHECK_OPTION:
2167                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
2168                         break;
2169                 case IMAGEX_COMPRESS_OPTION:
2170                         compression_type = get_compression_type(optarg);
2171                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
2172                                 goto out_err;
2173                         break;
2174                 case IMAGEX_REF_OPTION:
2175                         swm_glob = optarg;
2176                         break;
2177                 case IMAGEX_THREADS_OPTION:
2178                         num_threads = parse_num_threads(optarg);
2179                         if (num_threads == UINT_MAX)
2180                                 goto out_err;
2181                         break;
2182                 case IMAGEX_REBUILD_OPTION:
2183                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
2184                         break;
2185                 case IMAGEX_PIPABLE_OPTION:
2186                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2187                         break;
2188                 case IMAGEX_NOT_PIPABLE_OPTION:
2189                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
2190                         break;
2191                 default:
2192                         goto out_usage;
2193                 }
2194         }
2195         argc -= optind;
2196         argv += optind;
2197         if (argc < 3 || argc > 5)
2198                 goto out_usage;
2199         src_wimfile           = argv[0];
2200         src_image_num_or_name = argv[1];
2201         dest_wimfile          = argv[2];
2202         dest_name             = (argc >= 4) ? argv[3] : NULL;
2203         dest_desc             = (argc >= 5) ? argv[4] : NULL;
2204         ret = wimlib_open_wim(src_wimfile,
2205                               open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_wim,
2206                               imagex_progress_func);
2207         if (ret)
2208                 goto out;
2209
2210         /* Determine if the destination is an existing file or not.  If so, we
2211          * try to append the exported image(s) to it; otherwise, we create a new
2212          * WIM containing the exported image(s).  Furthermore, determine if we
2213          * need to write a pipable WIM directly to standard output.  */
2214
2215         if (tstrcmp(dest_wimfile, T("-")) == 0) {
2216         #if 0
2217                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2218                         imagex_error("Can't write a non-pipable WIM to "
2219                                      "standard output!  Specify --pipable\n"
2220                                      "       if you want to create a pipable WIM "
2221                                      "(but read the docs first).");
2222                         ret = -1;
2223                         goto out_free_src_wim;
2224                 }
2225         #else
2226                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2227         #endif
2228                 dest_wimfile = NULL;
2229                 dest_wim_fd = STDOUT_FILENO;
2230                 imagex_info_file = stderr;
2231                 set_fd_to_binary_mode(dest_wim_fd);
2232         }
2233         errno = ENOENT;
2234         if (dest_wimfile != NULL && tstat(dest_wimfile, &stbuf) == 0) {
2235                 wim_is_new = false;
2236                 /* Destination file exists. */
2237
2238                 if (!S_ISREG(stbuf.st_mode)) {
2239                         imagex_error(T("\"%"TS"\" is not a regular file"),
2240                                      dest_wimfile);
2241                         ret = -1;
2242                         goto out_free_src_wim;
2243                 }
2244                 ret = wimlib_open_wim(dest_wimfile, open_flags | WIMLIB_OPEN_FLAG_WRITE_ACCESS,
2245                                       &dest_wim, imagex_progress_func);
2246                 if (ret)
2247                         goto out_free_src_wim;
2248
2249                 if (compression_type != WIMLIB_COMPRESSION_TYPE_INVALID) {
2250                         /* The user specified a compression type, but we're
2251                          * exporting to an existing WIM.  Make sure the
2252                          * specified compression type is the same as the
2253                          * compression type of the existing destination WIM. */
2254                         struct wimlib_wim_info dest_info;
2255
2256                         wimlib_get_wim_info(dest_wim, &dest_info);
2257                         if (compression_type != dest_info.compression_type) {
2258                                 imagex_error(T("Cannot specify a compression type that is "
2259                                                "not the same as that used in the "
2260                                                "destination WIM"));
2261                                 ret = -1;
2262                                 goto out_free_dest_wim;
2263                         }
2264                 }
2265         } else {
2266                 wim_is_new = true;
2267
2268                 if (errno != ENOENT) {
2269                         imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
2270                                                 dest_wimfile);
2271                         ret = -1;
2272                         goto out_free_src_wim;
2273                 }
2274
2275                 /* dest_wimfile is not an existing file, so create a new WIM. */
2276
2277                 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID) {
2278                         /* The user did not specify a compression type; default
2279                          * to that of the source WIM.  */
2280
2281                         struct wimlib_wim_info src_info;
2282
2283                         wimlib_get_wim_info(src_wim, &src_info);
2284                         compression_type = src_info.compression_type;
2285                 }
2286                 ret = wimlib_create_new_wim(compression_type, &dest_wim);
2287                 if (ret)
2288                         goto out_free_src_wim;
2289         }
2290
2291         image = wimlib_resolve_image(src_wim, src_image_num_or_name);
2292         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
2293         if (ret)
2294                 goto out_free_dest_wim;
2295
2296         if (swm_glob) {
2297                 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
2298                                           &additional_swms,
2299                                           &num_additional_swms);
2300                 if (ret)
2301                         goto out_free_dest_wim;
2302         } else {
2303                 additional_swms = NULL;
2304                 num_additional_swms = 0;
2305         }
2306
2307         ret = wimlib_export_image(src_wim, image, dest_wim, dest_name,
2308                                   dest_desc, export_flags, additional_swms,
2309                                   num_additional_swms, imagex_progress_func);
2310         if (ret)
2311                 goto out_free_swms;
2312
2313         if (!wim_is_new)
2314                 ret = wimlib_overwrite(dest_wim, write_flags, num_threads,
2315                                        imagex_progress_func);
2316         else if (dest_wimfile)
2317                 ret = wimlib_write(dest_wim, dest_wimfile, WIMLIB_ALL_IMAGES,
2318                                    write_flags, num_threads,
2319                                    imagex_progress_func);
2320         else
2321                 ret = wimlib_write_to_fd(dest_wim, dest_wim_fd,
2322                                          WIMLIB_ALL_IMAGES, write_flags,
2323                                          num_threads, imagex_progress_func);
2324         if (ret)
2325                 imagex_error(T("Export failed."));
2326 out_free_swms:
2327         for (unsigned i = 0; i < num_additional_swms; i++)
2328                 wimlib_free(additional_swms[i]);
2329         free(additional_swms);
2330 out_free_dest_wim:
2331         wimlib_free(dest_wim);
2332 out_free_src_wim:
2333         wimlib_free(src_wim);
2334 out:
2335         return ret;
2336
2337 out_usage:
2338         usage(CMD_EXPORT, stderr);
2339 out_err:
2340         ret = -1;
2341         goto out;
2342 }
2343
2344 static bool
2345 is_root_wim_path(const tchar *path)
2346 {
2347         const tchar *p;
2348         for (p = path; *p; p++)
2349                 if (*p != T('\\') && *p != T('/'))
2350                         return false;
2351         return true;
2352 }
2353
2354 static void
2355 free_extract_commands(struct wimlib_extract_command *cmds, size_t num_cmds,
2356                       const tchar *dest_dir)
2357 {
2358         for (size_t i = 0; i < num_cmds; i++)
2359                 if (cmds[i].fs_dest_path != dest_dir)
2360                         free(cmds[i].fs_dest_path);
2361         free(cmds);
2362 }
2363
2364 static struct wimlib_extract_command *
2365 prepare_extract_commands(tchar **paths, unsigned num_paths,
2366                          int extract_flags, tchar *dest_dir,
2367                          size_t *num_cmds_ret)
2368 {
2369         struct wimlib_extract_command *cmds;
2370         size_t num_cmds;
2371         tchar *emptystr = T("");
2372
2373         if (num_paths == 0) {
2374                 num_paths = 1;
2375                 paths = &emptystr;
2376         }
2377         num_cmds = num_paths;
2378         cmds = calloc(num_cmds, sizeof(cmds[0]));
2379         if (!cmds) {
2380                 imagex_error(T("Out of memory!"));
2381                 return NULL;
2382         }
2383
2384         for (size_t i = 0; i < num_cmds; i++) {
2385                 cmds[i].extract_flags = extract_flags;
2386                 cmds[i].wim_source_path = paths[i];
2387                 if (is_root_wim_path(paths[i])) {
2388                         cmds[i].fs_dest_path = dest_dir;
2389                 } else {
2390                         size_t len = tstrlen(dest_dir) + 1 + tstrlen(paths[i]);
2391                         cmds[i].fs_dest_path = malloc((len + 1) * sizeof(tchar));
2392                         if (!cmds[i].fs_dest_path) {
2393                                 free_extract_commands(cmds, num_cmds, dest_dir);
2394                                 return NULL;
2395                         }
2396                         tsprintf(cmds[i].fs_dest_path,
2397                                  T("%"TS""OS_PREFERRED_PATH_SEPARATOR_STRING"%"TS),
2398                                  dest_dir, tbasename(paths[i]));
2399                 }
2400         }
2401         *num_cmds_ret = num_cmds;
2402         return cmds;
2403 }
2404
2405 /* Extract files or directories from a WIM image */
2406 static int
2407 imagex_extract(int argc, tchar **argv, int cmd)
2408 {
2409         int c;
2410         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2411         int image;
2412         WIMStruct *wim;
2413         int ret;
2414         const tchar *wimfile;
2415         const tchar *image_num_or_name;
2416         tchar *dest_dir = T(".");
2417         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL | WIMLIB_EXTRACT_FLAG_NORPFIX;
2418
2419         const tchar *swm_glob = NULL;
2420         WIMStruct **additional_swms;
2421         unsigned num_additional_swms;
2422
2423         struct wimlib_extract_command *cmds;
2424         size_t num_cmds;
2425
2426         for_opt(c, extract_options) {
2427                 switch (c) {
2428                 case IMAGEX_CHECK_OPTION:
2429                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2430                         break;
2431                 case IMAGEX_VERBOSE_OPTION:
2432                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
2433                         break;
2434                 case IMAGEX_REF_OPTION:
2435                         swm_glob = optarg;
2436                         break;
2437                 case IMAGEX_UNIX_DATA_OPTION:
2438                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
2439                         break;
2440                 case IMAGEX_NO_ACLS_OPTION:
2441                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
2442                         break;
2443                 case IMAGEX_STRICT_ACLS_OPTION:
2444                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
2445                         break;
2446                 case IMAGEX_DEST_DIR_OPTION:
2447                         dest_dir = optarg;
2448                         break;
2449                 case IMAGEX_TO_STDOUT_OPTION:
2450                         extract_flags |= WIMLIB_EXTRACT_FLAG_TO_STDOUT;
2451                         imagex_info_file = stderr;
2452                         imagex_be_quiet = true;
2453                         break;
2454                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
2455                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
2456                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
2457                         break;
2458                 default:
2459                         goto out_usage;
2460                 }
2461         }
2462         argc -= optind;
2463         argv += optind;
2464
2465         if (argc < 2)
2466                 goto out_usage;
2467
2468         wimfile = argv[0];
2469         image_num_or_name = argv[1];
2470
2471         argc -= 2;
2472         argv += 2;
2473
2474         cmds = prepare_extract_commands(argv, argc, extract_flags, dest_dir,
2475                                         &num_cmds);
2476         if (!cmds)
2477                 goto out_err;
2478
2479         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2480         if (ret)
2481                 goto out_free_cmds;
2482
2483         image = wimlib_resolve_image(wim, image_num_or_name);
2484         ret = verify_image_exists_and_is_single(image,
2485                                                 image_num_or_name,
2486                                                 wimfile);
2487         if (ret)
2488                 goto out_wimlib_free;
2489
2490         if (swm_glob) {
2491                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2492                                           &additional_swms,
2493                                           &num_additional_swms);
2494                 if (ret)
2495                         goto out_wimlib_free;
2496         } else {
2497                 additional_swms = NULL;
2498                 num_additional_swms = 0;
2499         }
2500
2501         ret = wimlib_extract_files(wim, image, cmds, num_cmds, 0,
2502                                    additional_swms, num_additional_swms,
2503                                    imagex_progress_func);
2504         if (ret == 0) {
2505                 if (!imagex_be_quiet)
2506                         imagex_printf(T("Done extracting files.\n"));
2507         } else if (ret == WIMLIB_ERR_PATH_DOES_NOT_EXIST) {
2508                 tfprintf(stderr, T("Note: You can use `%"TS"' to see what "
2509                                    "files and directories\n"
2510                                    "      are in the WIM image.\n"),
2511                                 get_cmd_string(CMD_INFO, false));
2512         }
2513         for (unsigned i = 0; i < num_additional_swms; i++)
2514                 wimlib_free(additional_swms[i]);
2515         free(additional_swms);
2516 out_wimlib_free:
2517         wimlib_free(wim);
2518 out_free_cmds:
2519         free_extract_commands(cmds, num_cmds, dest_dir);
2520 out:
2521         return ret;
2522
2523 out_usage:
2524         usage(CMD_EXTRACT, stderr);
2525 out_err:
2526         ret = -1;
2527         goto out;
2528 }
2529
2530 static void print_byte_field(const uint8_t field[], size_t len)
2531 {
2532         while (len--)
2533                 tprintf(T("%02hhx"), *field++);
2534 }
2535
2536 static void
2537 print_wim_information(const tchar *wimfile, const struct wimlib_wim_info *info)
2538 {
2539         tputs(T("WIM Information:"));
2540         tputs(T("----------------"));
2541         tprintf(T("Path:           %"TS"\n"), wimfile);
2542         tprintf(T("GUID:           0x"));
2543         print_byte_field(info->guid, sizeof(info->guid));
2544         tputchar(T('\n'));
2545         tprintf(T("Image Count:    %d\n"), info->image_count);
2546         tprintf(T("Compression:    %"TS"\n"),
2547                 wimlib_get_compression_type_string(info->compression_type));
2548         tprintf(T("Part Number:    %d/%d\n"), info->part_number, info->total_parts);
2549         tprintf(T("Boot Index:     %d\n"), info->boot_index);
2550         tprintf(T("Size:           %"PRIu64" bytes\n"), info->total_bytes);
2551         tprintf(T("Integrity Info: %"TS"\n"),
2552                 info->has_integrity_table ? T("yes") : T("no"));
2553         tprintf(T("Relative path junction: %"TS"\n"),
2554                 info->has_rpfix ? T("yes") : T("no"));
2555         tprintf(T("Pipable:        %"TS"\n"),
2556                 info->pipable ? T("yes") : T("no"));
2557         tputchar(T('\n'));
2558 }
2559
2560 static int
2561 print_resource(const struct wimlib_resource_entry *resource,
2562                void *_ignore)
2563 {
2564
2565         tprintf(T("Uncompressed size   = %"PRIu64" bytes\n"),
2566                 resource->uncompressed_size);
2567
2568         tprintf(T("Compressed size     = %"PRIu64" bytes\n"),
2569                 resource->compressed_size);
2570
2571         tprintf(T("Offset              = %"PRIu64" bytes\n"),
2572                 resource->offset);
2573
2574
2575         tprintf(T("Part Number         = %u\n"), resource->part_number);
2576         tprintf(T("Reference Count     = %u\n"), resource->reference_count);
2577
2578         tprintf(T("Hash                = 0x"));
2579         print_byte_field(resource->sha1_hash, sizeof(resource->sha1_hash));
2580         tputchar(T('\n'));
2581
2582         tprintf(T("Flags               = "));
2583         if (resource->is_compressed)
2584                 tprintf(T("WIM_RESHDR_FLAG_COMPRESSED  "));
2585         if (resource->is_metadata)
2586                 tprintf(T("WIM_RESHDR_FLAG_METADATA  "));
2587         if (resource->is_free)
2588                 tprintf(T("WIM_RESHDR_FLAG_FREE  "));
2589         if (resource->is_spanned)
2590                 tprintf(T("WIM_RESHDR_FLAG_SPANNED  "));
2591         tputchar(T('\n'));
2592         tputchar(T('\n'));
2593         return 0;
2594 }
2595
2596 static void
2597 print_lookup_table(WIMStruct *wim)
2598 {
2599         wimlib_iterate_lookup_table(wim, 0, print_resource, NULL);
2600 }
2601
2602 /* Prints information about a WIM file; also can mark an image as bootable,
2603  * change the name of an image, or change the description of an image. */
2604 static int
2605 imagex_info(int argc, tchar **argv, int cmd)
2606 {
2607         int c;
2608         bool boot         = false;
2609         bool check        = false;
2610         bool nocheck      = false;
2611         bool header       = false;
2612         bool lookup_table = false;
2613         bool xml          = false;
2614         bool metadata     = false;
2615         bool short_header = true;
2616         const tchar *xml_out_file = NULL;
2617         const tchar *wimfile;
2618         const tchar *image_num_or_name;
2619         const tchar *new_name;
2620         const tchar *new_desc;
2621         WIMStruct *wim;
2622         int image;
2623         int ret;
2624         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2625         struct wimlib_wim_info info;
2626
2627         for_opt(c, info_options) {
2628                 switch (c) {
2629                 case IMAGEX_BOOT_OPTION:
2630                         boot = true;
2631                         break;
2632                 case IMAGEX_CHECK_OPTION:
2633                         check = true;
2634                         break;
2635                 case IMAGEX_NOCHECK_OPTION:
2636                         nocheck = true;
2637                         break;
2638                 case IMAGEX_HEADER_OPTION:
2639                         header = true;
2640                         short_header = false;
2641                         break;
2642                 case IMAGEX_LOOKUP_TABLE_OPTION:
2643                         lookup_table = true;
2644                         short_header = false;
2645                         break;
2646                 case IMAGEX_XML_OPTION:
2647                         xml = true;
2648                         short_header = false;
2649                         break;
2650                 case IMAGEX_EXTRACT_XML_OPTION:
2651                         xml_out_file = optarg;
2652                         short_header = false;
2653                         break;
2654                 case IMAGEX_METADATA_OPTION:
2655                         metadata = true;
2656                         short_header = false;
2657                         break;
2658                 default:
2659                         goto out_usage;
2660                 }
2661         }
2662
2663         argc -= optind;
2664         argv += optind;
2665         if (argc < 1 || argc > 4)
2666                 goto out_usage;
2667
2668         wimfile           = argv[0];
2669         image_num_or_name = (argc >= 2) ? argv[1] : T("all");
2670         new_name          = (argc >= 3) ? argv[2] : NULL;
2671         new_desc          = (argc >= 4) ? argv[3] : NULL;
2672
2673         if (check && nocheck) {
2674                 imagex_error(T("Can't specify both --check and --nocheck"));
2675                 goto out_err;
2676         }
2677
2678         if (check)
2679                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2680
2681         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2682         if (ret)
2683                 goto out;
2684
2685         wimlib_get_wim_info(wim, &info);
2686
2687         image = wimlib_resolve_image(wim, image_num_or_name);
2688         ret = WIMLIB_ERR_INVALID_IMAGE;
2689         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
2690                 imagex_error(T("The image \"%"TS"\" does not exist in \"%"TS"\""),
2691                              image_num_or_name, wimfile);
2692                 if (boot) {
2693                         imagex_error(T("If you would like to set the boot "
2694                                        "index to 0, specify image \"0\" with "
2695                                        "the --boot flag."));
2696                 }
2697                 goto out_wimlib_free;
2698         }
2699
2700         if (boot && info.image_count == 0) {
2701                 imagex_error(T("--boot is meaningless on a WIM with no images"));
2702                 goto out_wimlib_free;
2703         }
2704
2705         if (image == WIMLIB_ALL_IMAGES && info.image_count > 1) {
2706                 if (boot) {
2707                         imagex_error(T("Cannot specify the --boot flag "
2708                                        "without specifying a specific "
2709                                        "image in a multi-image WIM"));
2710                         goto out_wimlib_free;
2711                 }
2712                 if (new_name) {
2713                         imagex_error(T("Cannot specify the NEW_NAME "
2714                                        "without specifying a specific "
2715                                        "image in a multi-image WIM"));
2716                         goto out_wimlib_free;
2717                 }
2718         }
2719
2720         /* Operations that print information are separated from operations that
2721          * recreate the WIM file. */
2722         if (!new_name && !boot) {
2723
2724                 /* Read-only operations */
2725
2726                 if (image == WIMLIB_NO_IMAGE) {
2727                         imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\""),
2728                                      image_num_or_name, wimfile);
2729                         goto out_wimlib_free;
2730                 }
2731
2732                 if (image == WIMLIB_ALL_IMAGES && short_header)
2733                         print_wim_information(wimfile, &info);
2734
2735                 if (header)
2736                         wimlib_print_header(wim);
2737
2738                 if (lookup_table) {
2739                         if (info.total_parts != 1) {
2740                                 tfprintf(stderr, T("Warning: Only showing the lookup table "
2741                                                    "for part %d of a %d-part WIM.\n"),
2742                                          info.part_number, info.total_parts);
2743                         }
2744                         print_lookup_table(wim);
2745                 }
2746
2747                 if (xml) {
2748                         ret = wimlib_extract_xml_data(wim, stdout);
2749                         if (ret)
2750                                 goto out_wimlib_free;
2751                 }
2752
2753                 if (xml_out_file) {
2754                         FILE *fp;
2755
2756                         fp = tfopen(xml_out_file, T("wb"));
2757                         if (!fp) {
2758                                 imagex_error_with_errno(T("Failed to open the "
2759                                                           "file \"%"TS"\" for "
2760                                                           "writing"),
2761                                                         xml_out_file);
2762                                 ret = -1;
2763                                 goto out_wimlib_free;
2764                         }
2765                         ret = wimlib_extract_xml_data(wim, fp);
2766                         if (fclose(fp)) {
2767                                 imagex_error(T("Failed to close the file "
2768                                                "\"%"TS"\""),
2769                                              xml_out_file);
2770                                 ret = -1;
2771                         }
2772                         if (ret)
2773                                 goto out_wimlib_free;
2774                 }
2775
2776                 if (short_header)
2777                         wimlib_print_available_images(wim, image);
2778
2779                 if (metadata) {
2780                         ret = wimlib_print_metadata(wim, image);
2781                         if (ret)
2782                                 goto out_wimlib_free;
2783                 }
2784                 ret = 0;
2785         } else {
2786
2787                 /* Modification operations */
2788
2789                 if (image == WIMLIB_ALL_IMAGES)
2790                         image = 1;
2791
2792                 if (image == WIMLIB_NO_IMAGE && new_name) {
2793                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2794                                        "when using image 0"), new_name);
2795                         ret = -1;
2796                         goto out_wimlib_free;
2797                 }
2798
2799                 if (boot) {
2800                         if (image == info.boot_index) {
2801                                 imagex_printf(T("Image %d is already marked as "
2802                                           "bootable.\n"), image);
2803                                 boot = false;
2804                         } else {
2805                                 imagex_printf(T("Marking image %d as bootable.\n"),
2806                                         image);
2807                                 info.boot_index = image;
2808                                 ret = wimlib_set_wim_info(wim, &info,
2809                                                           WIMLIB_CHANGE_BOOT_INDEX);
2810                                 if (ret)
2811                                         goto out_wimlib_free;
2812                         }
2813                 }
2814                 if (new_name) {
2815                         if (!tstrcmp(wimlib_get_image_name(wim, image), new_name))
2816                         {
2817                                 imagex_printf(T("Image %d is already named \"%"TS"\".\n"),
2818                                         image, new_name);
2819                                 new_name = NULL;
2820                         } else {
2821                                 imagex_printf(T("Changing the name of image %d to "
2822                                           "\"%"TS"\".\n"), image, new_name);
2823                                 ret = wimlib_set_image_name(wim, image, new_name);
2824                                 if (ret)
2825                                         goto out_wimlib_free;
2826                         }
2827                 }
2828                 if (new_desc) {
2829                         const tchar *old_desc;
2830                         old_desc = wimlib_get_image_description(wim, image);
2831                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
2832                                 imagex_printf(T("The description of image %d is already "
2833                                           "\"%"TS"\".\n"), image, new_desc);
2834                                 new_desc = NULL;
2835                         } else {
2836                                 imagex_printf(T("Changing the description of image %d "
2837                                           "to \"%"TS"\".\n"), image, new_desc);
2838                                 ret = wimlib_set_image_descripton(wim, image,
2839                                                                   new_desc);
2840                                 if (ret)
2841                                         goto out_wimlib_free;
2842                         }
2843                 }
2844
2845                 /* Only call wimlib_overwrite() if something actually needs to
2846                  * be changed.  */
2847                 if (boot || new_name || new_desc ||
2848                     (check && !info.has_integrity_table) ||
2849                     (nocheck && info.has_integrity_table))
2850                 {
2851                         int write_flags = 0;
2852
2853                         if (check)
2854                                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2855                         if (nocheck)
2856                                 write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
2857                         ret = wimlib_overwrite(wim, write_flags, 1,
2858                                                imagex_progress_func);
2859                 } else {
2860                         imagex_printf(T("The file \"%"TS"\" was not modified "
2861                                         "because nothing needed to be done.\n"),
2862                                       wimfile);
2863                         ret = 0;
2864                 }
2865         }
2866 out_wimlib_free:
2867         wimlib_free(wim);
2868 out:
2869         return ret;
2870
2871 out_usage:
2872         usage(CMD_INFO, stderr);
2873 out_err:
2874         ret = -1;
2875         goto out;
2876 }
2877
2878 /* Join split WIMs into one part WIM */
2879 static int
2880 imagex_join(int argc, tchar **argv, int cmd)
2881 {
2882         int c;
2883         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2884         int wim_write_flags = 0;
2885         const tchar *output_path;
2886         int ret;
2887
2888         for_opt(c, join_options) {
2889                 switch (c) {
2890                 case IMAGEX_CHECK_OPTION:
2891                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2892                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2893                         break;
2894                 default:
2895                         goto out_usage;
2896                 }
2897         }
2898         argc -= optind;
2899         argv += optind;
2900
2901         if (argc < 2) {
2902                 imagex_error(T("Must specify one or more split WIM (.swm) "
2903                                "parts to join"));
2904                 goto out_usage;
2905         }
2906         output_path = argv[0];
2907         ret = wimlib_join((const tchar * const *)++argv,
2908                           --argc,
2909                           output_path,
2910                           swm_open_flags,
2911                           wim_write_flags,
2912                           imagex_progress_func);
2913 out:
2914         return ret;
2915
2916 out_usage:
2917         usage(CMD_JOIN, stderr);
2918         ret = -1;
2919         goto out;
2920 }
2921
2922 #if WIM_MOUNTING_SUPPORTED
2923
2924 /* Mounts a WIM image.  */
2925 static int
2926 imagex_mount_rw_or_ro(int argc, tchar **argv, int cmd)
2927 {
2928         int c;
2929         int mount_flags = 0;
2930         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2931         const tchar *swm_glob = NULL;
2932         const tchar *staging_dir = NULL;
2933         const tchar *wimfile;
2934         const tchar *dir;
2935         WIMStruct *wim;
2936         int image;
2937         int ret;
2938         WIMStruct **additional_swms;
2939         unsigned num_additional_swms;
2940
2941         if (cmd == CMD_MOUNTRW) {
2942                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
2943                 open_flags |= WIMLIB_OPEN_FLAG_WRITE_ACCESS;
2944         }
2945
2946         for_opt(c, mount_options) {
2947                 switch (c) {
2948                 case IMAGEX_ALLOW_OTHER_OPTION:
2949                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
2950                         break;
2951                 case IMAGEX_CHECK_OPTION:
2952                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2953                         break;
2954                 case IMAGEX_DEBUG_OPTION:
2955                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
2956                         break;
2957                 case IMAGEX_STREAMS_INTERFACE_OPTION:
2958                         if (!tstrcasecmp(optarg, T("none")))
2959                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
2960                         else if (!tstrcasecmp(optarg, T("xattr")))
2961                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2962                         else if (!tstrcasecmp(optarg, T("windows")))
2963                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
2964                         else {
2965                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
2966                                              optarg);
2967                                 goto out_usage;
2968                         }
2969                         break;
2970                 case IMAGEX_REF_OPTION:
2971                         swm_glob = optarg;
2972                         break;
2973                 case IMAGEX_STAGING_DIR_OPTION:
2974                         staging_dir = optarg;
2975                         break;
2976                 case IMAGEX_UNIX_DATA_OPTION:
2977                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
2978                         break;
2979                 default:
2980                         goto out_usage;
2981                 }
2982         }
2983         argc -= optind;
2984         argv += optind;
2985         if (argc != 2 && argc != 3)
2986                 goto out_usage;
2987
2988         wimfile = argv[0];
2989
2990         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2991         if (ret)
2992                 goto out;
2993
2994         if (argc >= 3) {
2995                 /* Image explicitly specified.  */
2996                 image = wimlib_resolve_image(wim, argv[1]);
2997                 dir = argv[2];
2998                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2999                 if (ret)
3000                         goto out_free_wim;
3001         } else {
3002                 /* No image specified; default to image 1, but only if the WIM
3003                  * contains exactly one image.  */
3004                 struct wimlib_wim_info info;
3005
3006                 wimlib_get_wim_info(wim, &info);
3007                 if (info.image_count != 1) {
3008                         imagex_error(T("\"%"TS"\" contains %d images; Please "
3009                                        "select one."), wimfile, info.image_count);
3010                         wimlib_free(wim);
3011                         goto out_usage;
3012                 }
3013                 image = 1;
3014                 dir = argv[1];
3015         }
3016
3017         if (swm_glob) {
3018                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
3019                                           &additional_swms,
3020                                           &num_additional_swms);
3021                 if (ret)
3022                         goto out_free_wim;
3023         } else {
3024                 additional_swms = NULL;
3025                 num_additional_swms = 0;
3026         }
3027
3028         ret = wimlib_mount_image(wim, image, dir, mount_flags, additional_swms,
3029                                  num_additional_swms, staging_dir);
3030         if (ret) {
3031                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
3032                                "on \"%"TS"\""),
3033                              image, wimfile, dir);
3034         }
3035         for (unsigned i = 0; i < num_additional_swms; i++)
3036                 wimlib_free(additional_swms[i]);
3037         free(additional_swms);
3038 out_free_wim:
3039         wimlib_free(wim);
3040 out:
3041         return ret;
3042
3043 out_usage:
3044         usage(cmd, stderr);
3045         ret = -1;
3046         goto out;
3047 }
3048 #endif /* WIM_MOUNTING_SUPPORTED */
3049
3050 /* Rebuild a WIM file */
3051 static int
3052 imagex_optimize(int argc, tchar **argv, int cmd)
3053 {
3054         int c;
3055         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3056         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
3057         int ret;
3058         WIMStruct *wim;
3059         const tchar *wimfile;
3060         off_t old_size;
3061         off_t new_size;
3062         unsigned num_threads = 0;
3063
3064         for_opt(c, optimize_options) {
3065                 switch (c) {
3066                 case IMAGEX_CHECK_OPTION:
3067                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3068                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3069                         break;
3070                 case IMAGEX_NOCHECK_OPTION:
3071                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3072                         break;
3073                 case IMAGEX_RECOMPRESS_OPTION:
3074                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3075                         break;
3076                 case IMAGEX_THREADS_OPTION:
3077                         num_threads = parse_num_threads(optarg);
3078                         if (num_threads == UINT_MAX)
3079                                 goto out_err;
3080                         break;
3081                 case IMAGEX_PIPABLE_OPTION:
3082                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
3083                         break;
3084                 case IMAGEX_NOT_PIPABLE_OPTION:
3085                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
3086                         break;
3087                 default:
3088                         goto out_usage;
3089                 }
3090         }
3091         argc -= optind;
3092         argv += optind;
3093
3094         if (argc != 1)
3095                 goto out_usage;
3096
3097         wimfile = argv[0];
3098
3099         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3100         if (ret)
3101                 goto out;
3102
3103         old_size = file_get_size(wimfile);
3104         tprintf(T("\"%"TS"\" original size: "), wimfile);
3105         if (old_size == -1)
3106                 tputs(T("Unknown"));
3107         else
3108                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
3109
3110         ret = wimlib_overwrite(wim, write_flags, num_threads,
3111                                imagex_progress_func);
3112         if (ret) {
3113                 imagex_error(T("Optimization of \"%"TS"\" failed."), wimfile);
3114                 goto out_wimlib_free;
3115         }
3116
3117         new_size = file_get_size(wimfile);
3118         tprintf(T("\"%"TS"\" optimized size: "), wimfile);
3119         if (new_size == -1)
3120                 tputs(T("Unknown"));
3121         else
3122                 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
3123
3124         tfputs(T("Space saved: "), stdout);
3125         if (new_size != -1 && old_size != -1) {
3126                 tprintf(T("%lld KiB\n"),
3127                        ((long long)old_size - (long long)new_size) >> 10);
3128         } else {
3129                 tputs(T("Unknown"));
3130         }
3131         ret = 0;
3132 out_wimlib_free:
3133         wimlib_free(wim);
3134 out:
3135         return ret;
3136
3137 out_usage:
3138         usage(CMD_OPTIMIZE, stderr);
3139 out_err:
3140         ret = -1;
3141         goto out;
3142 }
3143
3144 /* Split a WIM into a spanned set */
3145 static int
3146 imagex_split(int argc, tchar **argv, int cmd)
3147 {
3148         int c;
3149         int open_flags = 0;
3150         int write_flags = 0;
3151         unsigned long part_size;
3152         tchar *tmp;
3153         int ret;
3154         WIMStruct *wim;
3155
3156         for_opt(c, split_options) {
3157                 switch (c) {
3158                 case IMAGEX_CHECK_OPTION:
3159                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3160                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3161                         break;
3162                 default:
3163                         goto out_usage;
3164                 }
3165         }
3166         argc -= optind;
3167         argv += optind;
3168
3169         if (argc != 3)
3170                 goto out_usage;
3171
3172         part_size = tstrtod(argv[2], &tmp) * (1 << 20);
3173         if (tmp == argv[2] || *tmp) {
3174                 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
3175                 imagex_error(T("The part size must be an integer or "
3176                                "floating-point number of megabytes."));
3177                 goto out_err;
3178         }
3179         ret = wimlib_open_wim(argv[0], open_flags, &wim, imagex_progress_func);
3180         if (ret)
3181                 goto out;
3182
3183         ret = wimlib_split(wim, argv[1], part_size, write_flags, imagex_progress_func);
3184         wimlib_free(wim);
3185 out:
3186         return ret;
3187
3188 out_usage:
3189         usage(CMD_SPLIT, stderr);
3190 out_err:
3191         ret = -1;
3192         goto out;
3193 }
3194
3195 #if WIM_MOUNTING_SUPPORTED
3196 /* Unmounts a mounted WIM image. */
3197 static int
3198 imagex_unmount(int argc, tchar **argv, int cmd)
3199 {
3200         int c;
3201         int unmount_flags = 0;
3202         int ret;
3203
3204         for_opt(c, unmount_options) {
3205                 switch (c) {
3206                 case IMAGEX_COMMIT_OPTION:
3207                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
3208                         break;
3209                 case IMAGEX_CHECK_OPTION:
3210                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
3211                         break;
3212                 case IMAGEX_REBUILD_OPTION:
3213                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
3214                         break;
3215                 case IMAGEX_LAZY_OPTION:
3216                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_LAZY;
3217                         break;
3218                 default:
3219                         goto out_usage;
3220                 }
3221         }
3222         argc -= optind;
3223         argv += optind;
3224         if (argc != 1)
3225                 goto out_usage;
3226
3227         ret = wimlib_unmount_image(argv[0], unmount_flags,
3228                                    imagex_progress_func);
3229         if (ret)
3230                 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
3231 out:
3232         return ret;
3233
3234 out_usage:
3235         usage(CMD_UNMOUNT, stderr);
3236         ret = -1;
3237         goto out;
3238 }
3239 #endif /* WIM_MOUNTING_SUPPORTED */
3240
3241 /*
3242  * Add, delete, or rename files in a WIM image.
3243  */
3244 static int
3245 imagex_update(int argc, tchar **argv, int cmd)
3246 {
3247         const tchar *wimfile;
3248         int image;
3249         WIMStruct *wim;
3250         int ret;
3251         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3252         int write_flags = 0;
3253         int update_flags = WIMLIB_UPDATE_FLAG_SEND_PROGRESS;
3254         int default_add_flags = WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE |
3255                                 WIMLIB_ADD_FLAG_WINCONFIG;
3256         int default_delete_flags = 0;
3257         unsigned num_threads = 0;
3258         int c;
3259         tchar *cmd_file_contents;
3260         size_t cmd_file_nchars;
3261         struct wimlib_update_command *cmds;
3262         size_t num_cmds;
3263         tchar *command_str = NULL;
3264
3265         const tchar *config_file = NULL;
3266         tchar *config_str;
3267         struct wimlib_capture_config *config;
3268
3269         for_opt(c, update_options) {
3270                 switch (c) {
3271                 /* Generic or write options */
3272                 case IMAGEX_THREADS_OPTION:
3273                         num_threads = parse_num_threads(optarg);
3274                         if (num_threads == UINT_MAX)
3275                                 goto out_err;
3276                         break;
3277                 case IMAGEX_CHECK_OPTION:
3278                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3279                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3280                         break;
3281                 case IMAGEX_REBUILD_OPTION:
3282                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
3283                         break;
3284                 case IMAGEX_COMMAND_OPTION:
3285                         if (command_str) {
3286                                 imagex_error(T("--command may only be specified "
3287                                                "one time.  Please provide\n"
3288                                                "       the update commands "
3289                                                "on standard input instead."));
3290                                 goto out_err;
3291                         }
3292                         command_str = tstrdup(optarg);
3293                         if (!command_str) {
3294                                 imagex_error(T("Out of memory!"));
3295                                 goto out_err;
3296                         }
3297                         break;
3298                 /* Default delete options */
3299                 case IMAGEX_FORCE_OPTION:
3300                         default_delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
3301                         break;
3302                 case IMAGEX_RECURSIVE_OPTION:
3303                         default_delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
3304                         break;
3305
3306                 /* Global add option */
3307                 case IMAGEX_CONFIG_OPTION:
3308                         default_add_flags &= ~WIMLIB_ADD_FLAG_WINCONFIG;
3309                         config_file = optarg;
3310                         break;
3311
3312                 /* Default add options */
3313                 case IMAGEX_VERBOSE_OPTION:
3314                         default_add_flags |= WIMLIB_ADD_FLAG_VERBOSE;
3315                         break;
3316                 case IMAGEX_DEREFERENCE_OPTION:
3317                         default_add_flags |= WIMLIB_ADD_FLAG_DEREFERENCE;
3318                         break;
3319                 case IMAGEX_UNIX_DATA_OPTION:
3320                         default_add_flags |= WIMLIB_ADD_FLAG_UNIX_DATA;
3321                         break;
3322                 case IMAGEX_NO_ACLS_OPTION:
3323                         default_add_flags |= WIMLIB_ADD_FLAG_NO_ACLS;
3324                         break;
3325                 case IMAGEX_STRICT_ACLS_OPTION:
3326                         default_add_flags |= WIMLIB_ADD_FLAG_STRICT_ACLS;
3327                         break;
3328                 default:
3329                         goto out_usage;
3330                 }
3331         }
3332         argv += optind;
3333         argc -= optind;
3334
3335         if (argc != 1 && argc != 2)
3336                 goto out_usage;
3337         wimfile = argv[0];
3338
3339         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3340         if (ret)
3341                 goto out_free_command_str;
3342
3343         if (argc >= 2) {
3344                 /* Image explicitly specified.  */
3345                 image = wimlib_resolve_image(wim, argv[1]);
3346                 ret = verify_image_exists_and_is_single(image, argv[1],
3347                                                         wimfile);
3348                 if (ret)
3349                         goto out_wimlib_free;
3350         } else {
3351                 /* No image specified; default to image 1, but only if the WIM
3352                  * contains exactly one image.  */
3353                 struct wimlib_wim_info info;
3354
3355                 wimlib_get_wim_info(wim, &info);
3356                 if (info.image_count != 1) {
3357                         imagex_error(T("\"%"TS"\" contains %d images; Please select one."),
3358                                      wimfile, info.image_count);
3359                         wimlib_free(wim);
3360                         goto out_usage;
3361                 }
3362                 image = 1;
3363         }
3364
3365         /* Parse capture configuration file if specified */
3366         if (config_file) {
3367                 size_t config_len;
3368
3369                 config_str = file_get_text_contents(config_file, &config_len);
3370                 if (!config_str) {
3371                         ret = -1;
3372                         goto out_wimlib_free;
3373                 }
3374
3375                 config = alloca(sizeof(*config));
3376                 ret = parse_capture_config(&config_str, config_len, config);
3377                 if (ret)
3378                         goto out_free_config;
3379         } else {
3380                 config = NULL;
3381         }
3382
3383         /* Read update commands from standard input, or the command string if
3384          * specified.  */
3385         if (command_str) {
3386                 cmd_file_contents = NULL;
3387                 cmds = parse_update_command_file(&command_str, tstrlen(command_str),
3388                                                  &num_cmds);
3389         } else {
3390                 if (isatty(STDIN_FILENO)) {
3391                         tputs(T("Reading update commands from standard input..."));
3392                         recommend_man_page(CMD_UPDATE, stdout);
3393                 }
3394                 cmd_file_contents = stdin_get_text_contents(&cmd_file_nchars);
3395                 if (!cmd_file_contents) {
3396                         ret = -1;
3397                         goto out_free_config;
3398                 }
3399
3400                 /* Parse the update commands */
3401                 cmds = parse_update_command_file(&cmd_file_contents, cmd_file_nchars,
3402                                                  &num_cmds);
3403         }
3404         if (!cmds) {
3405                 ret = -1;
3406                 goto out_free_cmd_file_contents;
3407         }
3408
3409         /* Set default flags and capture config on the update commands */
3410         for (size_t i = 0; i < num_cmds; i++) {
3411                 switch (cmds[i].op) {
3412                 case WIMLIB_UPDATE_OP_ADD:
3413                         cmds[i].add.add_flags |= default_add_flags;
3414                         cmds[i].add.config = config;
3415                         break;
3416                 case WIMLIB_UPDATE_OP_DELETE:
3417                         cmds[i].delete.delete_flags |= default_delete_flags;
3418                         break;
3419                 default:
3420                         break;
3421                 }
3422         }
3423
3424         /* Execute the update commands */
3425         ret = wimlib_update_image(wim, image, cmds, num_cmds, update_flags,
3426                                   imagex_progress_func);
3427         if (ret)
3428                 goto out_free_cmds;
3429
3430         /* Overwrite the updated WIM */
3431         ret = wimlib_overwrite(wim, write_flags, num_threads,
3432                                imagex_progress_func);
3433 out_free_cmds:
3434         free(cmds);
3435 out_free_cmd_file_contents:
3436         free(cmd_file_contents);
3437 out_free_config:
3438         if (config) {
3439                 free(config->exclusion_pats.pats);
3440                 free(config->exclusion_exception_pats.pats);
3441                 free(config_str);
3442         }
3443 out_wimlib_free:
3444         wimlib_free(wim);
3445 out_free_command_str:
3446         free(command_str);
3447         return ret;
3448
3449 out_usage:
3450         usage(CMD_UPDATE, stderr);
3451 out_err:
3452         ret = -1;
3453         goto out_free_command_str;
3454 }
3455
3456
3457
3458 struct imagex_command {
3459         const tchar *name;
3460         int (*func)(int argc, tchar **argv, int cmd);
3461 };
3462
3463 static const struct imagex_command imagex_commands[] = {
3464         [CMD_APPEND]   = {T("append"),   imagex_capture_or_append},
3465         [CMD_APPLY]    = {T("apply"),    imagex_apply},
3466         [CMD_CAPTURE]  = {T("capture"),  imagex_capture_or_append},
3467         [CMD_DELETE]   = {T("delete"),   imagex_delete},
3468         [CMD_DIR ]     = {T("dir"),      imagex_dir},
3469         [CMD_EXPORT]   = {T("export"),   imagex_export},
3470         [CMD_EXTRACT]  = {T("extract"),  imagex_extract},
3471         [CMD_INFO]     = {T("info"),     imagex_info},
3472         [CMD_JOIN]     = {T("join"),     imagex_join},
3473 #if WIM_MOUNTING_SUPPORTED
3474         [CMD_MOUNT]    = {T("mount"),    imagex_mount_rw_or_ro},
3475         [CMD_MOUNTRW]  = {T("mountrw"),  imagex_mount_rw_or_ro},
3476 #endif
3477         [CMD_OPTIMIZE] = {T("optimize"), imagex_optimize},
3478         [CMD_SPLIT]    = {T("split"),    imagex_split},
3479 #if WIM_MOUNTING_SUPPORTED
3480         [CMD_UNMOUNT]  = {T("unmount"),  imagex_unmount},
3481 #endif
3482         [CMD_UPDATE]   = {T("update"),   imagex_update},
3483 };
3484
3485 static const tchar *usage_strings[] = {
3486 [CMD_APPEND] =
3487 T(
3488 "    %"TS" (DIRECTORY | NTFS_VOLUME) WIMFILE\n"
3489 "                    [IMAGE_NAME [IMAGE_DESCRIPTION]] [--boot] [--check]\n"
3490 "                    [--nocheck] [--flags EDITION_ID] [--verbose]\n"
3491 "                    [--dereference] [--config=FILE] [--threads=NUM_THREADS]\n"
3492 "                    [--rebuild] [--unix-data] [--source-list] [--no-acls]\n"
3493 "                    [--strict-acls] [--rpfix] [--norpfix] [--pipable]\n"
3494 "                    [--not-pipable] [--delta-from=IMAGE]\n"
3495 ),
3496 [CMD_APPLY] =
3497 T(
3498 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME | all)]\n"
3499 "                    (DIRECTORY | NTFS_VOLUME) [--check] [--hardlink]\n"
3500 "                    [--symlink] [--verbose] [--ref=\"GLOB\"] [--unix-data]\n"
3501 "                    [--no-acls] [--strict-acls] [--rpfix] [--norpfix]\n"
3502 "                    [--include-invalid-names]\n"
3503 ),
3504 [CMD_CAPTURE] =
3505 T(
3506 "    %"TS" (DIRECTORY | NTFS_VOLUME) WIMFILE\n"
3507 "                    [IMAGE_NAME [IMAGE_DESCRIPTION]] [--boot] [--check]\n"
3508 "                    [--nocheck] [--compress=TYPE] [--flags EDITION_ID]\n"
3509 "                    [--verbose] [--dereference] [--config=FILE]\n"
3510 "                    [--threads=NUM_THREADS] [--unix-data] [--source-list]\n"
3511 "                    [--no-acls] [--strict-acls] [--norpfix] [--pipable]\n"
3512 ),
3513 [CMD_DELETE] =
3514 T(
3515 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--check]\n"
3516 "                    [--soft]\n"
3517 ),
3518 [CMD_DIR] =
3519 T(
3520 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME | all) [--path=PATH]\n"
3521 ),
3522 [CMD_EXPORT] =
3523 T(
3524 "    %"TS" SRC_WIMFILE (SRC_IMAGE_NUM | SRC_IMAGE_NAME | all ) \n"
3525 "                    DEST_WIMFILE [DEST_IMAGE_NAME [DEST_IMAGE_DESCRIPTION]]\n"
3526 "                    [--boot] [--check] [--nocheck] [--compress=TYPE]\n"
3527 "                    [--ref=\"GLOB\"] [--threads=NUM_THREADS] [--rebuild]\n"
3528 "                    [--pipable] [--not-pipable]\n"
3529 ),
3530 [CMD_EXTRACT] =
3531 T(
3532 "    %"TS" WIMFILE (IMAGE_NUM | IMAGE_NAME) [PATH...]\n"
3533 "                    [--check] [--ref=\"GLOB\"] [--verbose] [--unix-data]\n"
3534 "                    [--no-acls] [--strict-acls] [--to-stdout]\n"
3535 "                    [--dest-dir=CMD_DIR] [--include-invalid-names]\n"
3536 ),
3537 [CMD_INFO] =
3538 T(
3539 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME) [NEW_NAME\n"
3540 "                    [NEW_DESC]]] [--boot] [--check] [--nocheck] [--header]\n"
3541 "                    [--lookup-table] [--xml] [--extract-xml FILE]\n"
3542 "                    [--metadata]\n"
3543 ),
3544 [CMD_JOIN] =
3545 T(
3546 "    %"TS" OUT_WIMFILE SPLIT_WIM_PART... [--check]\n"
3547 ),
3548 #if WIM_MOUNTING_SUPPORTED
3549 [CMD_MOUNT] =
3550 T(
3551 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME)] DIRECTORY\n"
3552 "                    [--check] [--debug] [--streams-interface=INTERFACE]\n"
3553 "                    [--ref=\"GLOB\"] [--unix-data] [--allow-other]\n"
3554 ),
3555 [CMD_MOUNTRW] =
3556 T(
3557 "    %"TS" WIMFILE [(IMAGE_NUM | IMAGE_NAME)] DIRECTORY\n"
3558 "                    [--check] [--debug] [--streams-interface=INTERFACE]\n"
3559 "                    [--staging-dir=CMD_DIR] [--unix-data] [--allow-other]\n"
3560 ),
3561 #endif
3562 [CMD_OPTIMIZE] =
3563 T(
3564 "    %"TS" WIMFILE [--check] [--nocheck] [--recompress]\n"
3565 "                    [--threads=NUM_THREADS] [--pipable] [--not-pipable]\n"
3566 ),
3567 [CMD_SPLIT] =
3568 T(
3569 "    %"TS" WIMFILE SPLIT_WIM_PART_1 PART_SIZE_MB [--check]\n"
3570 ),
3571 #if WIM_MOUNTING_SUPPORTED
3572 [CMD_UNMOUNT] =
3573 T(
3574 "    %"TS" DIRECTORY [--commit] [--check] [--rebuild] [--lazy]\n"
3575 ),
3576 #endif
3577 [CMD_UPDATE] =
3578 T(
3579 "    %"TS" WIMFILE [IMAGE_NUM | IMAGE_NAME] [--check] [--rebuild]\n"
3580 "                    [--threads=NUM_THREADS] [DEFAULT_ADD_OPTIONS]\n"
3581 "                    [DEFAULT_DELETE_OPTIONS] [--command=STRING] [< CMDFILE]\n"
3582 ),
3583 };
3584
3585 static const tchar *invocation_name;
3586 static int invocation_cmd = CMD_NONE;
3587
3588 static const tchar *get_cmd_string(int cmd, bool nospace)
3589 {
3590         static tchar buf[50];
3591         if (cmd == CMD_NONE) {
3592                 tsprintf(buf, T("%"TS), T(IMAGEX_PROGNAME));
3593         } else if (invocation_cmd != CMD_NONE) {
3594                 tsprintf(buf, T("wim%"TS), imagex_commands[cmd].name);
3595         } else {
3596                 const tchar *format;
3597
3598                 if (nospace)
3599                         format = T("%"TS"-%"TS"");
3600                 else
3601                         format = T("%"TS" %"TS"");
3602                 tsprintf(buf, format, invocation_name, imagex_commands[cmd].name);
3603         }
3604         return buf;
3605 }
3606
3607 static void
3608 version(void)
3609 {
3610         static const tchar *s =
3611         T(
3612 IMAGEX_PROGNAME " (" PACKAGE ") " PACKAGE_VERSION "\n"
3613 "Copyright (C) 2012, 2013 Eric Biggers\n"
3614 "License GPLv3+; GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
3615 "This is free software: you are free to change and redistribute it.\n"
3616 "There is NO WARRANTY, to the extent permitted by law.\n"
3617 "\n"
3618 "Report bugs to "PACKAGE_BUGREPORT".\n"
3619         );
3620         tfputs(s, stdout);
3621 }
3622
3623
3624 static void
3625 help_or_version(int argc, tchar **argv, int cmd)
3626 {
3627         int i;
3628         const tchar *p;
3629
3630         for (i = 1; i < argc; i++) {
3631                 p = argv[i];
3632                 if (p[0] == T('-') && p[1] == T('-')) {
3633                         p += 2;
3634                         if (!tstrcmp(p, T("help"))) {
3635                                 if (cmd == CMD_NONE)
3636                                         usage_all(stdout);
3637                                 else
3638                                         usage(cmd, stdout);
3639                                 exit(0);
3640                         } else if (!tstrcmp(p, T("version"))) {
3641                                 version();
3642                                 exit(0);
3643                         }
3644                 }
3645         }
3646 }
3647
3648 static void
3649 print_usage_string(int cmd, FILE *fp)
3650 {
3651         tfprintf(fp, usage_strings[cmd], get_cmd_string(cmd, false));
3652 }
3653
3654 static void
3655 recommend_man_page(int cmd, FILE *fp)
3656 {
3657         const tchar *format_str;
3658 #ifdef __WIN32__
3659         format_str = T("See %"TS".pdf in the doc directory for more details.\n");
3660 #else
3661         format_str = T("Try `man %"TS"' for more details.\n");
3662 #endif
3663         tfprintf(fp, format_str, get_cmd_string(cmd, true));
3664 }
3665
3666 static void
3667 usage(int cmd, FILE *fp)
3668 {
3669         tfprintf(fp, T("Usage:\n"));
3670         print_usage_string(cmd, fp);
3671         tfprintf(fp, T("\n"));
3672         recommend_man_page(cmd, fp);
3673 }
3674
3675 static void
3676 usage_all(FILE *fp)
3677 {
3678         tfprintf(fp, T("Usage:\n"));
3679         for (int cmd = 0; cmd < CMD_MAX; cmd++) {
3680                 print_usage_string(cmd, fp);
3681                 tfprintf(fp, T("\n"));
3682         }
3683         static const tchar *extra =
3684         T(
3685 "    %"TS" --help\n"
3686 "    %"TS" --version\n"
3687 "\n"
3688 "    The compression TYPE may be \"maximum\", \"fast\", or \"none\".\n"
3689 "\n"
3690         );
3691         tfprintf(fp, extra, invocation_name, invocation_name);
3692         recommend_man_page(CMD_NONE, fp);
3693 }
3694
3695 /* Entry point for wimlib's ImageX implementation.  On UNIX the command
3696  * arguments will just be 'char' strings (ideally UTF-8 encoded, but could be
3697  * something else), while an Windows the command arguments will be UTF-16LE
3698  * encoded 'wchar_t' strings. */
3699 int
3700 #ifdef __WIN32__
3701 wmain(int argc, wchar_t **argv, wchar_t **envp)
3702 #else
3703 main(int argc, char **argv)
3704 #endif
3705 {
3706         int ret;
3707         int init_flags = 0;
3708         int cmd;
3709
3710         imagex_info_file = stdout;
3711         invocation_name = tbasename(argv[0]);
3712
3713 #ifndef __WIN32__
3714         if (getenv("WIMLIB_IMAGEX_USE_UTF8")) {
3715                 init_flags |= WIMLIB_INIT_FLAG_ASSUME_UTF8;
3716         } else {
3717                 char *codeset;
3718
3719                 setlocale(LC_ALL, "");
3720                 codeset = nl_langinfo(CODESET);
3721                 if (!strstr(codeset, "UTF-8") &&
3722                     !strstr(codeset, "UTF8") &&
3723                     !strstr(codeset, "utf-8") &&
3724                     !strstr(codeset, "utf8"))
3725                 {
3726                         fprintf(stderr,
3727 "WARNING: Running %"TS" in a UTF-8 locale is recommended!\n"
3728 "         Maybe try: `export LANG=en_US.UTF-8'?\n"
3729 "         Alternatively, set the environmental variable WIMLIB_IMAGEX_USE_UTF8\n"
3730 "         to any value to force wimlib to use UTF-8.\n",
3731                         invocation_name);
3732
3733                 }
3734         }
3735 #endif /* !__WIN32__ */
3736
3737         /* Allow being invoked as wimCOMMAND (e.g. wimapply).  */
3738         cmd = CMD_NONE;
3739         if (!tstrncmp(invocation_name, T("wim"), 3) &&
3740             tstrcmp(invocation_name, T(IMAGEX_PROGNAME))) {
3741                 for (int i = 0; i < CMD_MAX; i++) {
3742                         if (!tstrcmp(invocation_name + 3,
3743                                      imagex_commands[i].name))
3744                         {
3745                                 invocation_cmd = i;
3746                                 cmd = i;
3747                                 break;
3748                         }
3749                 }
3750         }
3751
3752         /* Unless already known from the invocation name, determine which
3753          * command was specified.  */
3754         if (cmd == CMD_NONE) {
3755                 if (argc < 2) {
3756                         imagex_error(T("No command specified!\n"));
3757                         usage_all(stderr);
3758                         exit(2);
3759                 }
3760                 for (int i = 0; i < CMD_MAX; i++) {
3761                         if (!tstrcmp(argv[1], imagex_commands[i].name)) {
3762                                 cmd = i;
3763                                 break;
3764                         }
3765                 }
3766                 if (cmd != CMD_NONE) {
3767                         argc--;
3768                         argv++;
3769                 }
3770         }
3771
3772         /* Handle --help and --version.  --help can be either for the program as
3773          * a whole (cmd == CMD_NONE) or just for a specific command (cmd !=
3774          * CMD_NONE).  Note: help_or_version() will not return if a --help or
3775          * --version argument was found.  */
3776         help_or_version(argc, argv, cmd);
3777
3778         /* Bail if a valid command was not specified.  */
3779         if (cmd == CMD_NONE) {
3780                 imagex_error(T("Unrecognized command: `%"TS"'\n"), argv[1]);
3781                 usage_all(stderr);
3782                 exit(2);
3783         }
3784
3785         /* Enable warning and error messages in wimlib be more user-friendly.
3786          * */
3787         wimlib_set_print_errors(true);
3788
3789         /* Initialize wimlib.  */
3790         ret = wimlib_global_init(init_flags);
3791         if (ret)
3792                 goto out_check_status;
3793
3794         /* Call the command handler function.  */
3795         ret = imagex_commands[cmd].func(argc, argv, cmd);
3796
3797         /* Check for error writing to standard output, especially since for some
3798          * commands, writing to standard output is part of the program's actual
3799          * behavior and not just for informational purposes.  */
3800         if (ferror(stdout) || fclose(stdout)) {
3801                 imagex_error_with_errno(T("error writing to standard output"));
3802                 if (ret == 0)
3803                         ret = -1;
3804         }
3805 out_check_status:
3806         /* Exit status (ret):  -1 indicates an error found by 'wimlib-imagex'
3807          * itself (not by wimlib).  0 indicates success.  > 0 indicates a wimlib
3808          * error code from which an error message can be printed.  */
3809         if (ret > 0) {
3810                 imagex_error(T("Exiting with error code %d:\n"
3811                                "       %"TS"."), ret,
3812                              wimlib_get_error_string(ret));
3813                 if (ret == WIMLIB_ERR_NTFS_3G && errno != 0)
3814                         imagex_error_with_errno(T("errno"));
3815         }
3816         /* Make wimlib free any resources it's holding (although this is not
3817          * strictly necessary because the process is ending anyway).  */
3818         wimlib_global_cleanup();
3819         return ret;
3820 }