be4b910eb024c55bd8917c27b265eda56c3456f0
[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                 imagex_printf(T("\nReading split pipable WIM part %u of %u\n"),
1094                               info->extract.part_number,
1095                               info->extract.total_parts);
1096                 break;
1097         case WIMLIB_PROGRESS_MSG_APPLY_TIMESTAMPS:
1098                 if (info->extract.extract_root_wim_source_path[0] == T('\0'))
1099                         imagex_printf(T("Setting timestamps on all extracted files...\n"));
1100                 break;
1101         case WIMLIB_PROGRESS_MSG_EXTRACT_IMAGE_END:
1102                 if (info->extract.extract_flags & WIMLIB_EXTRACT_FLAG_NTFS) {
1103                         imagex_printf(T("Unmounting NTFS volume \"%"TS"\"...\n"),
1104                                 info->extract.target);
1105                 }
1106                 break;
1107         case WIMLIB_PROGRESS_MSG_SPLIT_BEGIN_PART:
1108                 percent_done = TO_PERCENT(info->split.completed_bytes,
1109                                           info->split.total_bytes);
1110                 unit_shift = get_unit(info->split.total_bytes, &unit_name);
1111                 imagex_printf(T("Writing \"%"TS"\" (part %u of %u): %"PRIu64" %"TS" of "
1112                           "%"PRIu64" %"TS" (%u%%) written\n"),
1113                         info->split.part_name,
1114                         info->split.cur_part_number,
1115                         info->split.total_parts,
1116                         info->split.completed_bytes >> unit_shift,
1117                         unit_name,
1118                         info->split.total_bytes >> unit_shift,
1119                         unit_name,
1120                         percent_done);
1121                 break;
1122         case WIMLIB_PROGRESS_MSG_SPLIT_END_PART:
1123                 if (info->split.completed_bytes == info->split.total_bytes) {
1124                         imagex_printf(T("Finished writing split WIM part %u of %u\n"),
1125                                 info->split.cur_part_number,
1126                                 info->split.total_parts);
1127                 }
1128                 break;
1129         case WIMLIB_PROGRESS_MSG_UPDATE_END_COMMAND:
1130                 switch (info->update.command->op) {
1131                 case WIMLIB_UPDATE_OP_DELETE:
1132                         imagex_printf(T("Deleted WIM path "
1133                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1134                                 info->update.command->delete.wim_path);
1135                         break;
1136                 case WIMLIB_UPDATE_OP_RENAME:
1137                         imagex_printf(T("Renamed WIM path "
1138                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\" => "
1139                                   "\""WIMLIB_WIM_PATH_SEPARATOR_STRING "%"TS"\"\n"),
1140                                 info->update.command->rename.wim_source_path,
1141                                 info->update.command->rename.wim_target_path);
1142                         break;
1143                 case WIMLIB_UPDATE_OP_ADD:
1144                 default:
1145                         break;
1146                 }
1147                 break;
1148         default:
1149                 break;
1150         }
1151         fflush(imagex_info_file);
1152         return 0;
1153 }
1154
1155 /* Open all the split WIM parts that correspond to a file glob.
1156  *
1157  * @first_part specifies the first part of the split WIM and it may be either
1158  * included or omitted from the glob. */
1159 static int
1160 open_swms_from_glob(const tchar *swm_glob,
1161                     const tchar *first_part,
1162                     int open_flags,
1163                     WIMStruct ***additional_swms_ret,
1164                     unsigned *num_additional_swms_ret)
1165 {
1166         unsigned num_additional_swms = 0;
1167         WIMStruct **additional_swms = NULL;
1168         glob_t globbuf;
1169         int ret;
1170
1171         /* Warning: glob() is replaced in Windows native builds */
1172         ret = tglob(swm_glob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1173         if (ret) {
1174                 if (ret == GLOB_NOMATCH) {
1175                         imagex_error(T("Found no files for glob \"%"TS"\""),
1176                                      swm_glob);
1177                 } else {
1178                         imagex_error_with_errno(T("Failed to process glob \"%"TS"\""),
1179                                                 swm_glob);
1180                 }
1181                 ret = -1;
1182                 goto out;
1183         }
1184         num_additional_swms = globbuf.gl_pathc;
1185         additional_swms = calloc(num_additional_swms, sizeof(additional_swms[0]));
1186         if (!additional_swms) {
1187                 imagex_error(T("Out of memory"));
1188                 ret = -1;
1189                 goto out_globfree;
1190         }
1191         unsigned offset = 0;
1192         for (unsigned i = 0; i < num_additional_swms; i++) {
1193                 if (tstrcmp(globbuf.gl_pathv[i], first_part) == 0) {
1194                         offset++;
1195                         continue;
1196                 }
1197                 ret = wimlib_open_wim(globbuf.gl_pathv[i],
1198                                       open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK,
1199                                       &additional_swms[i - offset],
1200                                       imagex_progress_func);
1201                 if (ret)
1202                         goto out_close_swms;
1203         }
1204         *additional_swms_ret = additional_swms;
1205         *num_additional_swms_ret = num_additional_swms - offset;
1206         ret = 0;
1207         goto out_globfree;
1208 out_close_swms:
1209         for (unsigned i = 0; i < num_additional_swms; i++)
1210                 wimlib_free(additional_swms[i]);
1211         free(additional_swms);
1212 out_globfree:
1213         globfree(&globbuf);
1214 out:
1215         return ret;
1216 }
1217
1218
1219 static unsigned
1220 parse_num_threads(const tchar *optarg)
1221 {
1222         tchar *tmp;
1223         unsigned long ul_nthreads = tstrtoul(optarg, &tmp, 10);
1224         if (ul_nthreads >= UINT_MAX || *tmp || tmp == optarg) {
1225                 imagex_error(T("Number of threads must be a non-negative integer!"));
1226                 return UINT_MAX;
1227         } else {
1228                 return ul_nthreads;
1229         }
1230 }
1231
1232 /*
1233  * Parse an option passed to an update command.
1234  *
1235  * @op:         One of WIMLIB_UPDATE_OP_* that indicates the command being
1236  *              parsed.
1237  *
1238  * @option:     Text string for the option (beginning with --)
1239  *
1240  * @cmd:        `struct wimlib_update_command' that is being constructed for
1241  *              this command.
1242  *
1243  * Returns true if the option was recognized; false if not.
1244  */
1245 static bool
1246 update_command_add_option(int op, const tchar *option,
1247                           struct wimlib_update_command *cmd)
1248 {
1249         bool recognized = true;
1250         switch (op) {
1251         case WIMLIB_UPDATE_OP_ADD:
1252                 if (!tstrcmp(option, T("--verbose")))
1253                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_VERBOSE;
1254                 else if (!tstrcmp(option, T("--unix-data")))
1255                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_UNIX_DATA;
1256                 else if (!tstrcmp(option, T("--no-acls")) || !tstrcmp(option, T("--noacls")))
1257                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_NO_ACLS;
1258                 else if (!tstrcmp(option, T("--strict-acls")))
1259                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_STRICT_ACLS;
1260                 else if (!tstrcmp(option, T("--dereference")))
1261                         cmd->add.add_flags |= WIMLIB_ADD_FLAG_DEREFERENCE;
1262                 else
1263                         recognized = false;
1264                 break;
1265         case WIMLIB_UPDATE_OP_DELETE:
1266                 if (!tstrcmp(option, T("--force")))
1267                         cmd->delete.delete_flags |= WIMLIB_DELETE_FLAG_FORCE;
1268                 else if (!tstrcmp(option, T("--recursive")))
1269                         cmd->delete.delete_flags |= WIMLIB_DELETE_FLAG_RECURSIVE;
1270                 else
1271                         recognized = false;
1272                 break;
1273         default:
1274                 recognized = false;
1275                 break;
1276         }
1277         return recognized;
1278 }
1279
1280 /* How many nonoption arguments each `imagex update' command expects */
1281 static const unsigned update_command_num_nonoptions[] = {
1282         [WIMLIB_UPDATE_OP_ADD] = 2,
1283         [WIMLIB_UPDATE_OP_DELETE] = 1,
1284         [WIMLIB_UPDATE_OP_RENAME] = 2,
1285 };
1286
1287 static void
1288 update_command_add_nonoption(int op, const tchar *nonoption,
1289                              struct wimlib_update_command *cmd,
1290                              unsigned num_nonoptions)
1291 {
1292         switch (op) {
1293         case WIMLIB_UPDATE_OP_ADD:
1294                 if (num_nonoptions == 0)
1295                         cmd->add.fs_source_path = (tchar*)nonoption;
1296                 else
1297                         cmd->add.wim_target_path = (tchar*)nonoption;
1298                 break;
1299         case WIMLIB_UPDATE_OP_DELETE:
1300                 cmd->delete.wim_path = (tchar*)nonoption;
1301                 break;
1302         case WIMLIB_UPDATE_OP_RENAME:
1303                 if (num_nonoptions == 0)
1304                         cmd->rename.wim_source_path = (tchar*)nonoption;
1305                 else
1306                         cmd->rename.wim_target_path = (tchar*)nonoption;
1307                 break;
1308         }
1309 }
1310
1311 /*
1312  * Parse a command passed on stdin to `imagex update'.
1313  *
1314  * @line:       Text of the command.
1315  * @len:        Length of the line, including a null terminator
1316  *              at line[len - 1].
1317  *
1318  * @command:    A `struct wimlib_update_command' to fill in from the parsed
1319  *              line.
1320  *
1321  * @line_number: Line number of the command, for diagnostics.
1322  *
1323  * Returns true on success; returns false on parse error.
1324  */
1325 static bool
1326 parse_update_command(tchar *line, size_t len,
1327                      struct wimlib_update_command *command,
1328                      size_t line_number)
1329 {
1330         int ret;
1331         tchar *command_name;
1332         int op;
1333         size_t num_nonoptions;
1334
1335         /* Get the command name ("add", "delete", "rename") */
1336         ret = parse_string(&line, &len, &command_name);
1337         if (ret != PARSE_STRING_SUCCESS)
1338                 return false;
1339
1340         if (!tstrcasecmp(command_name, T("add"))) {
1341                 op = WIMLIB_UPDATE_OP_ADD;
1342         } else if (!tstrcasecmp(command_name, T("delete"))) {
1343                 op = WIMLIB_UPDATE_OP_DELETE;
1344         } else if (!tstrcasecmp(command_name, T("rename"))) {
1345                 op = WIMLIB_UPDATE_OP_RENAME;
1346         } else {
1347                 imagex_error(T("Unknown update command \"%"TS"\" on line %zu"),
1348                              command_name, line_number);
1349                 return false;
1350         }
1351         command->op = op;
1352
1353         /* Parse additional options and non-options as needed */
1354         num_nonoptions = 0;
1355         for (;;) {
1356                 tchar *next_string;
1357
1358                 ret = parse_string(&line, &len, &next_string);
1359                 if (ret == PARSE_STRING_NONE) /* End of line */
1360                         break;
1361                 else if (ret != PARSE_STRING_SUCCESS) /* Parse failure */
1362                         return false;
1363                 if (next_string[0] == T('-') && next_string[1] == T('-')) {
1364                         /* Option */
1365                         if (!update_command_add_option(op, next_string, command))
1366                         {
1367                                 imagex_error(T("Unrecognized option \"%"TS"\" to "
1368                                                "update command \"%"TS"\" on line %zu"),
1369                                              next_string, command_name, line_number);
1370
1371                                 return false;
1372                         }
1373                 } else {
1374                         /* Nonoption */
1375                         if (num_nonoptions == update_command_num_nonoptions[op])
1376                         {
1377                                 imagex_error(T("Unexpected argument \"%"TS"\" in "
1378                                                "update command on line %zu\n"
1379                                                "       (The \"%"TS"\" command only "
1380                                                "takes %zu nonoption arguments!)\n"),
1381                                              next_string, line_number,
1382                                              command_name, num_nonoptions);
1383                                 return false;
1384                         }
1385                         update_command_add_nonoption(op, next_string,
1386                                                      command, num_nonoptions);
1387                         num_nonoptions++;
1388                 }
1389         }
1390
1391         if (num_nonoptions != update_command_num_nonoptions[op]) {
1392                 imagex_error(T("Not enough arguments to update command "
1393                                "\"%"TS"\" on line %zu"), command_name, line_number);
1394                 return false;
1395         }
1396         return true;
1397 }
1398
1399 static struct wimlib_update_command *
1400 parse_update_command_file(tchar **cmd_file_contents_p, size_t cmd_file_nchars,
1401                           size_t *num_cmds_ret)
1402 {
1403         ssize_t nlines;
1404         tchar *p;
1405         struct wimlib_update_command *cmds;
1406         size_t i, j;
1407
1408         nlines = text_file_count_lines(cmd_file_contents_p,
1409                                        &cmd_file_nchars);
1410         if (nlines < 0)
1411                 return NULL;
1412
1413         /* Always allocate at least 1 slot, just in case the implementation of
1414          * calloc() returns NULL if 0 bytes are requested. */
1415         cmds = calloc(nlines ?: 1, sizeof(struct wimlib_update_command));
1416         if (!cmds) {
1417                 imagex_error(T("out of memory"));
1418                 return NULL;
1419         }
1420         p = *cmd_file_contents_p;
1421         j = 0;
1422         for (i = 0; i < nlines; i++) {
1423                 /* XXX: Could use rawmemchr() here instead, but it may not be
1424                  * available on all platforms. */
1425                 tchar *endp = tmemchr(p, T('\n'), cmd_file_nchars);
1426                 size_t len = endp - p + 1;
1427                 *endp = T('\0');
1428                 if (!is_comment_line(p, len)) {
1429                         if (!parse_update_command(p, len, &cmds[j++], i + 1)) {
1430                                 free(cmds);
1431                                 return NULL;
1432                         }
1433                 }
1434                 p = endp + 1;
1435         }
1436         *num_cmds_ret = j;
1437         return cmds;
1438 }
1439
1440 /* Apply one image, or all images, from a WIM file into a directory, OR apply
1441  * one image from a WIM file to a NTFS volume.  */
1442 static int
1443 imagex_apply(int argc, tchar **argv, int cmd)
1444 {
1445         int c;
1446         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
1447         int image;
1448         WIMStruct *wim;
1449         int ret;
1450         const tchar *wimfile;
1451         const tchar *target;
1452         const tchar *image_num_or_name;
1453         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL;
1454
1455         const tchar *swm_glob = NULL;
1456         WIMStruct **additional_swms;
1457         unsigned num_additional_swms;
1458
1459         for_opt(c, apply_options) {
1460                 switch (c) {
1461                 case IMAGEX_CHECK_OPTION:
1462                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1463                         break;
1464                 case IMAGEX_HARDLINK_OPTION:
1465                         extract_flags |= WIMLIB_EXTRACT_FLAG_HARDLINK;
1466                         break;
1467                 case IMAGEX_SYMLINK_OPTION:
1468                         extract_flags |= WIMLIB_EXTRACT_FLAG_SYMLINK;
1469                         break;
1470                 case IMAGEX_VERBOSE_OPTION:
1471                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
1472                         break;
1473                 case IMAGEX_REF_OPTION:
1474                         swm_glob = optarg;
1475                         break;
1476                 case IMAGEX_UNIX_DATA_OPTION:
1477                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
1478                         break;
1479                 case IMAGEX_NO_ACLS_OPTION:
1480                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
1481                         break;
1482                 case IMAGEX_STRICT_ACLS_OPTION:
1483                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
1484                         break;
1485                 case IMAGEX_NORPFIX_OPTION:
1486                         extract_flags |= WIMLIB_EXTRACT_FLAG_NORPFIX;
1487                         break;
1488                 case IMAGEX_RPFIX_OPTION:
1489                         extract_flags |= WIMLIB_EXTRACT_FLAG_RPFIX;
1490                         break;
1491                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
1492                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
1493                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
1494                         break;
1495                 case IMAGEX_RESUME_OPTION:
1496                         extract_flags |= WIMLIB_EXTRACT_FLAG_RESUME;
1497                         break;
1498                 default:
1499                         goto out_usage;
1500                 }
1501         }
1502         argc -= optind;
1503         argv += optind;
1504         if (argc != 2 && argc != 3)
1505                 goto out_usage;
1506
1507         wimfile = argv[0];
1508
1509         if (!tstrcmp(wimfile, T("-"))) {
1510                 /* Attempt to apply pipable WIM from standard input.  */
1511                 if (argc == 2) {
1512                         image_num_or_name = NULL;
1513                         target = argv[1];
1514                 } else {
1515                         image_num_or_name = argv[1];
1516                         target = argv[2];
1517                 }
1518                 wim = NULL;
1519                 num_additional_swms = 0;
1520                 additional_swms = NULL;
1521         } else {
1522                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
1523                                       imagex_progress_func);
1524                 if (ret)
1525                         goto out;
1526
1527                 if (argc >= 3) {
1528                         /* Image explicitly specified.  */
1529                         image_num_or_name = argv[1];
1530                         image = wimlib_resolve_image(wim, image_num_or_name);
1531                         ret = verify_image_exists(image, image_num_or_name, wimfile);
1532                         if (ret)
1533                                 goto out_wimlib_free;
1534                         target = argv[2];
1535                 } else {
1536                         /* No image specified; default to image 1, but only if the WIM
1537                          * contains exactly one image.  */
1538                         struct wimlib_wim_info info;
1539
1540                         wimlib_get_wim_info(wim, &info);
1541                         if (info.image_count != 1) {
1542                                 imagex_error(T("\"%"TS"\" contains %d images; "
1543                                                "Please select one (or all)."),
1544                                              wimfile, info.image_count);
1545                                 wimlib_free(wim);
1546                                 goto out_usage;
1547                         }
1548                         image = 1;
1549                         target = argv[1];
1550                 }
1551
1552                 if (swm_glob) {
1553                         ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
1554                                                   &additional_swms,
1555                                                   &num_additional_swms);
1556                         if (ret)
1557                                 goto out_wimlib_free;
1558                 } else {
1559                         additional_swms = NULL;
1560                         num_additional_swms = 0;
1561                 }
1562         }
1563
1564 #ifndef __WIN32__
1565         {
1566                 /* Interpret a regular file or block device target as a NTFS
1567                  * volume.  */
1568                 struct stat stbuf;
1569
1570                 if (tstat(target, &stbuf)) {
1571                         if (errno != ENOENT) {
1572                                 imagex_error_with_errno(T("Failed to stat \"%"TS"\""),
1573                                                         target);
1574                                 ret = -1;
1575                                 goto out_free_swms;
1576                         }
1577                 } else {
1578                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode))
1579                                 extract_flags |= WIMLIB_EXTRACT_FLAG_NTFS;
1580                 }
1581         }
1582 #endif
1583
1584         if (wim) {
1585                 ret = wimlib_extract_image(wim, image, target, extract_flags,
1586                                            additional_swms, num_additional_swms,
1587                                            imagex_progress_func);
1588         } else {
1589                 set_fd_to_binary_mode(STDIN_FILENO);
1590                 ret = wimlib_extract_image_from_pipe(STDIN_FILENO,
1591                                                      image_num_or_name,
1592                                                      target, extract_flags,
1593                                                      imagex_progress_func);
1594         }
1595         if (ret == 0)
1596                 imagex_printf(T("Done applying WIM image.\n"));
1597 out_free_swms:
1598         for (unsigned i = 0; i < num_additional_swms; i++)
1599                 wimlib_free(additional_swms[i]);
1600         free(additional_swms);
1601 out_wimlib_free:
1602         wimlib_free(wim);
1603 out:
1604         return ret;
1605
1606 out_usage:
1607         usage(CMD_APPLY, stderr);
1608         ret = -1;
1609         goto out;
1610 }
1611
1612 /* Create a WIM image from a directory tree, NTFS volume, or multiple files or
1613  * directory trees.  'wimlib-imagex capture': create a new WIM file containing
1614  * the desired image.  'wimlib-imagex append': add a new image to an existing
1615  * WIM file. */
1616 static int
1617 imagex_capture_or_append(int argc, tchar **argv, int cmd)
1618 {
1619         int c;
1620         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
1621         int add_image_flags = WIMLIB_ADD_IMAGE_FLAG_EXCLUDE_VERBOSE |
1622                               WIMLIB_ADD_IMAGE_FLAG_WINCONFIG;
1623         int write_flags = 0;
1624         int compression_type = WIMLIB_COMPRESSION_TYPE_LZX;
1625         const tchar *wimfile;
1626         int wim_fd;
1627         const tchar *name;
1628         const tchar *desc;
1629         const tchar *flags_element = NULL;
1630         const tchar *template_image_name_or_num = NULL;
1631         int template_image;
1632         WIMStruct *wim;
1633         int ret;
1634         unsigned num_threads = 0;
1635
1636         tchar *source;
1637         tchar *source_copy;
1638
1639         const tchar *config_file = NULL;
1640         tchar *config_str;
1641         struct wimlib_capture_config *config;
1642
1643         bool source_list = false;
1644         size_t source_list_nchars;
1645         tchar *source_list_contents;
1646         bool capture_sources_malloced;
1647         struct wimlib_capture_source *capture_sources;
1648         size_t num_sources;
1649         bool name_defaulted;
1650
1651         for_opt(c, capture_or_append_options) {
1652                 switch (c) {
1653                 case IMAGEX_BOOT_OPTION:
1654                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_BOOT;
1655                         break;
1656                 case IMAGEX_CHECK_OPTION:
1657                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1658                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1659                         break;
1660                 case IMAGEX_NOCHECK_OPTION:
1661                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
1662                         break;
1663                 case IMAGEX_CONFIG_OPTION:
1664                         config_file = optarg;
1665                         add_image_flags &= ~WIMLIB_ADD_IMAGE_FLAG_WINCONFIG;
1666                         break;
1667                 case IMAGEX_COMPRESS_OPTION:
1668                         compression_type = get_compression_type(optarg);
1669                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
1670                                 goto out_err;
1671                         break;
1672                 case IMAGEX_FLAGS_OPTION:
1673                         flags_element = optarg;
1674                         break;
1675                 case IMAGEX_DEREFERENCE_OPTION:
1676                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_DEREFERENCE;
1677                         break;
1678                 case IMAGEX_VERBOSE_OPTION:
1679                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_VERBOSE;
1680                         break;
1681                 case IMAGEX_THREADS_OPTION:
1682                         num_threads = parse_num_threads(optarg);
1683                         if (num_threads == UINT_MAX)
1684                                 goto out_err;
1685                         break;
1686                 case IMAGEX_REBUILD_OPTION:
1687                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
1688                         break;
1689                 case IMAGEX_UNIX_DATA_OPTION:
1690                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA;
1691                         break;
1692                 case IMAGEX_SOURCE_LIST_OPTION:
1693                         source_list = true;
1694                         break;
1695                 case IMAGEX_NO_ACLS_OPTION:
1696                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NO_ACLS;
1697                         break;
1698                 case IMAGEX_STRICT_ACLS_OPTION:
1699                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_STRICT_ACLS;
1700                         break;
1701                 case IMAGEX_RPFIX_OPTION:
1702                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_RPFIX;
1703                         break;
1704                 case IMAGEX_NORPFIX_OPTION:
1705                         add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NORPFIX;
1706                         break;
1707                 case IMAGEX_PIPABLE_OPTION:
1708                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1709                         break;
1710                 case IMAGEX_NOT_PIPABLE_OPTION:
1711                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
1712                         break;
1713                 case IMAGEX_DELTA_FROM_OPTION:
1714                         if (cmd == CMD_CAPTURE) {
1715                                 imagex_error(T("--delta-from=IMAGE is only "
1716                                                "valid for append."));
1717                                 goto out_usage;
1718                         }
1719                         template_image_name_or_num = optarg;
1720                         break;
1721                 default:
1722                         goto out_usage;
1723                 }
1724         }
1725         argc -= optind;
1726         argv += optind;
1727
1728         if (argc < 2 || argc > 4)
1729                 goto out_usage;
1730
1731         source = argv[0];
1732         wimfile = argv[1];
1733
1734         if (!tstrcmp(wimfile, T("-"))) {
1735                 /* Writing captured WIM to standard output.  */
1736         #if 0
1737                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
1738                         imagex_error("Can't write a non-pipable WIM to "
1739                                      "standard output!  Specify --pipable\n"
1740                                      "       if you want to create a pipable WIM "
1741                                      "(but read the docs first).");
1742                         goto out_err;
1743                 }
1744         #else
1745                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
1746         #endif
1747                 if (cmd == CMD_APPEND) {
1748                         imagex_error(T("Using standard output for append does "
1749                                        "not make sense."));
1750                         goto out_err;
1751                 }
1752                 wim_fd = STDOUT_FILENO;
1753                 wimfile = NULL;
1754                 imagex_info_file = stderr;
1755                 set_fd_to_binary_mode(wim_fd);
1756         }
1757
1758         if (argc >= 3) {
1759                 name = argv[2];
1760                 name_defaulted = false;
1761         } else {
1762                 /* Set default name to SOURCE argument, omitting any directory
1763                  * prefixes and trailing slashes.  This requires making a copy
1764                  * of @source.  Leave some free characters at the end in case we
1765                  * append a number to keep the name unique. */
1766                 size_t source_name_len;
1767
1768                 source_name_len = tstrlen(source);
1769                 source_copy = alloca((source_name_len + 1 + 25) * sizeof(tchar));
1770                 name = tbasename(tstrcpy(source_copy, source));
1771                 name_defaulted = true;
1772         }
1773         /* Image description defaults to NULL if not given. */
1774         if (argc >= 4)
1775                 desc = argv[3];
1776         else
1777                 desc = NULL;
1778
1779         if (source_list) {
1780                 /* Set up capture sources in source list mode */
1781                 if (source[0] == T('-') && source[1] == T('\0')) {
1782                         source_list_contents = stdin_get_text_contents(&source_list_nchars);
1783                 } else {
1784                         source_list_contents = file_get_text_contents(source,
1785                                                                       &source_list_nchars);
1786                 }
1787                 if (!source_list_contents)
1788                         goto out_err;
1789
1790                 capture_sources = parse_source_list(&source_list_contents,
1791                                                     source_list_nchars,
1792                                                     &num_sources);
1793                 if (!capture_sources) {
1794                         ret = -1;
1795                         goto out_free_source_list_contents;
1796                 }
1797                 capture_sources_malloced = true;
1798         } else {
1799                 /* Set up capture source in non-source-list mode (could be
1800                  * either "normal" mode or "NTFS mode"--- see the man page). */
1801                 capture_sources = alloca(sizeof(struct wimlib_capture_source));
1802                 capture_sources[0].fs_source_path = source;
1803                 capture_sources[0].wim_target_path = NULL;
1804                 capture_sources[0].reserved = 0;
1805                 num_sources = 1;
1806                 capture_sources_malloced = false;
1807                 source_list_contents = NULL;
1808         }
1809
1810         if (config_file) {
1811                 size_t config_len;
1812
1813                 config_str = file_get_text_contents(config_file, &config_len);
1814                 if (!config_str) {
1815                         ret = -1;
1816                         goto out_free_capture_sources;
1817                 }
1818
1819                 config = alloca(sizeof(*config));
1820                 ret = parse_capture_config(&config_str, config_len, config);
1821                 if (ret)
1822                         goto out_free_config;
1823         } else {
1824                 config = NULL;
1825         }
1826
1827         if (cmd == CMD_APPEND)
1828                 ret = wimlib_open_wim(wimfile, open_flags, &wim,
1829                                       imagex_progress_func);
1830         else
1831                 ret = wimlib_create_new_wim(compression_type, &wim);
1832         if (ret)
1833                 goto out_free_config;
1834
1835 #ifndef __WIN32__
1836         if (!source_list) {
1837                 struct stat stbuf;
1838
1839                 if (tstat(source, &stbuf) == 0) {
1840                         if (S_ISBLK(stbuf.st_mode) || S_ISREG(stbuf.st_mode)) {
1841                                 imagex_printf(T("Capturing WIM image from NTFS "
1842                                           "filesystem on \"%"TS"\"\n"), source);
1843                                 add_image_flags |= WIMLIB_ADD_IMAGE_FLAG_NTFS;
1844                         }
1845                 } else {
1846                         if (errno != ENOENT) {
1847                                 imagex_error_with_errno(T("Failed to stat "
1848                                                           "\"%"TS"\""), source);
1849                                 ret = -1;
1850                                 goto out_wimlib_free;
1851                         }
1852                 }
1853         }
1854 #endif
1855
1856         if (cmd == CMD_APPEND && name_defaulted) {
1857                 /* If the user did not specify an image name, and the basename
1858                  * of the source already exists as an image name in the WIM
1859                  * file, append a suffix to make it unique. */
1860                 unsigned long conflict_idx;
1861                 tchar *name_end = tstrchr(name, T('\0'));
1862                 for (conflict_idx = 1;
1863                      wimlib_image_name_in_use(wim, name);
1864                      conflict_idx++)
1865                 {
1866                         tsprintf(name_end, T(" (%lu)"), conflict_idx);
1867                 }
1868         }
1869
1870         if (template_image_name_or_num) {
1871                 template_image = wimlib_resolve_image(wim, template_image_name_or_num);
1872                 if (template_image_name_or_num[0] == T('-')) {
1873                         tchar *tmp;
1874                         unsigned long n;
1875                         struct wimlib_wim_info info;
1876
1877                         wimlib_get_wim_info(wim, &info);
1878                         n = tstrtoul(template_image_name_or_num + 1, &tmp, 10);
1879                         if (n >= 1 && n <= info.image_count &&
1880                             *tmp == T('\0') &&
1881                             tmp != template_image_name_or_num + 1)
1882                         {
1883                                 template_image = info.image_count - (n - 1);
1884                         }
1885                 }
1886                 ret = verify_image_exists_and_is_single(template_image,
1887                                                         template_image_name_or_num,
1888                                                         wimfile);
1889                 if (ret)
1890                         goto out_wimlib_free;
1891         }
1892
1893         ret = wimlib_add_image_multisource(wim,
1894                                            capture_sources,
1895                                            num_sources,
1896                                            name,
1897                                            config,
1898                                            add_image_flags,
1899                                            imagex_progress_func);
1900         if (ret)
1901                 goto out_wimlib_free;
1902
1903         if (desc || flags_element || template_image_name_or_num) {
1904                 /* User provided <DESCRIPTION> or <FLAGS> element, or an image
1905                  * on which the added one is to be based has been specified with
1906                  * --delta-from=IMAGE.  Get the index of the image we just
1907                  *  added, then use it to call the appropriate functions.  */
1908                 struct wimlib_wim_info info;
1909
1910                 wimlib_get_wim_info(wim, &info);
1911
1912                 if (desc) {
1913                         ret = wimlib_set_image_descripton(wim,
1914                                                           info.image_count,
1915                                                           desc);
1916                         if (ret)
1917                                 goto out_wimlib_free;
1918                 }
1919
1920                 if (flags_element) {
1921                         ret = wimlib_set_image_flags(wim, info.image_count,
1922                                                      flags_element);
1923                         if (ret)
1924                                 goto out_wimlib_free;
1925                 }
1926
1927                 if (template_image_name_or_num) {
1928                         ret = wimlib_reference_template_image(wim,
1929                                                               info.image_count,
1930                                                               template_image,
1931                                                               0, NULL);
1932                         if (ret)
1933                                 goto out_wimlib_free;
1934                 }
1935         }
1936
1937         /* Write the new WIM or overwrite the existing WIM with the new image
1938          * appended.  */
1939         if (cmd == CMD_APPEND) {
1940                 ret = wimlib_overwrite(wim, write_flags, num_threads,
1941                                        imagex_progress_func);
1942         } else if (wimfile) {
1943                 ret = wimlib_write(wim, wimfile, WIMLIB_ALL_IMAGES,
1944                                    write_flags, num_threads,
1945                                    imagex_progress_func);
1946         } else {
1947                 ret = wimlib_write_to_fd(wim, wim_fd, WIMLIB_ALL_IMAGES,
1948                                          write_flags, num_threads,
1949                                          imagex_progress_func);
1950         }
1951 out_wimlib_free:
1952         wimlib_free(wim);
1953 out_free_config:
1954         if (config) {
1955                 free(config->exclusion_pats.pats);
1956                 free(config->exclusion_exception_pats.pats);
1957                 free(config_str);
1958         }
1959 out_free_capture_sources:
1960         if (capture_sources_malloced)
1961                 free(capture_sources);
1962 out_free_source_list_contents:
1963         free(source_list_contents);
1964 out:
1965         return ret;
1966
1967 out_usage:
1968         usage(cmd, stderr);
1969 out_err:
1970         ret = -1;
1971         goto out;
1972 }
1973
1974 /* Remove image(s) from a WIM. */
1975 static int
1976 imagex_delete(int argc, tchar **argv, int cmd)
1977 {
1978         int c;
1979         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
1980         int write_flags = 0;
1981         const tchar *wimfile;
1982         const tchar *image_num_or_name;
1983         WIMStruct *wim;
1984         int image;
1985         int ret;
1986
1987         for_opt(c, delete_options) {
1988                 switch (c) {
1989                 case IMAGEX_CHECK_OPTION:
1990                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
1991                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
1992                         break;
1993                 case IMAGEX_SOFT_OPTION:
1994                         write_flags |= WIMLIB_WRITE_FLAG_SOFT_DELETE;
1995                         break;
1996                 default:
1997                         goto out_usage;
1998                 }
1999         }
2000         argc -= optind;
2001         argv += optind;
2002
2003         if (argc != 2) {
2004                 if (argc < 1)
2005                         imagex_error(T("Must specify a WIM file"));
2006                 if (argc < 2)
2007                         imagex_error(T("Must specify an image"));
2008                 goto out_usage;
2009         }
2010         wimfile = argv[0];
2011         image_num_or_name = argv[1];
2012
2013         ret = wimlib_open_wim(wimfile, open_flags, &wim,
2014                               imagex_progress_func);
2015         if (ret)
2016                 goto out;
2017
2018         image = wimlib_resolve_image(wim, image_num_or_name);
2019
2020         ret = verify_image_exists(image, image_num_or_name, wimfile);
2021         if (ret)
2022                 goto out_wimlib_free;
2023
2024         ret = wimlib_delete_image(wim, image);
2025         if (ret) {
2026                 imagex_error(T("Failed to delete image from \"%"TS"\""),
2027                              wimfile);
2028                 goto out_wimlib_free;
2029         }
2030
2031         ret = wimlib_overwrite(wim, write_flags, 0, imagex_progress_func);
2032         if (ret) {
2033                 imagex_error(T("Failed to write the file \"%"TS"\" with image "
2034                                "deleted"), wimfile);
2035         }
2036 out_wimlib_free:
2037         wimlib_free(wim);
2038 out:
2039         return ret;
2040
2041 out_usage:
2042         usage(CMD_DELETE, stderr);
2043         ret = -1;
2044         goto out;
2045 }
2046
2047 static int
2048 print_full_path(const struct wimlib_dir_entry *wdentry, void *_ignore)
2049 {
2050         int ret = tprintf(T("%"TS"\n"), wdentry->full_path);
2051         return (ret >= 0) ? 0 : -1;
2052 }
2053
2054 /* Print the files contained in an image(s) in a WIM file. */
2055 static int
2056 imagex_dir(int argc, tchar **argv, int cmd)
2057 {
2058         const tchar *wimfile;
2059         WIMStruct *wim = NULL;
2060         int image;
2061         int ret;
2062         const tchar *path = T("");
2063         int c;
2064
2065         for_opt(c, dir_options) {
2066                 switch (c) {
2067                 case IMAGEX_PATH_OPTION:
2068                         path = optarg;
2069                         break;
2070                 default:
2071                         goto out_usage;
2072                 }
2073         }
2074         argc -= optind;
2075         argv += optind;
2076
2077         if (argc < 1) {
2078                 imagex_error(T("Must specify a WIM file"));
2079                 goto out_usage;
2080         }
2081         if (argc > 2) {
2082                 imagex_error(T("Too many arguments"));
2083                 goto out_usage;
2084         }
2085
2086         wimfile = argv[0];
2087         ret = wimlib_open_wim(wimfile, WIMLIB_OPEN_FLAG_SPLIT_OK, &wim,
2088                               imagex_progress_func);
2089         if (ret)
2090                 goto out;
2091
2092         if (argc >= 2) {
2093                 image = wimlib_resolve_image(wim, argv[1]);
2094                 ret = verify_image_exists(image, argv[1], wimfile);
2095                 if (ret)
2096                         goto out_wimlib_free;
2097         } else {
2098                 /* No image specified; default to image 1, but only if the WIM
2099                  * contains exactly one image.  */
2100
2101                 struct wimlib_wim_info info;
2102
2103                 wimlib_get_wim_info(wim, &info);
2104                 if (info.image_count != 1) {
2105                         imagex_error(T("\"%"TS"\" contains %d images; Please "
2106                                        "select one (or all)."),
2107                                      wimfile, info.image_count);
2108                         wimlib_free(wim);
2109                         goto out_usage;
2110                 }
2111                 image = 1;
2112         }
2113
2114         ret = wimlib_iterate_dir_tree(wim, image, path,
2115                                       WIMLIB_ITERATE_DIR_TREE_FLAG_RECURSIVE,
2116                                       print_full_path, NULL);
2117 out_wimlib_free:
2118         wimlib_free(wim);
2119 out:
2120         return ret;
2121
2122 out_usage:
2123         usage(CMD_DIR, stderr);
2124         ret = -1;
2125         goto out;
2126 }
2127
2128 /* Exports one, or all, images from a WIM file to a new WIM file or an existing
2129  * WIM file. */
2130 static int
2131 imagex_export(int argc, tchar **argv, int cmd)
2132 {
2133         int c;
2134         int open_flags = 0;
2135         int export_flags = 0;
2136         int write_flags = 0;
2137         int compression_type = WIMLIB_COMPRESSION_TYPE_INVALID;
2138         const tchar *src_wimfile;
2139         const tchar *src_image_num_or_name;
2140         const tchar *dest_wimfile;
2141         int dest_wim_fd;
2142         const tchar *dest_name;
2143         const tchar *dest_desc;
2144         WIMStruct *src_wim;
2145         WIMStruct *dest_wim;
2146         int ret;
2147         int image;
2148         struct stat stbuf;
2149         bool wim_is_new;
2150         const tchar *swm_glob = NULL;
2151         WIMStruct **additional_swms;
2152         unsigned num_additional_swms;
2153         unsigned num_threads = 0;
2154
2155         for_opt(c, export_options) {
2156                 switch (c) {
2157                 case IMAGEX_BOOT_OPTION:
2158                         export_flags |= WIMLIB_EXPORT_FLAG_BOOT;
2159                         break;
2160                 case IMAGEX_CHECK_OPTION:
2161                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2162                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2163                         break;
2164                 case IMAGEX_NOCHECK_OPTION:
2165                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
2166                         break;
2167                 case IMAGEX_COMPRESS_OPTION:
2168                         compression_type = get_compression_type(optarg);
2169                         if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID)
2170                                 goto out_err;
2171                         break;
2172                 case IMAGEX_REF_OPTION:
2173                         swm_glob = optarg;
2174                         break;
2175                 case IMAGEX_THREADS_OPTION:
2176                         num_threads = parse_num_threads(optarg);
2177                         if (num_threads == UINT_MAX)
2178                                 goto out_err;
2179                         break;
2180                 case IMAGEX_REBUILD_OPTION:
2181                         write_flags |= WIMLIB_WRITE_FLAG_REBUILD;
2182                         break;
2183                 case IMAGEX_PIPABLE_OPTION:
2184                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2185                         break;
2186                 case IMAGEX_NOT_PIPABLE_OPTION:
2187                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
2188                         break;
2189                 default:
2190                         goto out_usage;
2191                 }
2192         }
2193         argc -= optind;
2194         argv += optind;
2195         if (argc < 3 || argc > 5)
2196                 goto out_usage;
2197         src_wimfile           = argv[0];
2198         src_image_num_or_name = argv[1];
2199         dest_wimfile          = argv[2];
2200         dest_name             = (argc >= 4) ? argv[3] : NULL;
2201         dest_desc             = (argc >= 5) ? argv[4] : NULL;
2202         ret = wimlib_open_wim(src_wimfile,
2203                               open_flags | WIMLIB_OPEN_FLAG_SPLIT_OK, &src_wim,
2204                               imagex_progress_func);
2205         if (ret)
2206                 goto out;
2207
2208         /* Determine if the destination is an existing file or not.  If so, we
2209          * try to append the exported image(s) to it; otherwise, we create a new
2210          * WIM containing the exported image(s).  Furthermore, determine if we
2211          * need to write a pipable WIM directly to standard output.  */
2212
2213         if (tstrcmp(dest_wimfile, T("-")) == 0) {
2214         #if 0
2215                 if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2216                         imagex_error("Can't write a non-pipable WIM to "
2217                                      "standard output!  Specify --pipable\n"
2218                                      "       if you want to create a pipable WIM "
2219                                      "(but read the docs first).");
2220                         ret = -1;
2221                         goto out_free_src_wim;
2222                 }
2223         #else
2224                 write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2225         #endif
2226                 dest_wimfile = NULL;
2227                 dest_wim_fd = STDOUT_FILENO;
2228                 imagex_info_file = stderr;
2229                 set_fd_to_binary_mode(dest_wim_fd);
2230         }
2231         errno = ENOENT;
2232         if (dest_wimfile != NULL && tstat(dest_wimfile, &stbuf) == 0) {
2233                 wim_is_new = false;
2234                 /* Destination file exists. */
2235
2236                 if (!S_ISREG(stbuf.st_mode)) {
2237                         imagex_error(T("\"%"TS"\" is not a regular file"),
2238                                      dest_wimfile);
2239                         ret = -1;
2240                         goto out_free_src_wim;
2241                 }
2242                 ret = wimlib_open_wim(dest_wimfile, open_flags | WIMLIB_OPEN_FLAG_WRITE_ACCESS,
2243                                       &dest_wim, imagex_progress_func);
2244                 if (ret)
2245                         goto out_free_src_wim;
2246
2247                 if (compression_type != WIMLIB_COMPRESSION_TYPE_INVALID) {
2248                         /* The user specified a compression type, but we're
2249                          * exporting to an existing WIM.  Make sure the
2250                          * specified compression type is the same as the
2251                          * compression type of the existing destination WIM. */
2252                         struct wimlib_wim_info dest_info;
2253
2254                         wimlib_get_wim_info(dest_wim, &dest_info);
2255                         if (compression_type != dest_info.compression_type) {
2256                                 imagex_error(T("Cannot specify a compression type that is "
2257                                                "not the same as that used in the "
2258                                                "destination WIM"));
2259                                 ret = -1;
2260                                 goto out_free_dest_wim;
2261                         }
2262                 }
2263         } else {
2264                 wim_is_new = true;
2265
2266                 if (errno != ENOENT) {
2267                         imagex_error_with_errno(T("Cannot stat file \"%"TS"\""),
2268                                                 dest_wimfile);
2269                         ret = -1;
2270                         goto out_free_src_wim;
2271                 }
2272
2273                 /* dest_wimfile is not an existing file, so create a new WIM. */
2274
2275                 if (compression_type == WIMLIB_COMPRESSION_TYPE_INVALID) {
2276                         /* The user did not specify a compression type; default
2277                          * to that of the source WIM.  */
2278
2279                         struct wimlib_wim_info src_info;
2280
2281                         wimlib_get_wim_info(src_wim, &src_info);
2282                         compression_type = src_info.compression_type;
2283                 }
2284                 ret = wimlib_create_new_wim(compression_type, &dest_wim);
2285                 if (ret)
2286                         goto out_free_src_wim;
2287         }
2288
2289         image = wimlib_resolve_image(src_wim, src_image_num_or_name);
2290         ret = verify_image_exists(image, src_image_num_or_name, src_wimfile);
2291         if (ret)
2292                 goto out_free_dest_wim;
2293
2294         if (swm_glob) {
2295                 ret = open_swms_from_glob(swm_glob, src_wimfile, open_flags,
2296                                           &additional_swms,
2297                                           &num_additional_swms);
2298                 if (ret)
2299                         goto out_free_dest_wim;
2300         } else {
2301                 additional_swms = NULL;
2302                 num_additional_swms = 0;
2303         }
2304
2305         ret = wimlib_export_image(src_wim, image, dest_wim, dest_name,
2306                                   dest_desc, export_flags, additional_swms,
2307                                   num_additional_swms, imagex_progress_func);
2308         if (ret)
2309                 goto out_free_swms;
2310
2311         if (!wim_is_new)
2312                 ret = wimlib_overwrite(dest_wim, write_flags, num_threads,
2313                                        imagex_progress_func);
2314         else if (dest_wimfile)
2315                 ret = wimlib_write(dest_wim, dest_wimfile, WIMLIB_ALL_IMAGES,
2316                                    write_flags, num_threads,
2317                                    imagex_progress_func);
2318         else
2319                 ret = wimlib_write_to_fd(dest_wim, dest_wim_fd,
2320                                          WIMLIB_ALL_IMAGES, write_flags,
2321                                          num_threads, imagex_progress_func);
2322         if (ret)
2323                 imagex_error(T("Export failed."));
2324 out_free_swms:
2325         for (unsigned i = 0; i < num_additional_swms; i++)
2326                 wimlib_free(additional_swms[i]);
2327         free(additional_swms);
2328 out_free_dest_wim:
2329         wimlib_free(dest_wim);
2330 out_free_src_wim:
2331         wimlib_free(src_wim);
2332 out:
2333         return ret;
2334
2335 out_usage:
2336         usage(CMD_EXPORT, stderr);
2337 out_err:
2338         ret = -1;
2339         goto out;
2340 }
2341
2342 static bool
2343 is_root_wim_path(const tchar *path)
2344 {
2345         const tchar *p;
2346         for (p = path; *p; p++)
2347                 if (*p != T('\\') && *p != T('/'))
2348                         return false;
2349         return true;
2350 }
2351
2352 static void
2353 free_extract_commands(struct wimlib_extract_command *cmds, size_t num_cmds,
2354                       const tchar *dest_dir)
2355 {
2356         for (size_t i = 0; i < num_cmds; i++)
2357                 if (cmds[i].fs_dest_path != dest_dir)
2358                         free(cmds[i].fs_dest_path);
2359         free(cmds);
2360 }
2361
2362 static struct wimlib_extract_command *
2363 prepare_extract_commands(tchar **paths, unsigned num_paths,
2364                          int extract_flags, tchar *dest_dir,
2365                          size_t *num_cmds_ret)
2366 {
2367         struct wimlib_extract_command *cmds;
2368         size_t num_cmds;
2369         tchar *emptystr = T("");
2370
2371         if (num_paths == 0) {
2372                 num_paths = 1;
2373                 paths = &emptystr;
2374         }
2375         num_cmds = num_paths;
2376         cmds = calloc(num_cmds, sizeof(cmds[0]));
2377         if (!cmds) {
2378                 imagex_error(T("Out of memory!"));
2379                 return NULL;
2380         }
2381
2382         for (size_t i = 0; i < num_cmds; i++) {
2383                 cmds[i].extract_flags = extract_flags;
2384                 cmds[i].wim_source_path = paths[i];
2385                 if (is_root_wim_path(paths[i])) {
2386                         cmds[i].fs_dest_path = dest_dir;
2387                 } else {
2388                         size_t len = tstrlen(dest_dir) + 1 + tstrlen(paths[i]);
2389                         cmds[i].fs_dest_path = malloc((len + 1) * sizeof(tchar));
2390                         if (!cmds[i].fs_dest_path) {
2391                                 free_extract_commands(cmds, num_cmds, dest_dir);
2392                                 return NULL;
2393                         }
2394                         tsprintf(cmds[i].fs_dest_path,
2395                                  T("%"TS""OS_PREFERRED_PATH_SEPARATOR_STRING"%"TS),
2396                                  dest_dir, tbasename(paths[i]));
2397                 }
2398         }
2399         *num_cmds_ret = num_cmds;
2400         return cmds;
2401 }
2402
2403 /* Extract files or directories from a WIM image */
2404 static int
2405 imagex_extract(int argc, tchar **argv, int cmd)
2406 {
2407         int c;
2408         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2409         int image;
2410         WIMStruct *wim;
2411         int ret;
2412         const tchar *wimfile;
2413         const tchar *image_num_or_name;
2414         tchar *dest_dir = T(".");
2415         int extract_flags = WIMLIB_EXTRACT_FLAG_SEQUENTIAL | WIMLIB_EXTRACT_FLAG_NORPFIX;
2416
2417         const tchar *swm_glob = NULL;
2418         WIMStruct **additional_swms;
2419         unsigned num_additional_swms;
2420
2421         struct wimlib_extract_command *cmds;
2422         size_t num_cmds;
2423
2424         for_opt(c, extract_options) {
2425                 switch (c) {
2426                 case IMAGEX_CHECK_OPTION:
2427                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2428                         break;
2429                 case IMAGEX_VERBOSE_OPTION:
2430                         extract_flags |= WIMLIB_EXTRACT_FLAG_VERBOSE;
2431                         break;
2432                 case IMAGEX_REF_OPTION:
2433                         swm_glob = optarg;
2434                         break;
2435                 case IMAGEX_UNIX_DATA_OPTION:
2436                         extract_flags |= WIMLIB_EXTRACT_FLAG_UNIX_DATA;
2437                         break;
2438                 case IMAGEX_NO_ACLS_OPTION:
2439                         extract_flags |= WIMLIB_EXTRACT_FLAG_NO_ACLS;
2440                         break;
2441                 case IMAGEX_STRICT_ACLS_OPTION:
2442                         extract_flags |= WIMLIB_EXTRACT_FLAG_STRICT_ACLS;
2443                         break;
2444                 case IMAGEX_DEST_DIR_OPTION:
2445                         dest_dir = optarg;
2446                         break;
2447                 case IMAGEX_TO_STDOUT_OPTION:
2448                         extract_flags |= WIMLIB_EXTRACT_FLAG_TO_STDOUT;
2449                         imagex_info_file = stderr;
2450                         imagex_be_quiet = true;
2451                         break;
2452                 case IMAGEX_INCLUDE_INVALID_NAMES_OPTION:
2453                         extract_flags |= WIMLIB_EXTRACT_FLAG_REPLACE_INVALID_FILENAMES;
2454                         extract_flags |= WIMLIB_EXTRACT_FLAG_ALL_CASE_CONFLICTS;
2455                         break;
2456                 default:
2457                         goto out_usage;
2458                 }
2459         }
2460         argc -= optind;
2461         argv += optind;
2462
2463         if (argc < 2)
2464                 goto out_usage;
2465
2466         wimfile = argv[0];
2467         image_num_or_name = argv[1];
2468
2469         argc -= 2;
2470         argv += 2;
2471
2472         cmds = prepare_extract_commands(argv, argc, extract_flags, dest_dir,
2473                                         &num_cmds);
2474         if (!cmds)
2475                 goto out_err;
2476
2477         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2478         if (ret)
2479                 goto out_free_cmds;
2480
2481         image = wimlib_resolve_image(wim, image_num_or_name);
2482         ret = verify_image_exists_and_is_single(image,
2483                                                 image_num_or_name,
2484                                                 wimfile);
2485         if (ret)
2486                 goto out_wimlib_free;
2487
2488         if (swm_glob) {
2489                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
2490                                           &additional_swms,
2491                                           &num_additional_swms);
2492                 if (ret)
2493                         goto out_wimlib_free;
2494         } else {
2495                 additional_swms = NULL;
2496                 num_additional_swms = 0;
2497         }
2498
2499         ret = wimlib_extract_files(wim, image, cmds, num_cmds, 0,
2500                                    additional_swms, num_additional_swms,
2501                                    imagex_progress_func);
2502         if (ret == 0) {
2503                 if (!imagex_be_quiet)
2504                         imagex_printf(T("Done extracting files.\n"));
2505         } else if (ret == WIMLIB_ERR_PATH_DOES_NOT_EXIST) {
2506                 tfprintf(stderr, T("Note: You can use `%"TS"' to see what "
2507                                    "files and directories\n"
2508                                    "      are in the WIM image.\n"),
2509                                 get_cmd_string(CMD_INFO, false));
2510         }
2511         for (unsigned i = 0; i < num_additional_swms; i++)
2512                 wimlib_free(additional_swms[i]);
2513         free(additional_swms);
2514 out_wimlib_free:
2515         wimlib_free(wim);
2516 out_free_cmds:
2517         free_extract_commands(cmds, num_cmds, dest_dir);
2518 out:
2519         return ret;
2520
2521 out_usage:
2522         usage(CMD_EXTRACT, stderr);
2523 out_err:
2524         ret = -1;
2525         goto out;
2526 }
2527
2528 static void print_byte_field(const uint8_t field[], size_t len)
2529 {
2530         while (len--)
2531                 tprintf(T("%02hhx"), *field++);
2532 }
2533
2534 static void
2535 print_wim_information(const tchar *wimfile, const struct wimlib_wim_info *info)
2536 {
2537         tputs(T("WIM Information:"));
2538         tputs(T("----------------"));
2539         tprintf(T("Path:           %"TS"\n"), wimfile);
2540         tprintf(T("GUID:           0x"));
2541         print_byte_field(info->guid, sizeof(info->guid));
2542         tputchar(T('\n'));
2543         tprintf(T("Image Count:    %d\n"), info->image_count);
2544         tprintf(T("Compression:    %"TS"\n"),
2545                 wimlib_get_compression_type_string(info->compression_type));
2546         tprintf(T("Part Number:    %d/%d\n"), info->part_number, info->total_parts);
2547         tprintf(T("Boot Index:     %d\n"), info->boot_index);
2548         tprintf(T("Size:           %"PRIu64" bytes\n"), info->total_bytes);
2549         tprintf(T("Integrity Info: %"TS"\n"),
2550                 info->has_integrity_table ? T("yes") : T("no"));
2551         tprintf(T("Relative path junction: %"TS"\n"),
2552                 info->has_rpfix ? T("yes") : T("no"));
2553         tprintf(T("Pipable:        %"TS"\n"),
2554                 info->pipable ? T("yes") : T("no"));
2555         tputchar(T('\n'));
2556 }
2557
2558 static int
2559 print_resource(const struct wimlib_resource_entry *resource,
2560                void *_ignore)
2561 {
2562
2563         tprintf(T("Uncompressed size   = %"PRIu64" bytes\n"),
2564                 resource->uncompressed_size);
2565
2566         tprintf(T("Compressed size     = %"PRIu64" bytes\n"),
2567                 resource->compressed_size);
2568
2569         tprintf(T("Offset              = %"PRIu64" bytes\n"),
2570                 resource->offset);
2571
2572
2573         tprintf(T("Part Number         = %u\n"), resource->part_number);
2574         tprintf(T("Reference Count     = %u\n"), resource->reference_count);
2575
2576         tprintf(T("Hash                = 0x"));
2577         print_byte_field(resource->sha1_hash, sizeof(resource->sha1_hash));
2578         tputchar(T('\n'));
2579
2580         tprintf(T("Flags               = "));
2581         if (resource->is_compressed)
2582                 tprintf(T("WIM_RESHDR_FLAG_COMPRESSED  "));
2583         if (resource->is_metadata)
2584                 tprintf(T("WIM_RESHDR_FLAG_METADATA  "));
2585         if (resource->is_free)
2586                 tprintf(T("WIM_RESHDR_FLAG_FREE  "));
2587         if (resource->is_spanned)
2588                 tprintf(T("WIM_RESHDR_FLAG_SPANNED  "));
2589         tputchar(T('\n'));
2590         tputchar(T('\n'));
2591         return 0;
2592 }
2593
2594 static void
2595 print_lookup_table(WIMStruct *wim)
2596 {
2597         wimlib_iterate_lookup_table(wim, 0, print_resource, NULL);
2598 }
2599
2600 /* Prints information about a WIM file; also can mark an image as bootable,
2601  * change the name of an image, or change the description of an image. */
2602 static int
2603 imagex_info(int argc, tchar **argv, int cmd)
2604 {
2605         int c;
2606         bool boot         = false;
2607         bool check        = false;
2608         bool nocheck      = false;
2609         bool header       = false;
2610         bool lookup_table = false;
2611         bool xml          = false;
2612         bool metadata     = false;
2613         bool short_header = true;
2614         const tchar *xml_out_file = NULL;
2615         const tchar *wimfile;
2616         const tchar *image_num_or_name;
2617         const tchar *new_name;
2618         const tchar *new_desc;
2619         WIMStruct *wim;
2620         int image;
2621         int ret;
2622         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2623         struct wimlib_wim_info info;
2624
2625         for_opt(c, info_options) {
2626                 switch (c) {
2627                 case IMAGEX_BOOT_OPTION:
2628                         boot = true;
2629                         break;
2630                 case IMAGEX_CHECK_OPTION:
2631                         check = true;
2632                         break;
2633                 case IMAGEX_NOCHECK_OPTION:
2634                         nocheck = true;
2635                         break;
2636                 case IMAGEX_HEADER_OPTION:
2637                         header = true;
2638                         short_header = false;
2639                         break;
2640                 case IMAGEX_LOOKUP_TABLE_OPTION:
2641                         lookup_table = true;
2642                         short_header = false;
2643                         break;
2644                 case IMAGEX_XML_OPTION:
2645                         xml = true;
2646                         short_header = false;
2647                         break;
2648                 case IMAGEX_EXTRACT_XML_OPTION:
2649                         xml_out_file = optarg;
2650                         short_header = false;
2651                         break;
2652                 case IMAGEX_METADATA_OPTION:
2653                         metadata = true;
2654                         short_header = false;
2655                         break;
2656                 default:
2657                         goto out_usage;
2658                 }
2659         }
2660
2661         argc -= optind;
2662         argv += optind;
2663         if (argc < 1 || argc > 4)
2664                 goto out_usage;
2665
2666         wimfile           = argv[0];
2667         image_num_or_name = (argc >= 2) ? argv[1] : T("all");
2668         new_name          = (argc >= 3) ? argv[2] : NULL;
2669         new_desc          = (argc >= 4) ? argv[3] : NULL;
2670
2671         if (check && nocheck) {
2672                 imagex_error(T("Can't specify both --check and --nocheck"));
2673                 goto out_err;
2674         }
2675
2676         if (check)
2677                 open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2678
2679         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2680         if (ret)
2681                 goto out;
2682
2683         wimlib_get_wim_info(wim, &info);
2684
2685         image = wimlib_resolve_image(wim, image_num_or_name);
2686         ret = WIMLIB_ERR_INVALID_IMAGE;
2687         if (image == WIMLIB_NO_IMAGE && tstrcmp(image_num_or_name, T("0"))) {
2688                 imagex_error(T("The image \"%"TS"\" does not exist in \"%"TS"\""),
2689                              image_num_or_name, wimfile);
2690                 if (boot) {
2691                         imagex_error(T("If you would like to set the boot "
2692                                        "index to 0, specify image \"0\" with "
2693                                        "the --boot flag."));
2694                 }
2695                 goto out_wimlib_free;
2696         }
2697
2698         if (boot && info.image_count == 0) {
2699                 imagex_error(T("--boot is meaningless on a WIM with no images"));
2700                 goto out_wimlib_free;
2701         }
2702
2703         if (image == WIMLIB_ALL_IMAGES && info.image_count > 1) {
2704                 if (boot) {
2705                         imagex_error(T("Cannot specify the --boot flag "
2706                                        "without specifying a specific "
2707                                        "image in a multi-image WIM"));
2708                         goto out_wimlib_free;
2709                 }
2710                 if (new_name) {
2711                         imagex_error(T("Cannot specify the NEW_NAME "
2712                                        "without specifying a specific "
2713                                        "image in a multi-image WIM"));
2714                         goto out_wimlib_free;
2715                 }
2716         }
2717
2718         /* Operations that print information are separated from operations that
2719          * recreate the WIM file. */
2720         if (!new_name && !boot) {
2721
2722                 /* Read-only operations */
2723
2724                 if (image == WIMLIB_NO_IMAGE) {
2725                         imagex_error(T("\"%"TS"\" is not a valid image in \"%"TS"\""),
2726                                      image_num_or_name, wimfile);
2727                         goto out_wimlib_free;
2728                 }
2729
2730                 if (image == WIMLIB_ALL_IMAGES && short_header)
2731                         print_wim_information(wimfile, &info);
2732
2733                 if (header)
2734                         wimlib_print_header(wim);
2735
2736                 if (lookup_table) {
2737                         if (info.total_parts != 1) {
2738                                 tfprintf(stderr, T("Warning: Only showing the lookup table "
2739                                                    "for part %d of a %d-part WIM.\n"),
2740                                          info.part_number, info.total_parts);
2741                         }
2742                         print_lookup_table(wim);
2743                 }
2744
2745                 if (xml) {
2746                         ret = wimlib_extract_xml_data(wim, stdout);
2747                         if (ret)
2748                                 goto out_wimlib_free;
2749                 }
2750
2751                 if (xml_out_file) {
2752                         FILE *fp;
2753
2754                         fp = tfopen(xml_out_file, T("wb"));
2755                         if (!fp) {
2756                                 imagex_error_with_errno(T("Failed to open the "
2757                                                           "file \"%"TS"\" for "
2758                                                           "writing"),
2759                                                         xml_out_file);
2760                                 ret = -1;
2761                                 goto out_wimlib_free;
2762                         }
2763                         ret = wimlib_extract_xml_data(wim, fp);
2764                         if (fclose(fp)) {
2765                                 imagex_error(T("Failed to close the file "
2766                                                "\"%"TS"\""),
2767                                              xml_out_file);
2768                                 ret = -1;
2769                         }
2770                         if (ret)
2771                                 goto out_wimlib_free;
2772                 }
2773
2774                 if (short_header)
2775                         wimlib_print_available_images(wim, image);
2776
2777                 if (metadata) {
2778                         ret = wimlib_print_metadata(wim, image);
2779                         if (ret)
2780                                 goto out_wimlib_free;
2781                 }
2782                 ret = 0;
2783         } else {
2784
2785                 /* Modification operations */
2786
2787                 if (image == WIMLIB_ALL_IMAGES)
2788                         image = 1;
2789
2790                 if (image == WIMLIB_NO_IMAGE && new_name) {
2791                         imagex_error(T("Cannot specify new_name (\"%"TS"\") "
2792                                        "when using image 0"), new_name);
2793                         ret = -1;
2794                         goto out_wimlib_free;
2795                 }
2796
2797                 if (boot) {
2798                         if (image == info.boot_index) {
2799                                 imagex_printf(T("Image %d is already marked as "
2800                                           "bootable.\n"), image);
2801                                 boot = false;
2802                         } else {
2803                                 imagex_printf(T("Marking image %d as bootable.\n"),
2804                                         image);
2805                                 info.boot_index = image;
2806                                 ret = wimlib_set_wim_info(wim, &info,
2807                                                           WIMLIB_CHANGE_BOOT_INDEX);
2808                                 if (ret)
2809                                         goto out_wimlib_free;
2810                         }
2811                 }
2812                 if (new_name) {
2813                         if (!tstrcmp(wimlib_get_image_name(wim, image), new_name))
2814                         {
2815                                 imagex_printf(T("Image %d is already named \"%"TS"\".\n"),
2816                                         image, new_name);
2817                                 new_name = NULL;
2818                         } else {
2819                                 imagex_printf(T("Changing the name of image %d to "
2820                                           "\"%"TS"\".\n"), image, new_name);
2821                                 ret = wimlib_set_image_name(wim, image, new_name);
2822                                 if (ret)
2823                                         goto out_wimlib_free;
2824                         }
2825                 }
2826                 if (new_desc) {
2827                         const tchar *old_desc;
2828                         old_desc = wimlib_get_image_description(wim, image);
2829                         if (old_desc && !tstrcmp(old_desc, new_desc)) {
2830                                 imagex_printf(T("The description of image %d is already "
2831                                           "\"%"TS"\".\n"), image, new_desc);
2832                                 new_desc = NULL;
2833                         } else {
2834                                 imagex_printf(T("Changing the description of image %d "
2835                                           "to \"%"TS"\".\n"), image, new_desc);
2836                                 ret = wimlib_set_image_descripton(wim, image,
2837                                                                   new_desc);
2838                                 if (ret)
2839                                         goto out_wimlib_free;
2840                         }
2841                 }
2842
2843                 /* Only call wimlib_overwrite() if something actually needs to
2844                  * be changed.  */
2845                 if (boot || new_name || new_desc ||
2846                     (check && !info.has_integrity_table) ||
2847                     (nocheck && info.has_integrity_table))
2848                 {
2849                         int write_flags = 0;
2850
2851                         if (check)
2852                                 write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2853                         if (nocheck)
2854                                 write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
2855                         ret = wimlib_overwrite(wim, write_flags, 1,
2856                                                imagex_progress_func);
2857                 } else {
2858                         imagex_printf(T("The file \"%"TS"\" was not modified "
2859                                         "because nothing needed to be done.\n"),
2860                                       wimfile);
2861                         ret = 0;
2862                 }
2863         }
2864 out_wimlib_free:
2865         wimlib_free(wim);
2866 out:
2867         return ret;
2868
2869 out_usage:
2870         usage(CMD_INFO, stderr);
2871 out_err:
2872         ret = -1;
2873         goto out;
2874 }
2875
2876 /* Join split WIMs into one part WIM */
2877 static int
2878 imagex_join(int argc, tchar **argv, int cmd)
2879 {
2880         int c;
2881         int swm_open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2882         int wim_write_flags = 0;
2883         const tchar *output_path;
2884         int ret;
2885
2886         for_opt(c, join_options) {
2887                 switch (c) {
2888                 case IMAGEX_CHECK_OPTION:
2889                         swm_open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2890                         wim_write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2891                         break;
2892                 default:
2893                         goto out_usage;
2894                 }
2895         }
2896         argc -= optind;
2897         argv += optind;
2898
2899         if (argc < 2) {
2900                 imagex_error(T("Must specify one or more split WIM (.swm) "
2901                                "parts to join"));
2902                 goto out_usage;
2903         }
2904         output_path = argv[0];
2905         ret = wimlib_join((const tchar * const *)++argv,
2906                           --argc,
2907                           output_path,
2908                           swm_open_flags,
2909                           wim_write_flags,
2910                           imagex_progress_func);
2911 out:
2912         return ret;
2913
2914 out_usage:
2915         usage(CMD_JOIN, stderr);
2916         ret = -1;
2917         goto out;
2918 }
2919
2920 #if WIM_MOUNTING_SUPPORTED
2921
2922 /* Mounts a WIM image.  */
2923 static int
2924 imagex_mount_rw_or_ro(int argc, tchar **argv, int cmd)
2925 {
2926         int c;
2927         int mount_flags = 0;
2928         int open_flags = WIMLIB_OPEN_FLAG_SPLIT_OK;
2929         const tchar *swm_glob = NULL;
2930         const tchar *staging_dir = NULL;
2931         const tchar *wimfile;
2932         const tchar *dir;
2933         WIMStruct *wim;
2934         int image;
2935         int ret;
2936         WIMStruct **additional_swms;
2937         unsigned num_additional_swms;
2938
2939         if (cmd == CMD_MOUNTRW) {
2940                 mount_flags |= WIMLIB_MOUNT_FLAG_READWRITE;
2941                 open_flags |= WIMLIB_OPEN_FLAG_WRITE_ACCESS;
2942         }
2943
2944         for_opt(c, mount_options) {
2945                 switch (c) {
2946                 case IMAGEX_ALLOW_OTHER_OPTION:
2947                         mount_flags |= WIMLIB_MOUNT_FLAG_ALLOW_OTHER;
2948                         break;
2949                 case IMAGEX_CHECK_OPTION:
2950                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
2951                         break;
2952                 case IMAGEX_DEBUG_OPTION:
2953                         mount_flags |= WIMLIB_MOUNT_FLAG_DEBUG;
2954                         break;
2955                 case IMAGEX_STREAMS_INTERFACE_OPTION:
2956                         if (!tstrcasecmp(optarg, T("none")))
2957                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_NONE;
2958                         else if (!tstrcasecmp(optarg, T("xattr")))
2959                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_XATTR;
2960                         else if (!tstrcasecmp(optarg, T("windows")))
2961                                 mount_flags |= WIMLIB_MOUNT_FLAG_STREAM_INTERFACE_WINDOWS;
2962                         else {
2963                                 imagex_error(T("Unknown stream interface \"%"TS"\""),
2964                                              optarg);
2965                                 goto out_usage;
2966                         }
2967                         break;
2968                 case IMAGEX_REF_OPTION:
2969                         swm_glob = optarg;
2970                         break;
2971                 case IMAGEX_STAGING_DIR_OPTION:
2972                         staging_dir = optarg;
2973                         break;
2974                 case IMAGEX_UNIX_DATA_OPTION:
2975                         mount_flags |= WIMLIB_MOUNT_FLAG_UNIX_DATA;
2976                         break;
2977                 default:
2978                         goto out_usage;
2979                 }
2980         }
2981         argc -= optind;
2982         argv += optind;
2983         if (argc != 2 && argc != 3)
2984                 goto out_usage;
2985
2986         wimfile = argv[0];
2987
2988         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
2989         if (ret)
2990                 goto out;
2991
2992         if (argc >= 3) {
2993                 /* Image explicitly specified.  */
2994                 image = wimlib_resolve_image(wim, argv[1]);
2995                 dir = argv[2];
2996                 ret = verify_image_exists_and_is_single(image, argv[1], wimfile);
2997                 if (ret)
2998                         goto out_free_wim;
2999         } else {
3000                 /* No image specified; default to image 1, but only if the WIM
3001                  * contains exactly one image.  */
3002                 struct wimlib_wim_info info;
3003
3004                 wimlib_get_wim_info(wim, &info);
3005                 if (info.image_count != 1) {
3006                         imagex_error(T("\"%"TS"\" contains %d images; Please "
3007                                        "select one."), wimfile, info.image_count);
3008                         wimlib_free(wim);
3009                         goto out_usage;
3010                 }
3011                 image = 1;
3012                 dir = argv[1];
3013         }
3014
3015         if (swm_glob) {
3016                 ret = open_swms_from_glob(swm_glob, wimfile, open_flags,
3017                                           &additional_swms,
3018                                           &num_additional_swms);
3019                 if (ret)
3020                         goto out_free_wim;
3021         } else {
3022                 additional_swms = NULL;
3023                 num_additional_swms = 0;
3024         }
3025
3026         ret = wimlib_mount_image(wim, image, dir, mount_flags, additional_swms,
3027                                  num_additional_swms, staging_dir);
3028         if (ret) {
3029                 imagex_error(T("Failed to mount image %d from \"%"TS"\" "
3030                                "on \"%"TS"\""),
3031                              image, wimfile, dir);
3032         }
3033         for (unsigned i = 0; i < num_additional_swms; i++)
3034                 wimlib_free(additional_swms[i]);
3035         free(additional_swms);
3036 out_free_wim:
3037         wimlib_free(wim);
3038 out:
3039         return ret;
3040
3041 out_usage:
3042         usage(cmd, stderr);
3043         ret = -1;
3044         goto out;
3045 }
3046 #endif /* WIM_MOUNTING_SUPPORTED */
3047
3048 /* Rebuild a WIM file */
3049 static int
3050 imagex_optimize(int argc, tchar **argv, int cmd)
3051 {
3052         int c;
3053         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3054         int write_flags = WIMLIB_WRITE_FLAG_REBUILD;
3055         int ret;
3056         WIMStruct *wim;
3057         const tchar *wimfile;
3058         off_t old_size;
3059         off_t new_size;
3060         unsigned num_threads = 0;
3061
3062         for_opt(c, optimize_options) {
3063                 switch (c) {
3064                 case IMAGEX_CHECK_OPTION:
3065                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3066                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3067                         break;
3068                 case IMAGEX_NOCHECK_OPTION:
3069                         write_flags |= WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY;
3070                         break;
3071                 case IMAGEX_RECOMPRESS_OPTION:
3072                         write_flags |= WIMLIB_WRITE_FLAG_RECOMPRESS;
3073                         break;
3074                 case IMAGEX_THREADS_OPTION:
3075                         num_threads = parse_num_threads(optarg);
3076                         if (num_threads == UINT_MAX)
3077                                 goto out_err;
3078                         break;
3079                 case IMAGEX_PIPABLE_OPTION:
3080                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
3081                         break;
3082                 case IMAGEX_NOT_PIPABLE_OPTION:
3083                         write_flags |= WIMLIB_WRITE_FLAG_NOT_PIPABLE;
3084                         break;
3085                 default:
3086                         goto out_usage;
3087                 }
3088         }
3089         argc -= optind;
3090         argv += optind;
3091
3092         if (argc != 1)
3093                 goto out_usage;
3094
3095         wimfile = argv[0];
3096
3097         ret = wimlib_open_wim(wimfile, open_flags, &wim, imagex_progress_func);
3098         if (ret)
3099                 goto out;
3100
3101         old_size = file_get_size(wimfile);
3102         tprintf(T("\"%"TS"\" original size: "), wimfile);
3103         if (old_size == -1)
3104                 tputs(T("Unknown"));
3105         else
3106                 tprintf(T("%"PRIu64" KiB\n"), old_size >> 10);
3107
3108         ret = wimlib_overwrite(wim, write_flags, num_threads,
3109                                imagex_progress_func);
3110         if (ret) {
3111                 imagex_error(T("Optimization of \"%"TS"\" failed."), wimfile);
3112                 goto out_wimlib_free;
3113         }
3114
3115         new_size = file_get_size(wimfile);
3116         tprintf(T("\"%"TS"\" optimized size: "), wimfile);
3117         if (new_size == -1)
3118                 tputs(T("Unknown"));
3119         else
3120                 tprintf(T("%"PRIu64" KiB\n"), new_size >> 10);
3121
3122         tfputs(T("Space saved: "), stdout);
3123         if (new_size != -1 && old_size != -1) {
3124                 tprintf(T("%lld KiB\n"),
3125                        ((long long)old_size - (long long)new_size) >> 10);
3126         } else {
3127                 tputs(T("Unknown"));
3128         }
3129         ret = 0;
3130 out_wimlib_free:
3131         wimlib_free(wim);
3132 out:
3133         return ret;
3134
3135 out_usage:
3136         usage(CMD_OPTIMIZE, stderr);
3137 out_err:
3138         ret = -1;
3139         goto out;
3140 }
3141
3142 /* Split a WIM into a spanned set */
3143 static int
3144 imagex_split(int argc, tchar **argv, int cmd)
3145 {
3146         int c;
3147         int open_flags = 0;
3148         int write_flags = 0;
3149         unsigned long part_size;
3150         tchar *tmp;
3151         int ret;
3152         WIMStruct *wim;
3153
3154         for_opt(c, split_options) {
3155                 switch (c) {
3156                 case IMAGEX_CHECK_OPTION:
3157                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3158                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3159                         break;
3160                 default:
3161                         goto out_usage;
3162                 }
3163         }
3164         argc -= optind;
3165         argv += optind;
3166
3167         if (argc != 3)
3168                 goto out_usage;
3169
3170         part_size = tstrtod(argv[2], &tmp) * (1 << 20);
3171         if (tmp == argv[2] || *tmp) {
3172                 imagex_error(T("Invalid part size \"%"TS"\""), argv[2]);
3173                 imagex_error(T("The part size must be an integer or "
3174                                "floating-point number of megabytes."));
3175                 goto out_err;
3176         }
3177         ret = wimlib_open_wim(argv[0], open_flags, &wim, imagex_progress_func);
3178         if (ret)
3179                 goto out;
3180
3181         ret = wimlib_split(wim, argv[1], part_size, write_flags, imagex_progress_func);
3182         wimlib_free(wim);
3183 out:
3184         return ret;
3185
3186 out_usage:
3187         usage(CMD_SPLIT, stderr);
3188 out_err:
3189         ret = -1;
3190         goto out;
3191 }
3192
3193 #if WIM_MOUNTING_SUPPORTED
3194 /* Unmounts a mounted WIM image. */
3195 static int
3196 imagex_unmount(int argc, tchar **argv, int cmd)
3197 {
3198         int c;
3199         int unmount_flags = 0;
3200         int ret;
3201
3202         for_opt(c, unmount_options) {
3203                 switch (c) {
3204                 case IMAGEX_COMMIT_OPTION:
3205                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_COMMIT;
3206                         break;
3207                 case IMAGEX_CHECK_OPTION:
3208                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_CHECK_INTEGRITY;
3209                         break;
3210                 case IMAGEX_REBUILD_OPTION:
3211                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_REBUILD;
3212                         break;
3213                 case IMAGEX_LAZY_OPTION:
3214                         unmount_flags |= WIMLIB_UNMOUNT_FLAG_LAZY;
3215                         break;
3216                 default:
3217                         goto out_usage;
3218                 }
3219         }
3220         argc -= optind;
3221         argv += optind;
3222         if (argc != 1)
3223                 goto out_usage;
3224
3225         ret = wimlib_unmount_image(argv[0], unmount_flags,
3226                                    imagex_progress_func);
3227         if (ret)
3228                 imagex_error(T("Failed to unmount \"%"TS"\""), argv[0]);
3229 out:
3230         return ret;
3231
3232 out_usage:
3233         usage(CMD_UNMOUNT, stderr);
3234         ret = -1;
3235         goto out;
3236 }
3237 #endif /* WIM_MOUNTING_SUPPORTED */
3238
3239 /*
3240  * Add, delete, or rename files in a WIM image.
3241  */
3242 static int
3243 imagex_update(int argc, tchar **argv, int cmd)
3244 {
3245         const tchar *wimfile;
3246         int image;
3247         WIMStruct *wim;
3248         int ret;
3249         int open_flags = WIMLIB_OPEN_FLAG_WRITE_ACCESS;
3250         int write_flags = 0;
3251         int update_flags = WIMLIB_UPDATE_FLAG_SEND_PROGRESS;
3252         int default_add_flags = WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE |
3253                                 WIMLIB_ADD_FLAG_WINCONFIG;
3254         int default_delete_flags = 0;
3255         unsigned num_threads = 0;
3256         int c;
3257         tchar *cmd_file_contents;
3258         size_t cmd_file_nchars;
3259         struct wimlib_update_command *cmds;
3260         size_t num_cmds;
3261         tchar *command_str = NULL;
3262
3263         const tchar *config_file = NULL;
3264         tchar *config_str;
3265         struct wimlib_capture_config *config;
3266
3267         for_opt(c, update_options) {
3268                 switch (c) {
3269                 /* Generic or write options */
3270                 case IMAGEX_THREADS_OPTION:
3271                         num_threads = parse_num_threads(optarg);
3272                         if (num_threads == UINT_MAX)
3273                                 goto out_err;
3274                         break;
3275                 case IMAGEX_CHECK_OPTION:
3276                         open_flags |= WIMLIB_OPEN_FLAG_CHECK_INTEGRITY;
3277                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
3278                &nb