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