]> wimlib.net Git - wimlib/blob - src/capture_common.c
8279497113280b9a82e53882ceee0d08ce9a802a
[wimlib] / src / capture_common.c
1 /*
2  * capture_common.c - Mostly code to handle excluding paths from capture.
3  */
4
5 /*
6  * Copyright (C) 2013, 2014 Eric Biggers
7  *
8  * This file is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU Lesser General Public License as published by the Free
10  * Software Foundation; either version 3 of the License, or (at your option) any
11  * later version.
12  *
13  * This file is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this file; if not, see http://www.gnu.org/licenses/.
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #  include "config.h"
24 #endif
25
26 #include <string.h>
27
28 #include "wimlib/blob_table.h"
29 #include "wimlib/capture.h"
30 #include "wimlib/dentry.h"
31 #include "wimlib/error.h"
32 #include "wimlib/paths.h"
33 #include "wimlib/pattern.h"
34 #include "wimlib/progress.h"
35 #include "wimlib/textfile.h"
36
37 /*
38  * Tally a file (or directory) that has been scanned for a capture operation,
39  * and possibly call the progress function provided by the library user.
40  *
41  * @params
42  *      Flags, optional progress function, and progress data for the capture
43  *      operation.
44  * @status
45  *      Status of the scanned file.
46  * @inode
47  *      If @status is WIMLIB_SCAN_DENTRY_OK, this is a pointer to the WIM inode
48  *      that has been created for the scanned file.  The first time the file is
49  *      seen, inode->i_nlink will be 1.  On subsequent visits of the same inode
50  *      via additional hard links, inode->i_nlink will be greater than 1.
51  */
52 int
53 do_capture_progress(struct capture_params *params, int status,
54                     const struct wim_inode *inode)
55 {
56         switch (status) {
57         case WIMLIB_SCAN_DENTRY_OK:
58                 if (!(params->add_flags & WIMLIB_ADD_FLAG_VERBOSE))
59                         return 0;
60                 break;
61         case WIMLIB_SCAN_DENTRY_UNSUPPORTED:
62         case WIMLIB_SCAN_DENTRY_EXCLUDED:
63         case WIMLIB_SCAN_DENTRY_FIXED_SYMLINK:
64         case WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK:
65                 if (!(params->add_flags & WIMLIB_ADD_FLAG_EXCLUDE_VERBOSE))
66                         return 0;
67                 break;
68         }
69         params->progress.scan.status = status;
70         if (status == WIMLIB_SCAN_DENTRY_OK) {
71
72                 /* The first time the inode is seen, tally all its streams.  */
73                 if (inode->i_nlink == 1) {
74                         for (unsigned i = 0; i < inode->i_num_streams; i++) {
75                                 const struct blob_descriptor *blob =
76                                         stream_blob_resolved(&inode->i_streams[i]);
77                                 if (blob)
78                                         params->progress.scan.num_bytes_scanned += blob->size;
79                         }
80                 }
81
82                 /* Tally the file itself, counting every hard link.  It's
83                  * debatable whether every link should be counted, but counting
84                  * every link makes the statistics consistent with the ones
85                  * placed in the FILECOUNT and DIRCOUNT elements of the WIM
86                  * file's XML document.  It also avoids possible user confusion
87                  * if the number of files reported were to be lower than that
88                  * displayed by some other software such as file browsers.  */
89                 if (inode_is_directory(inode))
90                         params->progress.scan.num_dirs_scanned++;
91                 else
92                         params->progress.scan.num_nondirs_scanned++;
93         }
94
95         /* Call the user-provided progress function.  */
96         return call_progress(params->progfunc, WIMLIB_PROGRESS_MSG_SCAN_DENTRY,
97                              &params->progress, params->progctx);
98 }
99
100 /*
101  * Given a null-terminated pathname pattern @pat that has been read from line
102  * @line_no of the file @path, validate and canonicalize the pattern.
103  *
104  * On success, returns 0.
105  * On failure, returns WIMLIB_ERR_INVALID_CAPTURE_CONFIG.
106  * In either case, @pat may have been modified in-place (and possibly
107  * shortened).
108  */
109 int
110 mangle_pat(tchar *pat, const tchar *path, unsigned long line_no)
111 {
112         if (!is_any_path_separator(pat[0]) &&
113             pat[0] != T('\0') && pat[1] == T(':'))
114         {
115                 /* Pattern begins with drive letter.  */
116
117                 if (!is_any_path_separator(pat[2])) {
118                         /* Something like c:file, which is actually a path
119                          * relative to the current working directory on the c:
120                          * drive.  We require paths with drive letters to be
121                          * absolute.  */
122                         ERROR("%"TS":%lu: Invalid pattern \"%"TS"\":\n"
123                               "        Patterns including drive letters must be absolute!\n"
124                               "        Maybe try \"%"TC":%"TC"%"TS"\"?\n",
125                               path, line_no, pat,
126                               pat[0], OS_PREFERRED_PATH_SEPARATOR, &pat[2]);
127                         return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
128                 }
129
130                 WARNING("%"TS":%lu: Pattern \"%"TS"\" starts with a drive "
131                         "letter, which is being removed.",
132                         path, line_no, pat);
133
134                 /* Strip the drive letter.  */
135                 tmemmove(pat, pat + 2, tstrlen(pat + 2) + 1);
136         }
137
138         /* Collapse consecutive path separators, and translate both / and \ into
139          * / (UNIX) or \ (Windows).
140          *
141          * Note: we expect that this function produces patterns that can be used
142          * for both filesystem paths and WIM paths, so the desired path
143          * separators must be the same.  */
144         STATIC_ASSERT(OS_PREFERRED_PATH_SEPARATOR == WIM_PATH_SEPARATOR);
145         do_canonicalize_path(pat, pat);
146
147         /* Relative patterns can only match file names, so they must be
148          * single-component only.  */
149         if (pat[0] != OS_PREFERRED_PATH_SEPARATOR &&
150             tstrchr(pat, OS_PREFERRED_PATH_SEPARATOR))
151         {
152                 ERROR("%"TS":%lu: Invalid pattern \"%"TS"\":\n"
153                       "        Relative patterns can only include one path component!\n"
154                       "        Maybe try \"%"TC"%"TS"\"?",
155                       path, line_no, pat, OS_PREFERRED_PATH_SEPARATOR, pat);
156                 return WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
157         }
158
159         return 0;
160 }
161
162 /*
163  * Read, parse, and validate a capture configuration file from either an on-disk
164  * file or an in-memory buffer.
165  *
166  * To read from a file, specify @config_file, and use NULL for @buf.
167  * To read from a buffer, specify @buf and @bufsize.
168  *
169  * @config must be initialized to all 0's.
170  *
171  * On success, 0 will be returned, and the resulting capture configuration will
172  * be stored in @config.
173  *
174  * On failure, a positive error code will be returned, and the contents of
175  * @config will be invalidated.
176  */
177 int
178 read_capture_config(const tchar *config_file, const void *buf,
179                     size_t bufsize, struct capture_config *config)
180 {
181         int ret;
182
183         /* [PrepopulateList] is used for apply, not capture.  But since we do
184          * understand it, recognize it, thereby avoiding the unrecognized
185          * section warning, but discard the resulting strings.
186          *
187          * We currently ignore [CompressionExclusionList] and
188          * [CompressionFolderList].  This is a known issue that doesn't seem to
189          * have any real consequences, so don't issue warnings about not
190          * recognizing those sections.  */
191         STRING_SET(prepopulate_pats);
192         STRING_SET(compression_exclusion_pats);
193         STRING_SET(compression_folder_pats);
194
195         struct text_file_section sections[] = {
196                 {T("ExclusionList"),
197                         &config->exclusion_pats},
198                 {T("ExclusionException"),
199                         &config->exclusion_exception_pats},
200                 {T("PrepopulateList"),
201                         &prepopulate_pats},
202                 {T("CompressionExclusionList"),
203                         &compression_exclusion_pats},
204                 {T("CompressionFolderList"),
205                         &compression_folder_pats},
206         };
207         void *mem;
208
209         ret = do_load_text_file(config_file, buf, bufsize, &mem,
210                                 sections, ARRAY_LEN(sections),
211                                 LOAD_TEXT_FILE_REMOVE_QUOTES, mangle_pat);
212         if (ret) {
213                 ERROR("Failed to load capture configuration file \"%"TS"\"",
214                       config_file);
215                 switch (ret) {
216                 case WIMLIB_ERR_INVALID_UTF8_STRING:
217                 case WIMLIB_ERR_INVALID_UTF16_STRING:
218                         ERROR("Note: the capture configuration file must be "
219                               "valid UTF-8 or UTF-16LE");
220                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
221                         break;
222                 case WIMLIB_ERR_OPEN:
223                 case WIMLIB_ERR_STAT:
224                 case WIMLIB_ERR_NOMEM:
225                 case WIMLIB_ERR_READ:
226                         ret = WIMLIB_ERR_UNABLE_TO_READ_CAPTURE_CONFIG;
227                         break;
228                 }
229                 return ret;
230         }
231
232         FREE(prepopulate_pats.strings);
233         FREE(compression_exclusion_pats.strings);
234         FREE(compression_folder_pats.strings);
235
236         config->buf = mem;
237         return 0;
238 }
239
240 void
241 destroy_capture_config(struct capture_config *config)
242 {
243         FREE(config->exclusion_pats.strings);
244         FREE(config->exclusion_exception_pats.strings);
245         FREE(config->buf);
246 }
247
248 /*
249  * Determine whether @path, or any ancestor directory of @path, matches any of
250  * the patterns in @list.  Path separators in @path must be WIM_PATH_SEPARATOR.
251  */
252 bool
253 match_pattern_list(const tchar *path, const struct string_set *list)
254 {
255         for (size_t i = 0; i < list->num_strings; i++)
256                 if (match_path(path, list->strings[i], true))
257                         return true;
258         return false;
259 }
260
261 /*
262  * Determine if a file should be excluded from capture.
263  *
264  * This function tests exclusions from both possible sources of exclusions:
265  *
266  *      (1) The capture configuration file
267  *      (2) The user-provided progress function
268  *
269  * The capture implementation must have set params->capture_root_nchars to an
270  * appropriate value.  Example for UNIX:  if the capture root directory is
271  * "foobar/subdir", then all paths will be provided starting with
272  * "foobar/subdir", so params->capture_root_nchars must be set to
273  * strlen("foobar/subdir") so that the appropriate path can be matched against
274  * the patterns in the exclusion list.
275  *
276  * Returns:
277  *      < 0 if excluded
278  *      = 0 if not excluded and no error
279  *      > 0 (wimlib error code) if error
280  */
281 int
282 try_exclude(const tchar *full_path, const struct capture_params *params)
283 {
284         int ret;
285
286         if (params->config) {
287                 const tchar *path = full_path + params->capture_root_nchars;
288                 if (match_pattern_list(path, &params->config->exclusion_pats) &&
289                     !match_pattern_list(path, &params->config->exclusion_exception_pats))
290                         return -1;
291         }
292
293         if (unlikely(params->add_flags & WIMLIB_ADD_FLAG_TEST_FILE_EXCLUSION)) {
294
295                 union wimlib_progress_info info;
296                 tchar *cookie;
297
298                 info.test_file_exclusion.path = full_path;
299                 info.test_file_exclusion.will_exclude = false;
300
301                 cookie = progress_get_win32_path(full_path);
302
303                 ret = call_progress(params->progfunc, WIMLIB_PROGRESS_MSG_TEST_FILE_EXCLUSION,
304                                     &info, params->progctx);
305
306                 progress_put_win32_path(cookie);
307
308                 if (ret)
309                         return ret;
310                 if (info.test_file_exclusion.will_exclude)
311                         return -1;
312         }
313
314         return 0;
315 }
316
317 /*
318  * Determine whether a directory entry of the specified name should be ignored.
319  * This is a lower level function which runs prior to try_exclude().  It handles
320  * the standard '.' and '..' entries, which show up in directory listings but
321  * should not be archived.  It also checks for odd filenames that usually should
322  * not exist but could cause problems if archiving them were to be attempted.
323  */
324 bool
325 should_ignore_filename(const tchar *name, const int name_nchars)
326 {
327         if (name_nchars <= 0) {
328                 WARNING("Ignoring empty filename");
329                 return true;
330         }
331
332         if (name[0] == T('.') &&
333             (name_nchars == 1 || (name_nchars == 2 && name[1] == T('.'))))
334                 return true;
335
336         for (int i = 0; i < name_nchars; i++) {
337                 if (name[i] == T('\0')) {
338                         WARNING("Ignoring filename containing embedded null character");
339                         return true;
340                 }
341                 if (name[i] == OS_PREFERRED_PATH_SEPARATOR) {
342                         WARNING("Ignoring filename containing embedded path separator");
343                         return true;
344                 }
345         }
346
347         return false;
348 }
349
350 /* Attach a newly scanned directory tree to its parent directory, with duplicate
351  * handling.  */
352 void
353 attach_scanned_tree(struct wim_dentry *parent, struct wim_dentry *child,
354                     struct blob_table *blob_table)
355 {
356         struct wim_dentry *duplicate;
357
358         if (child && (duplicate = dentry_add_child(parent, child))) {
359                 WARNING("Duplicate file path: \"%"TS"\".  Only capturing "
360                         "the first version.", dentry_full_path(duplicate));
361                 free_dentry_tree(child, blob_table);
362         }
363 }