1 /*
2  * win32_capture.c - Windows-specific code for capturing files into a WIM image.
3  *
4  * This now uses the native Windows NT API a lot and not just Win32.
5  */
6 
7 /*
8  * Copyright (C) 2013-2018 Eric Biggers
9  *
10  * This file is free software; you can redistribute it and/or modify it under
11  * the terms of the GNU Lesser General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option) any
13  * later version.
14  *
15  * This file is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this file; if not, see http://www.gnu.org/licenses/.
22  */
23 
24 #ifdef __WIN32__
25 
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29 
30 #include "wimlib/win32_common.h"
31 
32 #include "wimlib/assert.h"
33 #include "wimlib/blob_table.h"
34 #include "wimlib/dentry.h"
35 #include "wimlib/encoding.h"
36 #include "wimlib/endianness.h"
37 #include "wimlib/error.h"
38 #include "wimlib/object_id.h"
39 #include "wimlib/paths.h"
40 #include "wimlib/reparse.h"
41 #include "wimlib/scan.h"
42 #include "wimlib/win32_vss.h"
43 #include "wimlib/wof.h"
44 #include "wimlib/xattr.h"
45 
46 struct winnt_scan_ctx {
47 	struct scan_params *params;
48 	bool is_ntfs;
49 	u32 vol_flags;
50 	unsigned long num_get_sd_access_denied;
51 	unsigned long num_get_sacl_priv_notheld;
52 
53 	/* True if WOF is definitely not attached to the volume being scanned;
54 	 * false if it may be  */
55 	bool wof_not_attached;
56 
57 	/* A reference to the VSS snapshot being used, or NULL if none  */
58 	struct vss_snapshot *snapshot;
59 };
60 
61 static inline const wchar_t *
printable_path(const struct winnt_scan_ctx * ctx)62 printable_path(const struct winnt_scan_ctx *ctx)
63 {
64 	/* Skip over \\?\ or \??\  */
65 	return ctx->params->cur_path + 4;
66 }
67 
68 /* Description of where data is located on a Windows filesystem  */
69 struct windows_file {
70 
71 	/* Is the data the raw encrypted data of an EFS-encrypted file?  */
72 	u64 is_encrypted : 1;
73 
74 	/* Is this file "open by file ID" rather than the regular "open by
75 	 * path"?  "Open by file ID" uses resources more efficiently.  */
76 	u64 is_file_id : 1;
77 
78 	/* The file's LCN (logical cluster number) for sorting, or 0 if unknown.
79 	 */
80 	u64 sort_key : 62;
81 
82 	/* Length of the path in bytes, excluding the null terminator if
83 	 * present.  */
84 	size_t path_nbytes;
85 
86 	/* A reference to the VSS snapshot containing the file, or NULL if none.
87 	 */
88 	struct vss_snapshot *snapshot;
89 
90 	/* The path to the file.  If 'is_encrypted=0' this is an NT namespace
91 	 * path; if 'is_encrypted=1' this is a Win32 namespace path.  If
92 	 * 'is_file_id=0', then the path is null-terminated.  If 'is_file_id=1'
93 	 * (only allowed with 'is_encrypted=0') the path ends with a binary file
94 	 * ID and may not be null-terminated.  */
95 	wchar_t path[0];
96 };
97 
98 /* Allocate a structure to describe the location of a data stream by path.  */
99 static struct windows_file *
alloc_windows_file(const wchar_t * path,size_t path_nchars,const wchar_t * stream_name,size_t stream_name_nchars,struct vss_snapshot * snapshot,bool is_encrypted)100 alloc_windows_file(const wchar_t *path, size_t path_nchars,
101 		   const wchar_t *stream_name, size_t stream_name_nchars,
102 		   struct vss_snapshot *snapshot, bool is_encrypted)
103 {
104 	size_t full_path_nbytes;
105 	struct windows_file *file;
106 	wchar_t *p;
107 
108 	full_path_nbytes = path_nchars * sizeof(wchar_t);
109 	if (stream_name_nchars)
110 		full_path_nbytes += (1 + stream_name_nchars) * sizeof(wchar_t);
111 
112 	file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
113 		      sizeof(wchar_t));
114 	if (!file)
115 		return NULL;
116 
117 	file->is_encrypted = is_encrypted;
118 	file->is_file_id = 0;
119 	file->sort_key = 0;
120 	file->path_nbytes = full_path_nbytes;
121 	file->snapshot = vss_get_snapshot(snapshot);
122 	p = wmempcpy(file->path, path, path_nchars);
123 	if (stream_name_nchars) {
124 		/* Named data stream  */
125 		*p++ = L':';
126 		p = wmempcpy(p, stream_name, stream_name_nchars);
127 	}
128 	*p = L'\0';
129 	return file;
130 }
131 
132 /* Allocate a structure to describe the location of a file by ID.  */
133 static struct windows_file *
alloc_windows_file_for_file_id(u64 file_id,const wchar_t * root_path,size_t root_path_nchars,struct vss_snapshot * snapshot)134 alloc_windows_file_for_file_id(u64 file_id, const wchar_t *root_path,
135 			       size_t root_path_nchars,
136 			       struct vss_snapshot *snapshot)
137 {
138 	size_t full_path_nbytes;
139 	struct windows_file *file;
140 	wchar_t *p;
141 
142 	full_path_nbytes = (root_path_nchars * sizeof(wchar_t)) +
143 			   sizeof(file_id);
144 	file = MALLOC(sizeof(struct windows_file) + full_path_nbytes +
145 		      sizeof(wchar_t));
146 	if (!file)
147 		return NULL;
148 
149 	file->is_encrypted = 0;
150 	file->is_file_id = 1;
151 	file->sort_key = 0;
152 	file->path_nbytes = full_path_nbytes;
153 	file->snapshot = vss_get_snapshot(snapshot);
154 	p = wmempcpy(file->path, root_path, root_path_nchars);
155 	p = mempcpy(p, &file_id, sizeof(file_id));
156 	*p = L'\0';
157 	return file;
158 }
159 
160 /* Add a stream, located on a Windows filesystem, to the specified WIM inode. */
161 static int
add_stream(struct wim_inode * inode,struct windows_file * windows_file,u64 stream_size,int stream_type,const utf16lechar * stream_name,struct list_head * unhashed_blobs)162 add_stream(struct wim_inode *inode, struct windows_file *windows_file,
163 	   u64 stream_size, int stream_type, const utf16lechar *stream_name,
164 	   struct list_head *unhashed_blobs)
165 {
166 	struct blob_descriptor *blob = NULL;
167 	struct wim_inode_stream *strm;
168 	int ret;
169 
170 	if (!windows_file)
171 		goto err_nomem;
172 
173 	/* If the stream is nonempty, create a blob descriptor for it.  */
174 	if (stream_size) {
175 		blob = new_blob_descriptor();
176 		if (!blob)
177 			goto err_nomem;
178 		blob->windows_file = windows_file;
179 		blob->blob_location = BLOB_IN_WINDOWS_FILE;
180 		blob->file_inode = inode;
181 		blob->size = stream_size;
182 		windows_file = NULL;
183 	}
184 
185 	strm = inode_add_stream(inode, stream_type, stream_name, blob);
186 	if (!strm)
187 		goto err_nomem;
188 
189 	prepare_unhashed_blob(blob, inode, strm->stream_id, unhashed_blobs);
190 	ret = 0;
191 out:
192 	if (windows_file)
193 		free_windows_file(windows_file);
194 	return ret;
195 
196 err_nomem:
197 	free_blob_descriptor(blob);
198 	ret = WIMLIB_ERR_NOMEM;
199 	goto out;
200 }
201 
202 struct windows_file *
clone_windows_file(const struct windows_file * file)203 clone_windows_file(const struct windows_file *file)
204 {
205 	struct windows_file *new;
206 
207 	new = memdup(file, sizeof(*file) + file->path_nbytes + sizeof(wchar_t));
208 	if (new)
209 		vss_get_snapshot(new->snapshot);
210 	return new;
211 }
212 
213 void
free_windows_file(struct windows_file * file)214 free_windows_file(struct windows_file *file)
215 {
216 	vss_put_snapshot(file->snapshot);
217 	FREE(file);
218 }
219 
220 int
cmp_windows_files(const struct windows_file * file1,const struct windows_file * file2)221 cmp_windows_files(const struct windows_file *file1,
222 		  const struct windows_file *file2)
223 {
224 	/* Compare by starting LCN (logical cluster number)  */
225 	int v = cmp_u64(file1->sort_key, file2->sort_key);
226 	if (v)
227 		return v;
228 
229 	/* Fall back to comparing files by path (arbitrary heuristic).  */
230 	v = memcmp(file1->path, file2->path,
231 		   min(file1->path_nbytes, file2->path_nbytes));
232 	if (v)
233 		return v;
234 
235 	return cmp_u32(file1->path_nbytes, file2->path_nbytes);
236 }
237 
238 const wchar_t *
get_windows_file_path(const struct windows_file * file)239 get_windows_file_path(const struct windows_file *file)
240 {
241 	return file->path;
242 }
243 
244 /*
245  * Open the file named by the NT namespace path @path of length @path_nchars
246  * characters.  If @cur_dir is not NULL then the path is given relative to
247  * @cur_dir; otherwise the path is absolute.  @perms is the access mask of
248  * permissions to request on the handle.  SYNCHRONIZE permision is always added.
249  */
250 static NTSTATUS
winnt_openat(HANDLE cur_dir,const wchar_t * path,size_t path_nchars,ACCESS_MASK perms,HANDLE * h_ret)251 winnt_openat(HANDLE cur_dir, const wchar_t *path, size_t path_nchars,
252 	     ACCESS_MASK perms, HANDLE *h_ret)
253 {
254 	UNICODE_STRING name = {
255 		.Length = path_nchars * sizeof(wchar_t),
256 		.MaximumLength = path_nchars * sizeof(wchar_t),
257 		.Buffer = (wchar_t *)path,
258 	};
259 	OBJECT_ATTRIBUTES attr = {
260 		.Length = sizeof(attr),
261 		.RootDirectory = cur_dir,
262 		.ObjectName = &name,
263 	};
264 	IO_STATUS_BLOCK iosb;
265 	NTSTATUS status;
266 	ULONG options = FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT;
267 
268 	perms |= SYNCHRONIZE;
269 	if (perms & (FILE_READ_DATA | FILE_LIST_DIRECTORY)) {
270 		options |= FILE_SYNCHRONOUS_IO_NONALERT;
271 		options |= FILE_SEQUENTIAL_ONLY;
272 	}
273 retry:
274 	status = NtOpenFile(h_ret, perms, &attr, &iosb,
275 			    FILE_SHARE_VALID_FLAGS, options);
276 	if (!NT_SUCCESS(status)) {
277 		/* Try requesting fewer permissions  */
278 		if (status == STATUS_ACCESS_DENIED ||
279 		    status == STATUS_PRIVILEGE_NOT_HELD) {
280 			if (perms & ACCESS_SYSTEM_SECURITY) {
281 				perms &= ~ACCESS_SYSTEM_SECURITY;
282 				goto retry;
283 			}
284 			if (perms & READ_CONTROL) {
285 				perms &= ~READ_CONTROL;
286 				goto retry;
287 			}
288 		}
289 	}
290 	return status;
291 }
292 
293 static NTSTATUS
winnt_open(const wchar_t * path,size_t path_nchars,ACCESS_MASK perms,HANDLE * h_ret)294 winnt_open(const wchar_t *path, size_t path_nchars, ACCESS_MASK perms,
295 	   HANDLE *h_ret)
296 {
297 	return winnt_openat(NULL, path, path_nchars, perms, h_ret);
298 }
299 
300 static const wchar_t *
windows_file_to_string(const struct windows_file * file,u8 * buf,size_t bufsize)301 windows_file_to_string(const struct windows_file *file, u8 *buf, size_t bufsize)
302 {
303 	if (file->is_file_id) {
304 		u64 file_id;
305 		memcpy(&file_id,
306 		       (u8 *)file->path + file->path_nbytes - sizeof(file_id),
307 		       sizeof(file_id));
308 		swprintf((wchar_t *)buf, L"NTFS inode 0x%016"PRIx64, file_id);
309 	} else if (file->path_nbytes + 3 * sizeof(wchar_t) <= bufsize) {
310 		swprintf((wchar_t *)buf, L"\"%ls\"", file->path);
311 	} else {
312 		return L"(name too long)";
313 	}
314 	return (wchar_t *)buf;
315 }
316 
317 static int
read_winnt_stream_prefix(const struct windows_file * file,u64 size,const struct consume_chunk_callback * cb)318 read_winnt_stream_prefix(const struct windows_file *file,
319 			 u64 size, const struct consume_chunk_callback *cb)
320 {
321 	IO_STATUS_BLOCK iosb;
322 	UNICODE_STRING name = {
323 		.Buffer = (wchar_t *)file->path,
324 		.Length = file->path_nbytes,
325 		.MaximumLength = file->path_nbytes,
326 	};
327 	OBJECT_ATTRIBUTES attr = {
328 		.Length = sizeof(attr),
329 		.ObjectName = &name,
330 	};
331 	HANDLE h;
332 	NTSTATUS status;
333 	u8 buf[BUFFER_SIZE] _aligned_attribute(8);
334 	u64 bytes_remaining;
335 	int ret;
336 
337 	status = NtOpenFile(&h, FILE_READ_DATA | SYNCHRONIZE,
338 			    &attr, &iosb,
339 			    FILE_SHARE_VALID_FLAGS,
340 			    FILE_OPEN_REPARSE_POINT |
341 				FILE_OPEN_FOR_BACKUP_INTENT |
342 				FILE_SYNCHRONOUS_IO_NONALERT |
343 				FILE_SEQUENTIAL_ONLY |
344 				(file->is_file_id ? FILE_OPEN_BY_FILE_ID : 0));
345 	if (unlikely(!NT_SUCCESS(status))) {
346 		if (status == STATUS_SHARING_VIOLATION) {
347 			ERROR("Can't open %ls for reading:\n"
348 			      "        File is in use by another process! "
349 			      "Consider using snapshot (VSS) mode.",
350 			      windows_file_to_string(file, buf, sizeof(buf)));
351 		} else {
352 			winnt_error(status, L"Can't open %ls for reading",
353 				    windows_file_to_string(file, buf, sizeof(buf)));
354 		}
355 		return WIMLIB_ERR_OPEN;
356 	}
357 
358 	ret = 0;
359 	bytes_remaining = size;
360 	while (bytes_remaining) {
361 		IO_STATUS_BLOCK iosb;
362 		ULONG count;
363 		ULONG bytes_read;
364 		const unsigned max_tries = 5;
365 		unsigned tries_remaining = max_tries;
366 
367 		count = min(sizeof(buf), bytes_remaining);
368 
369 	retry_read:
370 		status = NtReadFile(h, NULL, NULL, NULL,
371 				    &iosb, buf, count, NULL, NULL);
372 		if (unlikely(!NT_SUCCESS(status))) {
373 			if (status == STATUS_END_OF_FILE) {
374 				ERROR("%ls: File was concurrently truncated",
375 				      windows_file_to_string(file, buf, sizeof(buf)));
376 				ret = WIMLIB_ERR_CONCURRENT_MODIFICATION_DETECTED;
377 			} else {
378 				winnt_warning(status, L"Error reading data from %ls",
379 					      windows_file_to_string(file, buf, sizeof(buf)));
380 
381 				/* Currently these retries are purely a guess;
382 				 * there is no reproducible problem that they solve.  */
383 				if (--tries_remaining) {
384 					int delay = 100;
385 					if (status == STATUS_INSUFFICIENT_RESOURCES ||
386 					    status == STATUS_NO_MEMORY) {
387 						delay *= 25;
388 					}
389 					WARNING("Retrying after %dms...", delay);
390 					Sleep(delay);
391 					goto retry_read;
392 				}
393 				ERROR("Too many retries; returning failure");
394 				ret = WIMLIB_ERR_READ;
395 			}
396 			break;
397 		} else if (unlikely(tries_remaining != max_tries)) {
398 			WARNING("A read request had to be retried multiple times "
399 				"before it succeeded!");
400 		}
401 
402 		bytes_read = iosb.Information;
403 
404 		bytes_remaining -= bytes_read;
405 		ret = consume_chunk(cb, buf, bytes_read);
406 		if (ret)
407 			break;
408 	}
409 	NtClose(h);
410 	return ret;
411 }
412 
413 struct win32_encrypted_read_ctx {
414 	const struct consume_chunk_callback *cb;
415 	int wimlib_err_code;
416 	u64 bytes_remaining;
417 };
418 
419 static DWORD WINAPI
win32_encrypted_export_cb(unsigned char * data,void * _ctx,unsigned long len)420 win32_encrypted_export_cb(unsigned char *data, void *_ctx, unsigned long len)
421 {
422 	struct win32_encrypted_read_ctx *ctx = _ctx;
423 	int ret;
424 	size_t bytes_to_consume = min(len, ctx->bytes_remaining);
425 
426 	if (bytes_to_consume == 0)
427 		return ERROR_SUCCESS;
428 
429 	ret = consume_chunk(ctx->cb, data, bytes_to_consume);
430 	if (ret) {
431 		ctx->wimlib_err_code = ret;
432 		/* It doesn't matter what error code is returned here, as long
433 		 * as it isn't ERROR_SUCCESS.  */
434 		return ERROR_READ_FAULT;
435 	}
436 	ctx->bytes_remaining -= bytes_to_consume;
437 	return ERROR_SUCCESS;
438 }
439 
440 static int
read_win32_encrypted_file_prefix(const wchar_t * path,bool is_dir,u64 size,const struct consume_chunk_callback * cb)441 read_win32_encrypted_file_prefix(const wchar_t *path, bool is_dir, u64 size,
442 				 const struct consume_chunk_callback *cb)
443 {
444 	struct win32_encrypted_read_ctx export_ctx;
445 	DWORD err;
446 	void *file_ctx;
447 	int ret;
448 	DWORD flags = 0;
449 
450 	if (is_dir)
451 		flags |= CREATE_FOR_DIR;
452 
453 	export_ctx.cb = cb;
454 	export_ctx.wimlib_err_code = 0;
455 	export_ctx.bytes_remaining = size;
456 
457 	err = OpenEncryptedFileRaw(path, flags, &file_ctx);
458 	if (err != ERROR_SUCCESS) {
459 		win32_error(err,
460 			    L"Failed to open encrypted file \"%ls\" for raw read",
461 			    path);
462 		return WIMLIB_ERR_OPEN;
463 	}
464 	err = ReadEncryptedFileRaw(win32_encrypted_export_cb,
465 				   &export_ctx, file_ctx);
466 	if (err != ERROR_SUCCESS) {
467 		ret = export_ctx.wimlib_err_code;
468 		if (ret == 0) {
469 			win32_error(err,
470 				    L"Failed to read encrypted file \"%ls\"",
471 				    path);
472 			ret = WIMLIB_ERR_READ;
473 		}
474 	} else if (export_ctx.bytes_remaining != 0) {
475 		ERROR("Only could read %"PRIu64" of %"PRIu64" bytes from "
476 		      "encrypted file \"%ls\"",
477 		      size - export_ctx.bytes_remaining, size,
478 		      path);
479 		ret = WIMLIB_ERR_READ;
480 	} else {
481 		ret = 0;
482 	}
483 	CloseEncryptedFileRaw(file_ctx);
484 	return ret;
485 }
486 
487 /* Read the first @size bytes from the file, or named data stream of a file,
488  * described by @blob.  */
489 int
read_windows_file_prefix(const struct blob_descriptor * blob,u64 size,const struct consume_chunk_callback * cb)490 read_windows_file_prefix(const struct blob_descriptor *blob, u64 size,
491 			 const struct consume_chunk_callback *cb)
492 {
493 	const struct windows_file *file = blob->windows_file;
494 
495 	if (unlikely(file->is_encrypted)) {
496 		bool is_dir = (blob->file_inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
497 		return read_win32_encrypted_file_prefix(file->path, is_dir, size, cb);
498 	}
499 
500 	return read_winnt_stream_prefix(file, size, cb);
501 }
502 
503 /*
504  * Load the short name of a file into a WIM dentry.
505  */
506 static noinline_for_stack NTSTATUS
winnt_get_short_name(HANDLE h,struct wim_dentry * dentry)507 winnt_get_short_name(HANDLE h, struct wim_dentry *dentry)
508 {
509 	/* It's not any harder to just make the NtQueryInformationFile() system
510 	 * call ourselves, and it saves a dumb call to FindFirstFile() which of
511 	 * course has to create its own handle.  */
512 	NTSTATUS status;
513 	IO_STATUS_BLOCK iosb;
514 	u8 buf[128] _aligned_attribute(8);
515 	const FILE_NAME_INFORMATION *info;
516 
517 	status = NtQueryInformationFile(h, &iosb, buf, sizeof(buf),
518 					FileAlternateNameInformation);
519 	info = (const FILE_NAME_INFORMATION *)buf;
520 	if (NT_SUCCESS(status) && info->FileNameLength != 0) {
521 		dentry->d_short_name = utf16le_dupz(info->FileName,
522 						    info->FileNameLength);
523 		if (!dentry->d_short_name)
524 			return STATUS_NO_MEMORY;
525 		dentry->d_short_name_nbytes = info->FileNameLength;
526 	}
527 	return status;
528 }
529 
530 /*
531  * Load the security descriptor of a file into the corresponding inode and the
532  * WIM image's security descriptor set.
533  */
534 static noinline_for_stack int
winnt_load_security_descriptor(HANDLE h,struct wim_inode * inode,struct winnt_scan_ctx * ctx)535 winnt_load_security_descriptor(HANDLE h, struct wim_inode *inode,
536 			       struct winnt_scan_ctx *ctx)
537 {
538 	SECURITY_INFORMATION requestedInformation;
539 	u8 _buf[4096] _aligned_attribute(8);
540 	u8 *buf;
541 	ULONG bufsize;
542 	ULONG len_needed;
543 	NTSTATUS status;
544 
545 	/*
546 	 * LABEL_SECURITY_INFORMATION is needed on Windows Vista and 7 because
547 	 * Microsoft decided to add mandatory integrity labels to the SACL but
548 	 * not have them returned by SACL_SECURITY_INFORMATION.
549 	 *
550 	 * BACKUP_SECURITY_INFORMATION is needed on Windows 8 because Microsoft
551 	 * decided to add even more stuff to the SACL and still not have it
552 	 * returned by SACL_SECURITY_INFORMATION; but they did remember that
553 	 * backup applications exist and simply want to read the stupid thing
554 	 * once and for all, so they added a flag to read the entire security
555 	 * descriptor.
556 	 *
557 	 * Older versions of Windows tolerate these new flags being passed in.
558 	 */
559 	requestedInformation = OWNER_SECURITY_INFORMATION |
560 			       GROUP_SECURITY_INFORMATION |
561 			       DACL_SECURITY_INFORMATION |
562 			       SACL_SECURITY_INFORMATION |
563 			       LABEL_SECURITY_INFORMATION |
564 			       BACKUP_SECURITY_INFORMATION;
565 
566 	buf = _buf;
567 	bufsize = sizeof(_buf);
568 
569 	/*
570 	 * We need the file's security descriptor in
571 	 * SECURITY_DESCRIPTOR_RELATIVE format, and we currently have a handle
572 	 * opened with as many relevant permissions as possible.  At this point,
573 	 * on Windows there are a number of options for reading a file's
574 	 * security descriptor:
575 	 *
576 	 * GetFileSecurity():  This takes in a path and returns the
577 	 * SECURITY_DESCRIPTOR_RELATIVE.  Problem: this uses an internal handle,
578 	 * not ours, and the handle created internally doesn't specify
579 	 * FILE_FLAG_BACKUP_SEMANTICS.  Therefore there can be access denied
580 	 * errors on some files and directories, even when running as the
581 	 * Administrator.
582 	 *
583 	 * GetSecurityInfo():  This takes in a handle and returns the security
584 	 * descriptor split into a bunch of different parts.  This should work,
585 	 * but it's dumb because we have to put the security descriptor back
586 	 * together again.
587 	 *
588 	 * BackupRead():  This can read the security descriptor, but this is a
589 	 * difficult-to-use API, probably only works as the Administrator, and
590 	 * the format of the returned data is not well documented.
591 	 *
592 	 * NtQuerySecurityObject():  This is exactly what we need, as it takes
593 	 * in a handle and returns the security descriptor in
594 	 * SECURITY_DESCRIPTOR_RELATIVE format.  Only problem is that it's a
595 	 * ntdll function and therefore not officially part of the Win32 API.
596 	 * Oh well.
597 	 */
598 	while (!NT_SUCCESS(status = NtQuerySecurityObject(h,
599 							  requestedInformation,
600 							  (PSECURITY_DESCRIPTOR)buf,
601 							  bufsize,
602 							  &len_needed)))
603 	{
604 		switch (status) {
605 		case STATUS_BUFFER_TOO_SMALL:
606 			wimlib_assert(buf == _buf);
607 			buf = MALLOC(len_needed);
608 			if (!buf) {
609 				status = STATUS_NO_MEMORY;
610 				goto out;
611 			}
612 			bufsize = len_needed;
613 			break;
614 		case STATUS_PRIVILEGE_NOT_HELD:
615 		case STATUS_ACCESS_DENIED:
616 			if (ctx->params->add_flags & WIMLIB_ADD_FLAG_STRICT_ACLS) {
617 		default:
618 				/* Permission denied in STRICT_ACLS mode, or
619 				 * unknown error.  */
620 				goto out;
621 			}
622 			if (requestedInformation & SACL_SECURITY_INFORMATION) {
623 				/* Try again without the SACL.  */
624 				ctx->num_get_sacl_priv_notheld++;
625 				requestedInformation &= ~(SACL_SECURITY_INFORMATION |
626 							  LABEL_SECURITY_INFORMATION |
627 							  BACKUP_SECURITY_INFORMATION);
628 				break;
629 			}
630 			/* Fake success (useful when capturing as
631 			 * non-Administrator).  */
632 			ctx->num_get_sd_access_denied++;
633 			status = STATUS_SUCCESS;
634 			goto out;
635 		}
636 	}
637 
638 	/* We can get a length of 0 with Samba.  Assume that means "no security
639 	 * descriptor".  */
640 	if (len_needed == 0)
641 		goto out;
642 
643 	/* Add the security descriptor to the WIM image, and save its ID in
644 	 * the file's inode.  */
645 	inode->i_security_id = sd_set_add_sd(ctx->params->sd_set, buf, len_needed);
646 	if (unlikely(inode->i_security_id < 0))
647 		status = STATUS_NO_MEMORY;
648 out:
649 	if (unlikely(buf != _buf))
650 		FREE(buf);
651 	if (!NT_SUCCESS(status)) {
652 		winnt_error(status, L"\"%ls\": Can't read security descriptor",
653 			    printable_path(ctx));
654 		return WIMLIB_ERR_STAT;
655 	}
656 	return 0;
657 }
658 
659 /* Load a file's object ID into the corresponding WIM inode.  */
660 static noinline_for_stack int
winnt_load_object_id(HANDLE h,struct wim_inode * inode,struct winnt_scan_ctx * ctx)661 winnt_load_object_id(HANDLE h, struct wim_inode *inode,
662 		     struct winnt_scan_ctx *ctx)
663 {
664 	FILE_OBJECTID_BUFFER buffer;
665 	NTSTATUS status;
666 	u32 len;
667 
668 	if (!(ctx->vol_flags & FILE_SUPPORTS_OBJECT_IDS))
669 		return 0;
670 
671 	status = winnt_fsctl(h, FSCTL_GET_OBJECT_ID, NULL, 0,
672 			     &buffer, sizeof(buffer), &len);
673 
674 	if (status == STATUS_OBJECTID_NOT_FOUND) /* No object ID  */
675 		return 0;
676 
677 	if (status == STATUS_INVALID_DEVICE_REQUEST ||
678 	    status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */) {
679 		/* The filesystem claimed to support object IDs, but we can't
680 		 * actually read them.  This happens with Samba.  */
681 		ctx->vol_flags &= ~FILE_SUPPORTS_OBJECT_IDS;
682 		return 0;
683 	}
684 
685 	if (!NT_SUCCESS(status)) {
686 		winnt_error(status, L"\"%ls\": Can't read object ID",
687 			    printable_path(ctx));
688 		return WIMLIB_ERR_STAT;
689 	}
690 
691 	if (len == 0) /* No object ID (for directories)  */
692 		return 0;
693 
694 	if (!inode_set_object_id(inode, &buffer, len))
695 		return WIMLIB_ERR_NOMEM;
696 
697 	return 0;
698 }
699 
700 /* Load a file's extended attributes into the corresponding WIM inode.  */
701 static noinline_for_stack int
winnt_load_xattrs(HANDLE h,struct wim_inode * inode,struct winnt_scan_ctx * ctx,u32 ea_size)702 winnt_load_xattrs(HANDLE h, struct wim_inode *inode,
703 		  struct winnt_scan_ctx *ctx, u32 ea_size)
704 {
705 	IO_STATUS_BLOCK iosb;
706 	NTSTATUS status;
707 	u8 _buf[1024] _aligned_attribute(4);
708 	u8 *buf = _buf;
709 	const FILE_FULL_EA_INFORMATION *ea;
710 	struct wim_xattr_entry *entry;
711 	int ret;
712 
713 
714 	/*
715 	 * EaSize from FILE_EA_INFORMATION is apparently supposed to give the
716 	 * size of the buffer required for NtQueryEaFile(), but it doesn't
717 	 * actually work correctly; it can be off by about 4 bytes per xattr.
718 	 *
719 	 * So just start out by doubling the advertised size, and also handle
720 	 * STATUS_BUFFER_OVERFLOW just in case.
721 	 */
722 retry:
723 	if (unlikely(ea_size * 2 < ea_size))
724 		ea_size = UINT32_MAX;
725 	else
726 		ea_size *= 2;
727 	if (unlikely(ea_size > sizeof(_buf))) {
728 		buf = MALLOC(ea_size);
729 		if (!buf) {
730 			if (ea_size >= (1 << 20)) {
731 				WARNING("\"%ls\": EaSize was extremely large (%u)",
732 					printable_path(ctx), ea_size);
733 			}
734 			return WIMLIB_ERR_NOMEM;
735 		}
736 	}
737 
738 	status = NtQueryEaFile(h, &iosb, buf, ea_size,
739 			       FALSE, NULL, 0, NULL, TRUE);
740 
741 	if (unlikely(!NT_SUCCESS(status))) {
742 		if (status == STATUS_BUFFER_OVERFLOW) {
743 			if (buf != _buf) {
744 				FREE(buf);
745 				buf = NULL;
746 			}
747 			goto retry;
748 		}
749 		if (status == STATUS_NO_EAS_ON_FILE) {
750 			/*
751 			 * FILE_EA_INFORMATION.EaSize was nonzero so this
752 			 * shouldn't happen, but just in case...
753 			 */
754 			ret = 0;
755 			goto out;
756 		}
757 		winnt_error(status, L"\"%ls\": Can't read extended attributes",
758 			    printable_path(ctx));
759 		ret = WIMLIB_ERR_STAT;
760 		goto out;
761 	}
762 
763 	ea = (const FILE_FULL_EA_INFORMATION *)buf;
764 	entry = (struct wim_xattr_entry *)buf;
765 	for (;;) {
766 		/*
767 		 * wim_xattr_entry is not larger than FILE_FULL_EA_INFORMATION,
768 		 * so we can reuse the same buffer by overwriting the
769 		 * FILE_FULL_EA_INFORMATION with the wim_xattr_entry in-place.
770 		 */
771 		FILE_FULL_EA_INFORMATION _ea;
772 
773 		STATIC_ASSERT(offsetof(struct wim_xattr_entry, name) <=
774 			      offsetof(FILE_FULL_EA_INFORMATION, EaName));
775 		wimlib_assert((u8 *)entry <= (const u8 *)ea);
776 
777 		memcpy(&_ea, ea, sizeof(_ea));
778 
779 		entry->value_len = cpu_to_le16(_ea.EaValueLength);
780 		entry->name_len = _ea.EaNameLength;
781 		entry->flags = _ea.Flags;
782 		memmove(entry->name, ea->EaName, _ea.EaNameLength);
783 		entry->name[_ea.EaNameLength] = '\0';
784 		memmove(&entry->name[_ea.EaNameLength + 1],
785 			&ea->EaName[_ea.EaNameLength + 1], _ea.EaValueLength);
786 		entry = (struct wim_xattr_entry *)
787 			 &entry->name[_ea.EaNameLength + 1 + _ea.EaValueLength];
788 		if (_ea.NextEntryOffset == 0)
789 			break;
790 		ea = (const FILE_FULL_EA_INFORMATION *)
791 			((const u8 *)ea + _ea.NextEntryOffset);
792 	}
793 	wimlib_assert((u8 *)entry - buf <= ea_size);
794 
795 	ret = WIMLIB_ERR_NOMEM;
796 	if (!inode_set_xattrs(inode, buf, (u8 *)entry - buf))
797 		goto out;
798 	ret = 0;
799 out:
800 	if (unlikely(buf != _buf))
801 		FREE(buf);
802 	return ret;
803 }
804 
805 static int
806 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
807 				  HANDLE cur_dir,
808 				  const wchar_t *relative_path,
809 				  size_t relative_path_nchars,
810 				  const wchar_t *filename,
811 				  struct winnt_scan_ctx *ctx);
812 
813 static int
winnt_recurse_directory(HANDLE h,struct wim_dentry * parent,struct winnt_scan_ctx * ctx)814 winnt_recurse_directory(HANDLE h,
815 			struct wim_dentry *parent,
816 			struct winnt_scan_ctx *ctx)
817 {
818 	void *buf;
819 	const size_t bufsize = 8192;
820 	IO_STATUS_BLOCK iosb;
821 	NTSTATUS status;
822 	int ret;
823 
824 	buf = MALLOC(bufsize);
825 	if (!buf)
826 		return WIMLIB_ERR_NOMEM;
827 
828 	/* Using NtQueryDirectoryFile() we can re-use the same open handle,
829 	 * which we opened with FILE_FLAG_BACKUP_SEMANTICS.  */
830 
831 	while (NT_SUCCESS(status = NtQueryDirectoryFile(h, NULL, NULL, NULL,
832 							&iosb, buf, bufsize,
833 							FileNamesInformation,
834 							FALSE, NULL, FALSE)))
835 	{
836 		const FILE_NAMES_INFORMATION *info = buf;
837 		for (;;) {
838 			if (!should_ignore_filename(info->FileName,
839 						    info->FileNameLength / 2))
840 			{
841 				struct wim_dentry *child;
842 				size_t orig_path_nchars;
843 				const wchar_t *filename;
844 
845 				ret = WIMLIB_ERR_NOMEM;
846 				filename = pathbuf_append_name(ctx->params,
847 							       info->FileName,
848 							       info->FileNameLength / 2,
849 							       &orig_path_nchars);
850 				if (!filename)
851 					goto out_free_buf;
852 
853 				ret = winnt_build_dentry_tree_recursive(
854 							&child,
855 							h,
856 							filename,
857 							info->FileNameLength / 2,
858 							filename,
859 							ctx);
860 
861 				pathbuf_truncate(ctx->params, orig_path_nchars);
862 
863 				if (ret)
864 					goto out_free_buf;
865 				attach_scanned_tree(parent, child,
866 						    ctx->params->blob_table);
867 			}
868 			if (info->NextEntryOffset == 0)
869 				break;
870 			info = (const FILE_NAMES_INFORMATION *)
871 					((const u8 *)info + info->NextEntryOffset);
872 		}
873 	}
874 
875 	if (unlikely(status != STATUS_NO_MORE_FILES)) {
876 		winnt_error(status, L"\"%ls\": Can't read directory",
877 			    printable_path(ctx));
878 		ret = WIMLIB_ERR_READ;
879 	}
880 out_free_buf:
881 	FREE(buf);
882 	return ret;
883 }
884 
885 /* Reparse point fixup status code  */
886 #define RP_FIXED	(-1)
887 
888 static bool
file_has_ino_and_dev(HANDLE h,u64 ino,u64 dev)889 file_has_ino_and_dev(HANDLE h, u64 ino, u64 dev)
890 {
891 	NTSTATUS status;
892 	IO_STATUS_BLOCK iosb;
893 	FILE_INTERNAL_INFORMATION int_info;
894 	FILE_FS_VOLUME_INFORMATION vol_info;
895 
896 	status = NtQueryInformationFile(h, &iosb, &int_info, sizeof(int_info),
897 					FileInternalInformation);
898 	if (!NT_SUCCESS(status))
899 		return false;
900 
901 	if (int_info.IndexNumber.QuadPart != ino)
902 		return false;
903 
904 	status = NtQueryVolumeInformationFile(h, &iosb,
905 					      &vol_info, sizeof(vol_info),
906 					      FileFsVolumeInformation);
907 	if (!(NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW))
908 		return false;
909 
910 	if (iosb.Information <
911 	     offsetof(FILE_FS_VOLUME_INFORMATION, VolumeSerialNumber) +
912 	     sizeof(vol_info.VolumeSerialNumber))
913 		return false;
914 
915 	return (vol_info.VolumeSerialNumber == dev);
916 }
917 
918 /*
919  * This is the Windows equivalent of unix_relativize_link_target(); see there
920  * for general details.  This version works with an "absolute" Windows link
921  * target, specified from the root of the Windows kernel object namespace.  Note
922  * that we have to open directories with a trailing slash when present because
923  * \??\E: opens the E: device itself and not the filesystem root directory.
924  */
925 static const wchar_t *
winnt_relativize_link_target(const wchar_t * target,size_t target_nbytes,u64 ino,u64 dev)926 winnt_relativize_link_target(const wchar_t *target, size_t target_nbytes,
927 			     u64 ino, u64 dev)
928 {
929 	UNICODE_STRING name;
930 	OBJECT_ATTRIBUTES attr;
931 	IO_STATUS_BLOCK iosb;
932 	NTSTATUS status;
933 	const wchar_t *target_end;
934 	const wchar_t *p;
935 
936 	target_end = target + (target_nbytes / sizeof(wchar_t));
937 
938 	/* Empty path??? */
939 	if (target_end == target)
940 		return target;
941 
942 	/* No leading slash???  */
943 	if (target[0] != L'\\')
944 		return target;
945 
946 	/* UNC path???  */
947 	if ((target_end - target) >= 2 &&
948 	    target[0] == L'\\' && target[1] == L'\\')
949 		return target;
950 
951 	attr.Length = sizeof(attr);
952 	attr.RootDirectory = NULL;
953 	attr.ObjectName = &name;
954 	attr.Attributes = 0;
955 	attr.SecurityDescriptor = NULL;
956 	attr.SecurityQualityOfService = NULL;
957 
958 	name.Buffer = (wchar_t *)target;
959 	name.Length = 0;
960 	p = target;
961 	do {
962 		HANDLE h;
963 		const wchar_t *orig_p = p;
964 
965 		/* Skip non-backslashes  */
966 		while (p != target_end && *p != L'\\')
967 			p++;
968 
969 		/* Skip backslashes  */
970 		while (p != target_end && *p == L'\\')
971 			p++;
972 
973 		/* Append path component  */
974 		name.Length += (p - orig_p) * sizeof(wchar_t);
975 		name.MaximumLength = name.Length;
976 
977 		/* Try opening the file  */
978 		status = NtOpenFile(&h,
979 				    FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
980 				    &attr,
981 				    &iosb,
982 				    FILE_SHARE_VALID_FLAGS,
983 				    FILE_OPEN_FOR_BACKUP_INTENT);
984 
985 		if (NT_SUCCESS(status)) {
986 			/* Reset root directory  */
987 			if (attr.RootDirectory)
988 				NtClose(attr.RootDirectory);
989 			attr.RootDirectory = h;
990 			name.Buffer = (wchar_t *)p;
991 			name.Length = 0;
992 
993 			if (file_has_ino_and_dev(h, ino, dev))
994 				goto out_close_root_dir;
995 		}
996 	} while (p != target_end);
997 
998 	p = target;
999 
1000 out_close_root_dir:
1001 	if (attr.RootDirectory)
1002 		NtClose(attr.RootDirectory);
1003 	while (p > target && *(p - 1) == L'\\')
1004 		p--;
1005 	return p;
1006 }
1007 
1008 static int
winnt_rpfix_progress(struct scan_params * params,const struct link_reparse_point * link,int scan_status)1009 winnt_rpfix_progress(struct scan_params *params,
1010 		     const struct link_reparse_point *link, int scan_status)
1011 {
1012 	size_t print_name_nchars = link->print_name_nbytes / sizeof(wchar_t);
1013 	wchar_t print_name0[print_name_nchars + 1];
1014 
1015 	wmemcpy(print_name0, link->print_name, print_name_nchars);
1016 	print_name0[print_name_nchars] = L'\0';
1017 
1018 	params->progress.scan.symlink_target = print_name0;
1019 	return do_scan_progress(params, scan_status, NULL);
1020 }
1021 
1022 static int
winnt_try_rpfix(struct reparse_buffer_disk * rpbuf,u16 * rpbuflen_p,struct scan_params * params)1023 winnt_try_rpfix(struct reparse_buffer_disk *rpbuf, u16 *rpbuflen_p,
1024 		struct scan_params *params)
1025 {
1026 	struct link_reparse_point link;
1027 	const wchar_t *rel_target;
1028 	int ret;
1029 
1030 	if (parse_link_reparse_point(rpbuf, *rpbuflen_p, &link)) {
1031 		/* Couldn't understand the reparse data; don't do the fixup.  */
1032 		return 0;
1033 	}
1034 
1035 	/*
1036 	 * Don't do reparse point fixups on relative symbolic links.
1037 	 *
1038 	 * On Windows, a relative symbolic link is supposed to be identifiable
1039 	 * by having reparse tag WIM_IO_REPARSE_TAG_SYMLINK and flags
1040 	 * SYMBOLIC_LINK_RELATIVE.  We will use this information, although this
1041 	 * may not always do what the user expects, since drive-relative
1042 	 * symbolic links such as "\Users\Public" have SYMBOLIC_LINK_RELATIVE
1043 	 * set, in addition to truly relative symbolic links such as "Users" or
1044 	 * "Users\Public".  However, WIMGAPI (as of Windows 8.1) has this same
1045 	 * behavior.
1046 	 *
1047 	 * Otherwise, as far as I can tell, the targets of symbolic links that
1048 	 * are NOT relative, as well as junctions (note: a mountpoint is the
1049 	 * sames thing as a junction), must be NT namespace paths, for example:
1050 	 *
1051 	 *     - \??\e:\Users\Public
1052 	 *     - \DosDevices\e:\Users\Public
1053 	 *     - \Device\HardDiskVolume4\Users\Public
1054 	 *     - \??\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1055 	 *     - \DosDevices\Volume{c47cb07c-946e-4155-b8f7-052e9cec7628}\Users\Public
1056 	 */
1057 	if (link_is_relative_symlink(&link))
1058 		return 0;
1059 
1060 	rel_target = winnt_relativize_link_target(link.substitute_name,
1061 						  link.substitute_name_nbytes,
1062 						  params->capture_root_ino,
1063 						  params->capture_root_dev);
1064 
1065 	if (rel_target == link.substitute_name) {
1066 		/* Target points outside of the tree being captured or had an
1067 		 * unrecognized path format.  Don't adjust it.  */
1068 		return winnt_rpfix_progress(params, &link,
1069 					    WIMLIB_SCAN_DENTRY_NOT_FIXED_SYMLINK);
1070 	}
1071 
1072 	/* We have an absolute target pointing within the directory being
1073 	 * captured. @rel_target is the suffix of the link target that is the
1074 	 * part relative to the directory being captured.
1075 	 *
1076 	 * We will cut off the prefix before this part (which is the path to the
1077 	 * directory being captured) and add a dummy prefix.  Since the process
1078 	 * will need to be reversed when applying the image, it doesn't matter
1079 	 * what exactly the prefix is, as long as it looks like an absolute
1080 	 * path.  */
1081 
1082 	static const wchar_t prefix[6] = L"\\??\\X:";
1083 	static const size_t num_unprintable_chars = 4;
1084 
1085 	size_t rel_target_nbytes =
1086 		link.substitute_name_nbytes - ((const u8 *)rel_target -
1087 					       (const u8 *)link.substitute_name);
1088 
1089 	wchar_t tmp[(sizeof(prefix) + rel_target_nbytes) / sizeof(wchar_t)];
1090 
1091 	memcpy(tmp, prefix, sizeof(prefix));
1092 	memcpy(tmp + ARRAY_LEN(prefix), rel_target, rel_target_nbytes);
1093 
1094 	link.substitute_name = tmp;
1095 	link.substitute_name_nbytes = sizeof(tmp);
1096 
1097 	link.print_name = link.substitute_name + num_unprintable_chars;
1098 	link.print_name_nbytes = link.substitute_name_nbytes -
1099 				 (num_unprintable_chars * sizeof(wchar_t));
1100 
1101 	if (make_link_reparse_point(&link, rpbuf, rpbuflen_p))
1102 		return 0;
1103 
1104 	ret = winnt_rpfix_progress(params, &link,
1105 				   WIMLIB_SCAN_DENTRY_FIXED_SYMLINK);
1106 	if (ret)
1107 		return ret;
1108 	return RP_FIXED;
1109 }
1110 
1111 /* Load the reparse data of a file into the corresponding WIM inode.  If the
1112  * reparse point is a symbolic link or junction with an absolute target and
1113  * RPFIX mode is enabled, then also rewrite its target to be relative to the
1114  * capture root.  */
1115 static noinline_for_stack int
winnt_load_reparse_data(HANDLE h,struct wim_inode * inode,struct winnt_scan_ctx * ctx)1116 winnt_load_reparse_data(HANDLE h, struct wim_inode *inode,
1117 			struct winnt_scan_ctx *ctx)
1118 {
1119 	struct reparse_buffer_disk rpbuf;
1120 	NTSTATUS status;
1121 	u32 len;
1122 	u16 rpbuflen;
1123 	int ret;
1124 
1125 	if (inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED) {
1126 		/* See comment above assign_stream_types_encrypted()  */
1127 		WARNING("Ignoring reparse data of encrypted file \"%ls\"",
1128 			printable_path(ctx));
1129 		return 0;
1130 	}
1131 
1132 	status = winnt_fsctl(h, FSCTL_GET_REPARSE_POINT,
1133 			     NULL, 0, &rpbuf, sizeof(rpbuf), &len);
1134 	if (!NT_SUCCESS(status)) {
1135 		winnt_error(status, L"\"%ls\": Can't get reparse point",
1136 			    printable_path(ctx));
1137 		return WIMLIB_ERR_READLINK;
1138 	}
1139 
1140 	rpbuflen = len;
1141 
1142 	if (unlikely(rpbuflen < REPARSE_DATA_OFFSET)) {
1143 		ERROR("\"%ls\": reparse point buffer is too short",
1144 		      printable_path(ctx));
1145 		return WIMLIB_ERR_INVALID_REPARSE_DATA;
1146 	}
1147 
1148 	if (le32_to_cpu(rpbuf.rptag) == WIM_IO_REPARSE_TAG_DEDUP) {
1149 		/*
1150 		 * Windows treats Data Deduplication reparse points specially.
1151 		 * Reads from the unnamed data stream actually return the
1152 		 * redirected file contents, even with FILE_OPEN_REPARSE_POINT.
1153 		 * Deduplicated files also cannot be properly restored without
1154 		 * also restoring the "System Volume Information" directory,
1155 		 * which wimlib excludes by default.  Therefore, the logical
1156 		 * behavior for us seems to be to ignore the reparse point and
1157 		 * treat the file as a normal file.
1158 		 */
1159 		inode->i_attributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
1160 		return 0;
1161 	}
1162 
1163 	if (ctx->params->add_flags & WIMLIB_ADD_FLAG_RPFIX) {
1164 		ret = winnt_try_rpfix(&rpbuf, &rpbuflen, ctx->params);
1165 		if (ret == RP_FIXED)
1166 			inode->i_rp_flags &= ~WIM_RP_FLAG_NOT_FIXED;
1167 		else if (ret)
1168 			return ret;
1169 	}
1170 
1171 	inode->i_reparse_tag = le32_to_cpu(rpbuf.rptag);
1172 	inode->i_rp_reserved = le16_to_cpu(rpbuf.rpreserved);
1173 
1174 	if (!inode_add_stream_with_data(inode,
1175 					STREAM_TYPE_REPARSE_POINT,
1176 					NO_STREAM_NAME,
1177 					rpbuf.rpdata,
1178 					rpbuflen - REPARSE_DATA_OFFSET,
1179 					ctx->params->blob_table))
1180 		return WIMLIB_ERR_NOMEM;
1181 
1182 	return 0;
1183 }
1184 
1185 static DWORD WINAPI
win32_tally_encrypted_size_cb(unsigned char * _data,void * _size_ret,unsigned long len)1186 win32_tally_encrypted_size_cb(unsigned char *_data, void *_size_ret,
1187 			      unsigned long len)
1188 {
1189 	*(u64*)_size_ret += len;
1190 	return ERROR_SUCCESS;
1191 }
1192 
1193 static int
win32_get_encrypted_file_size(const wchar_t * path,bool is_dir,u64 * size_ret)1194 win32_get_encrypted_file_size(const wchar_t *path, bool is_dir, u64 *size_ret)
1195 {
1196 	DWORD err;
1197 	void *file_ctx;
1198 	int ret;
1199 	DWORD flags = 0;
1200 
1201 	if (is_dir)
1202 		flags |= CREATE_FOR_DIR;
1203 
1204 	err = OpenEncryptedFileRaw(path, flags, &file_ctx);
1205 	if (err != ERROR_SUCCESS) {
1206 		win32_error(err,
1207 			    L"Failed to open encrypted file \"%ls\" for raw read",
1208 			    path);
1209 		return WIMLIB_ERR_OPEN;
1210 	}
1211 	*size_ret = 0;
1212 	err = ReadEncryptedFileRaw(win32_tally_encrypted_size_cb,
1213 				   size_ret, file_ctx);
1214 	if (err != ERROR_SUCCESS) {
1215 		win32_error(err,
1216 			    L"Failed to read raw encrypted data from \"%ls\"",
1217 			    path);
1218 		ret = WIMLIB_ERR_READ;
1219 	} else {
1220 		ret = 0;
1221 	}
1222 	CloseEncryptedFileRaw(file_ctx);
1223 	return ret;
1224 }
1225 
1226 static int
winnt_scan_efsrpc_raw_data(struct wim_inode * inode,struct winnt_scan_ctx * ctx)1227 winnt_scan_efsrpc_raw_data(struct wim_inode *inode,
1228 			   struct winnt_scan_ctx *ctx)
1229 {
1230 	wchar_t *path = ctx->params->cur_path;
1231 	size_t path_nchars = ctx->params->cur_path_nchars;
1232 	const bool is_dir = (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY);
1233 	struct windows_file *windows_file;
1234 	u64 size;
1235 	int ret;
1236 
1237 	/* OpenEncryptedFileRaw() expects a Win32 name.  */
1238 	wimlib_assert(!wmemcmp(path, L"\\??\\", 4));
1239 	path[1] = L'\\';
1240 
1241 	ret = win32_get_encrypted_file_size(path, is_dir, &size);
1242 	if (ret)
1243 		goto out;
1244 
1245 	/* Empty EFSRPC data does not make sense  */
1246 	wimlib_assert(size != 0);
1247 
1248 	windows_file = alloc_windows_file(path, path_nchars, NULL, 0,
1249 					  ctx->snapshot, true);
1250 	ret = add_stream(inode, windows_file, size, STREAM_TYPE_EFSRPC_RAW_DATA,
1251 			 NO_STREAM_NAME, ctx->params->unhashed_blobs);
1252 out:
1253 	path[1] = L'?';
1254 	return ret;
1255 }
1256 
1257 static bool
get_data_stream_name(const wchar_t * raw_stream_name,size_t raw_stream_name_nchars,const wchar_t ** stream_name_ret,size_t * stream_name_nchars_ret)1258 get_data_stream_name(const wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1259 		     const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
1260 {
1261 	const wchar_t *sep, *type, *end;
1262 
1263 	/* The stream name should be returned as :NAME:TYPE  */
1264 	if (raw_stream_name_nchars < 1)
1265 		return false;
1266 	if (raw_stream_name[0] != L':')
1267 		return false;
1268 
1269 	raw_stream_name++;
1270 	raw_stream_name_nchars--;
1271 
1272 	end = raw_stream_name + raw_stream_name_nchars;
1273 
1274 	sep = wmemchr(raw_stream_name, L':', raw_stream_name_nchars);
1275 	if (!sep)
1276 		return false;
1277 
1278 	type = sep + 1;
1279 	if (end - type != 5)
1280 		return false;
1281 
1282 	if (wmemcmp(type, L"$DATA", 5))
1283 		return false;
1284 
1285 	*stream_name_ret = raw_stream_name;
1286 	*stream_name_nchars_ret = sep - raw_stream_name;
1287 	return true;
1288 }
1289 
1290 static int
winnt_scan_data_stream(wchar_t * raw_stream_name,size_t raw_stream_name_nchars,u64 stream_size,struct wim_inode * inode,struct winnt_scan_ctx * ctx)1291 winnt_scan_data_stream(wchar_t *raw_stream_name, size_t raw_stream_name_nchars,
1292 		       u64 stream_size, struct wim_inode *inode,
1293 		       struct winnt_scan_ctx *ctx)
1294 {
1295 	wchar_t *stream_name;
1296 	size_t stream_name_nchars;
1297 	struct windows_file *windows_file;
1298 
1299 	/* Given the raw stream name (which is something like
1300 	 * :streamname:$DATA), extract just the stream name part (streamname).
1301 	 * Ignore any non-$DATA streams.  */
1302 	if (!get_data_stream_name(raw_stream_name, raw_stream_name_nchars,
1303 				  (const wchar_t **)&stream_name,
1304 				  &stream_name_nchars))
1305 		return 0;
1306 
1307 	stream_name[stream_name_nchars] = L'\0';
1308 
1309 	windows_file = alloc_windows_file(ctx->params->cur_path,
1310 					  ctx->params->cur_path_nchars,
1311 					  stream_name, stream_name_nchars,
1312 					  ctx->snapshot, false);
1313 	return add_stream(inode, windows_file, stream_size, STREAM_TYPE_DATA,
1314 			  stream_name, ctx->params->unhashed_blobs);
1315 }
1316 
1317 /*
1318  * Load information about the data streams of an open file into a WIM inode.
1319  *
1320  * We use the NtQueryInformationFile() system call instead of FindFirstStream()
1321  * and FindNextStream().  This is done for two reasons:
1322  *
1323  * - FindFirstStream() opens its own handle to the file or directory and
1324  *   apparently does so without specifying FILE_FLAG_BACKUP_SEMANTICS, thereby
1325  *   causing access denied errors on certain files (even when running as the
1326  *   Administrator).
1327  * - FindFirstStream() and FindNextStream() is only available on Windows Vista
1328  *   and later, whereas the stream support in NtQueryInformationFile() was
1329  *   already present in Windows XP.
1330  */
1331 static noinline_for_stack int
winnt_scan_data_streams(HANDLE h,struct wim_inode * inode,u64 file_size,struct winnt_scan_ctx * ctx)1332 winnt_scan_data_streams(HANDLE h, struct wim_inode *inode, u64 file_size,
1333 			struct winnt_scan_ctx *ctx)
1334 {
1335 	int ret;
1336 	u8 _buf[4096] _aligned_attribute(8);
1337 	u8 *buf;
1338 	size_t bufsize;
1339 	IO_STATUS_BLOCK iosb;
1340 	NTSTATUS status;
1341 	FILE_STREAM_INFORMATION *info;
1342 
1343 	buf = _buf;
1344 	bufsize = sizeof(_buf);
1345 
1346 	if (!(ctx->vol_flags & FILE_NAMED_STREAMS))
1347 		goto unnamed_only;
1348 
1349 	/* Get a buffer containing the stream information.  */
1350 	while (!NT_SUCCESS(status = NtQueryInformationFile(h,
1351 							   &iosb,
1352 							   buf,
1353 							   bufsize,
1354 							   FileStreamInformation)))
1355 	{
1356 
1357 		switch (status) {
1358 		case STATUS_BUFFER_OVERFLOW:
1359 			{
1360 				u8 *newbuf;
1361 
1362 				bufsize *= 2;
1363 				if (buf == _buf)
1364 					newbuf = MALLOC(bufsize);
1365 				else
1366 					newbuf = REALLOC(buf, bufsize);
1367 				if (!newbuf) {
1368 					ret = WIMLIB_ERR_NOMEM;
1369 					goto out_free_buf;
1370 				}
1371 				buf = newbuf;
1372 			}
1373 			break;
1374 		case STATUS_NOT_IMPLEMENTED:
1375 		case STATUS_NOT_SUPPORTED:
1376 		case STATUS_INVALID_INFO_CLASS:
1377 			goto unnamed_only;
1378 		default:
1379 			winnt_error(status,
1380 				    L"\"%ls\": Failed to query stream information",
1381 				    printable_path(ctx));
1382 			ret = WIMLIB_ERR_READ;
1383 			goto out_free_buf;
1384 		}
1385 	}
1386 
1387 	if (iosb.Information == 0) {
1388 		/* No stream information.  */
1389 		ret = 0;
1390 		goto out_free_buf;
1391 	}
1392 
1393 	/* Parse one or more stream information structures.  */
1394 	info = (FILE_STREAM_INFORMATION *)buf;
1395 	for (;;) {
1396 		/* Load the stream information.  */
1397 		ret = winnt_scan_data_stream(info->StreamName,
1398 					     info->StreamNameLength / 2,
1399 					     info->StreamSize.QuadPart,
1400 					     inode, ctx);
1401 		if (ret)
1402 			goto out_free_buf;
1403 
1404 		if (info->NextEntryOffset == 0) {
1405 			/* No more stream information.  */
1406 			break;
1407 		}
1408 		/* Advance to next stream information.  */
1409 		info = (FILE_STREAM_INFORMATION *)
1410 				((u8 *)info + info->NextEntryOffset);
1411 	}
1412 	ret = 0;
1413 	goto out_free_buf;
1414 
1415 unnamed_only:
1416 	/* The volume does not support named streams.  Only capture the unnamed
1417 	 * data stream.  */
1418 	if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1419 				   FILE_ATTRIBUTE_REPARSE_POINT))
1420 	{
1421 		ret = 0;
1422 		goto out_free_buf;
1423 	}
1424 
1425 	{
1426 		wchar_t stream_name[] = L"::$DATA";
1427 		ret = winnt_scan_data_stream(stream_name, 7, file_size,
1428 					     inode, ctx);
1429 	}
1430 out_free_buf:
1431 	/* Free buffer if allocated on heap.  */
1432 	if (unlikely(buf != _buf))
1433 		FREE(buf);
1434 	return ret;
1435 }
1436 
1437 static u64
extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER * extents)1438 extract_starting_lcn(const RETRIEVAL_POINTERS_BUFFER *extents)
1439 {
1440 	if (extents->ExtentCount < 1)
1441 		return 0;
1442 
1443 	return extents->Extents[0].Lcn.QuadPart;
1444 }
1445 
1446 static noinline_for_stack u64
get_sort_key(HANDLE h)1447 get_sort_key(HANDLE h)
1448 {
1449 	STARTING_VCN_INPUT_BUFFER in = { .StartingVcn.QuadPart = 0 };
1450 	RETRIEVAL_POINTERS_BUFFER out;
1451 
1452 	if (!NT_SUCCESS(winnt_fsctl(h, FSCTL_GET_RETRIEVAL_POINTERS,
1453 				    &in, sizeof(in), &out, sizeof(out), NULL)))
1454 		return 0;
1455 
1456 	return extract_starting_lcn(&out);
1457 }
1458 
1459 static void
set_sort_key(struct wim_inode * inode,u64 sort_key)1460 set_sort_key(struct wim_inode *inode, u64 sort_key)
1461 {
1462 	for (unsigned i = 0; i < inode->i_num_streams; i++) {
1463 		struct wim_inode_stream *strm = &inode->i_streams[i];
1464 		struct blob_descriptor *blob = stream_blob_resolved(strm);
1465 		if (blob && blob->blob_location == BLOB_IN_WINDOWS_FILE)
1466 			blob->windows_file->sort_key = sort_key;
1467 	}
1468 }
1469 
1470 static inline bool
should_try_to_use_wimboot_hash(const struct wim_inode * inode,const struct winnt_scan_ctx * ctx)1471 should_try_to_use_wimboot_hash(const struct wim_inode *inode,
1472 			       const struct winnt_scan_ctx *ctx)
1473 {
1474 	/* Directories and encrypted files aren't valid for external backing. */
1475 	if (inode->i_attributes & (FILE_ATTRIBUTE_DIRECTORY |
1476 				   FILE_ATTRIBUTE_ENCRYPTED))
1477 		return false;
1478 
1479 	/* If the file is a reparse point, then try the hash fixup if it's a WOF
1480 	 * reparse point and we're in WIMBOOT mode.  Otherwise, try the hash
1481 	 * fixup if WOF may be attached. */
1482 	if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)
1483 		return (inode->i_reparse_tag == WIM_IO_REPARSE_TAG_WOF) &&
1484 			(ctx->params->add_flags & WIMLIB_ADD_FLAG_WIMBOOT);
1485 	return !ctx->wof_not_attached;
1486 }
1487 
1488 /*
1489  * This function implements an optimization for capturing files from a
1490  * filesystem with a backing WIM(s).  If a file is WIM-backed, then we can
1491  * retrieve the SHA-1 message digest of its original contents from its reparse
1492  * point.  This may eliminate the need to read the file's data and/or allow the
1493  * file's data to be immediately deduplicated with existing data in the WIM.
1494  *
1495  * If WOF is attached, then this function is merely an optimization, but
1496  * potentially a very effective one.  If WOF is detached, then this function
1497  * really causes WIM-backed files to be, effectively, automatically
1498  * "dereferenced" when possible; the unnamed data stream is updated to reference
1499  * the original contents and the reparse point is removed.
1500  *
1501  * This function returns 0 if the fixup succeeded or was intentionally not
1502  * executed.  Otherwise it returns an error code.
1503  */
1504 static noinline_for_stack int
try_to_use_wimboot_hash(HANDLE h,struct wim_inode * inode,struct winnt_scan_ctx * ctx)1505 try_to_use_wimboot_hash(HANDLE h, struct wim_inode *inode,
1506 			struct winnt_scan_ctx *ctx)
1507 {
1508 	struct blob_table *blob_table = ctx->params->blob_table;
1509 	struct wim_inode_stream *reparse_strm = NULL;
1510 	struct wim_inode_stream *strm;
1511 	struct blob_descriptor *blob;
1512 	u8 hash[SHA1_HASH_SIZE];
1513 	int ret;
1514 
1515 	if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1516 		struct reparse_buffer_disk rpbuf;
1517 		struct {
1518 			struct wof_external_info wof_info;
1519 			struct wim_provider_rpdata wim_info;
1520 		} *rpdata = (void *)rpbuf.rpdata;
1521 		struct blob_descriptor *reparse_blob;
1522 
1523 		/* The file has a WOF reparse point, so WOF must be detached.
1524 		 * We can read the reparse point directly.  */
1525 		ctx->wof_not_attached = true;
1526 		reparse_strm = inode_get_unnamed_stream(inode, STREAM_TYPE_REPARSE_POINT);
1527 		reparse_blob = stream_blob_resolved(reparse_strm);
1528 
1529 		if (!reparse_blob || reparse_blob->size < sizeof(*rpdata))
1530 			return 0;  /* Not a WIM-backed file  */
1531 
1532 		ret = read_blob_into_buf(reparse_blob, rpdata);
1533 		if (ret)
1534 			return ret;
1535 
1536 		if (rpdata->wof_info.version != WOF_CURRENT_VERSION ||
1537 		    rpdata->wof_info.provider != WOF_PROVIDER_WIM ||
1538 		    rpdata->wim_info.version != 2)
1539 			return 0;  /* Not a WIM-backed file  */
1540 
1541 		/* Okay, this is a WIM backed file.  Get its SHA-1 hash.  */
1542 		copy_hash(hash, rpdata->wim_info.unnamed_data_stream_hash);
1543 	} else {
1544 		struct {
1545 			struct wof_external_info wof_info;
1546 			struct wim_provider_external_info wim_info;
1547 		} out;
1548 		NTSTATUS status;
1549 
1550 		/* WOF may be attached.  Try reading this file's external
1551 		 * backing info.  */
1552 		status = winnt_fsctl(h, FSCTL_GET_EXTERNAL_BACKING,
1553 				     NULL, 0, &out, sizeof(out), NULL);
1554 
1555 		/* Is WOF not attached?  */
1556 		if (status == STATUS_INVALID_DEVICE_REQUEST ||
1557 		    status == STATUS_NOT_SUPPORTED) {
1558 			ctx->wof_not_attached = true;
1559 			return 0;
1560 		}
1561 
1562 		/* Is this file not externally backed?  */
1563 		if (status == STATUS_OBJECT_NOT_EXTERNALLY_BACKED)
1564 			return 0;
1565 
1566 		/* Does this file have an unknown type of external backing that
1567 		 * needed a larger information buffer?  */
1568 		if (status == STATUS_BUFFER_TOO_SMALL)
1569 			return 0;
1570 
1571 		/* Was there some other failure?  */
1572 		if (status != STATUS_SUCCESS) {
1573 			winnt_error(status,
1574 				    L"\"%ls\": FSCTL_GET_EXTERNAL_BACKING failed",
1575 				    printable_path(ctx));
1576 			return WIMLIB_ERR_STAT;
1577 		}
1578 
1579 		/* Is this file backed by a WIM?  */
1580 		if (out.wof_info.version != WOF_CURRENT_VERSION ||
1581 		    out.wof_info.provider != WOF_PROVIDER_WIM ||
1582 		    out.wim_info.version != WIM_PROVIDER_CURRENT_VERSION)
1583 			return 0;
1584 
1585 		/* Okay, this is a WIM backed file.  Get its SHA-1 hash.  */
1586 		copy_hash(hash, out.wim_info.unnamed_data_stream_hash);
1587 	}
1588 
1589 	/* If the file's unnamed data stream is nonempty, then fill in its hash
1590 	 * and deduplicate it if possible.
1591 	 *
1592 	 * With WOF detached, we require that the blob *must* de-duplicable for
1593 	 * any action can be taken, since without WOF we can't fall back to
1594 	 * getting the "dereferenced" data by reading the stream (the real
1595 	 * stream is sparse and contains all zeroes).  */
1596 	strm = inode_get_unnamed_data_stream(inode);
1597 	if (strm && (blob = stream_blob_resolved(strm))) {
1598 		struct blob_descriptor **back_ptr;
1599 
1600 		if (reparse_strm && !lookup_blob(blob_table, hash))
1601 			return 0;
1602 		back_ptr = retrieve_pointer_to_unhashed_blob(blob);
1603 		copy_hash(blob->hash, hash);
1604 		if (after_blob_hashed(blob, back_ptr, blob_table) != blob)
1605 			free_blob_descriptor(blob);
1606 	}
1607 
1608 	/* Remove the reparse point, if present.  */
1609 	if (reparse_strm) {
1610 		inode_remove_stream(inode, reparse_strm, blob_table);
1611 		inode->i_attributes &= ~(FILE_ATTRIBUTE_REPARSE_POINT |
1612 					 FILE_ATTRIBUTE_SPARSE_FILE);
1613 		if (inode->i_attributes == 0)
1614 			inode->i_attributes = FILE_ATTRIBUTE_NORMAL;
1615 	}
1616 
1617 	return 0;
1618 }
1619 
1620 struct file_info {
1621 	u32 attributes;
1622 	u32 num_links;
1623 	u64 creation_time;
1624 	u64 last_write_time;
1625 	u64 last_access_time;
1626 	u64 ino;
1627 	u64 end_of_file;
1628 	u32 ea_size;
1629 };
1630 
1631 static noinline_for_stack NTSTATUS
get_file_info(HANDLE h,struct file_info * info)1632 get_file_info(HANDLE h, struct file_info *info)
1633 {
1634 	IO_STATUS_BLOCK iosb;
1635 	NTSTATUS status;
1636 	FILE_ALL_INFORMATION all_info;
1637 
1638 	status = NtQueryInformationFile(h, &iosb, &all_info, sizeof(all_info),
1639 					FileAllInformation);
1640 
1641 	if (unlikely(!NT_SUCCESS(status) && status != STATUS_BUFFER_OVERFLOW))
1642 		return status;
1643 
1644 	info->attributes = all_info.BasicInformation.FileAttributes;
1645 	info->num_links = all_info.StandardInformation.NumberOfLinks;
1646 	info->creation_time = all_info.BasicInformation.CreationTime.QuadPart;
1647 	info->last_write_time = all_info.BasicInformation.LastWriteTime.QuadPart;
1648 	info->last_access_time = all_info.BasicInformation.LastAccessTime.QuadPart;
1649 	info->ino = all_info.InternalInformation.IndexNumber.QuadPart;
1650 	info->end_of_file = all_info.StandardInformation.EndOfFile.QuadPart;
1651 	info->ea_size = all_info.EaInformation.EaSize;
1652 	return STATUS_SUCCESS;
1653 }
1654 
1655 static void
get_volume_information(HANDLE h,struct winnt_scan_ctx * ctx)1656 get_volume_information(HANDLE h, struct winnt_scan_ctx *ctx)
1657 {
1658 	u8 _attr_info[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + 128] _aligned_attribute(8);
1659 	FILE_FS_ATTRIBUTE_INFORMATION *attr_info = (void *)_attr_info;
1660 	FILE_FS_VOLUME_INFORMATION vol_info;
1661 	struct file_info file_info;
1662 	IO_STATUS_BLOCK iosb;
1663 	NTSTATUS status;
1664 
1665 	/* Get volume flags  */
1666 	status = NtQueryVolumeInformationFile(h, &iosb, attr_info,
1667 					      sizeof(_attr_info),
1668 					      FileFsAttributeInformation);
1669 	if (NT_SUCCESS(status)) {
1670 		ctx->vol_flags = attr_info->FileSystemAttributes;
1671 		ctx->is_ntfs = (attr_info->FileSystemNameLength == 4 * sizeof(wchar_t)) &&
1672 				!wmemcmp(attr_info->FileSystemName, L"NTFS", 4);
1673 	} else {
1674 		winnt_warning(status, L"\"%ls\": Can't get volume attributes",
1675 			      printable_path(ctx));
1676 	}
1677 
1678 	/* Get volume ID.  */
1679 	status = NtQueryVolumeInformationFile(h, &iosb, &vol_info,
1680 					      sizeof(vol_info),
1681 					      FileFsVolumeInformation);
1682 	if ((NT_SUCCESS(status) || status == STATUS_BUFFER_OVERFLOW) &&
1683 	    (iosb.Information >= offsetof(FILE_FS_VOLUME_INFORMATION,
1684 					  VolumeSerialNumber) +
1685 	     sizeof(vol_info.VolumeSerialNumber)))
1686 	{
1687 		ctx->params->capture_root_dev = vol_info.VolumeSerialNumber;
1688 	} else {
1689 		winnt_warning(status, L"\"%ls\": Can't get volume ID",
1690 			      printable_path(ctx));
1691 	}
1692 
1693 	/* Get inode number.  */
1694 	status = get_file_info(h, &file_info);
1695 	if (NT_SUCCESS(status)) {
1696 		ctx->params->capture_root_ino = file_info.ino;
1697 	} else {
1698 		winnt_warning(status, L"\"%ls\": Can't get file information",
1699 			      printable_path(ctx));
1700 	}
1701 }
1702 
1703 static int
winnt_build_dentry_tree_recursive(struct wim_dentry ** root_ret,HANDLE cur_dir,const wchar_t * relative_path,size_t relative_path_nchars,const wchar_t * filename,struct winnt_scan_ctx * ctx)1704 winnt_build_dentry_tree_recursive(struct wim_dentry **root_ret,
1705 				  HANDLE cur_dir,
1706 				  const wchar_t *relative_path,
1707 				  size_t relative_path_nchars,
1708 				  const wchar_t *filename,
1709 				  struct winnt_scan_ctx *ctx)
1710 {
1711 	struct wim_dentry *root = NULL;
1712 	struct wim_inode *inode = NULL;
1713 	HANDLE h = NULL;
1714 	int ret;
1715 	NTSTATUS status;
1716 	struct file_info file_info;
1717 	u64 sort_key;
1718 
1719 	ret = try_exclude(ctx->params);
1720 	if (unlikely(ret < 0)) /* Excluded? */
1721 		goto out_progress;
1722 	if (unlikely(ret > 0)) /* Error? */
1723 		goto out;
1724 
1725 	/* Open the file with permission to read metadata.  Although we will
1726 	 * later need a handle with FILE_LIST_DIRECTORY permission (or,
1727 	 * equivalently, FILE_READ_DATA; they're the same numeric value) if the
1728 	 * file is a directory, it can significantly slow things down to request
1729 	 * this permission on all nondirectories.  Perhaps it causes Windows to
1730 	 * start prefetching the file contents...  */
1731 	status = winnt_openat(cur_dir, relative_path, relative_path_nchars,
1732 			      FILE_READ_ATTRIBUTES | FILE_READ_EA |
1733 				READ_CONTROL | ACCESS_SYSTEM_SECURITY,
1734 			      &h);
1735 	if (unlikely(!NT_SUCCESS(status))) {
1736 		if (status == STATUS_DELETE_PENDING) {
1737 			WARNING("\"%ls\": Deletion pending; skipping file",
1738 				printable_path(ctx));
1739 			ret = 0;
1740 			goto out;
1741 		}
1742 		if (status == STATUS_SHARING_VIOLATION) {
1743 			ERROR("Can't open \"%ls\":\n"
1744 			      "        File is in use by another process! "
1745 			      "Consider using snapshot (VSS) mode.",
1746 			      printable_path(ctx));
1747 			ret = WIMLIB_ERR_OPEN;
1748 			goto out;
1749 		}
1750 		winnt_error(status, L"\"%ls\": Can't open file",
1751 			    printable_path(ctx));
1752 		if (status == STATUS_FVE_LOCKED_VOLUME)
1753 			ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
1754 		else
1755 			ret = WIMLIB_ERR_OPEN;
1756 		goto out;
1757 	}
1758 
1759 	/* Get information about the file.  */
1760 	status = get_file_info(h, &file_info);
1761 	if (!NT_SUCCESS(status)) {
1762 		winnt_error(status, L"\"%ls\": Can't get file information",
1763 			    printable_path(ctx));
1764 		ret = WIMLIB_ERR_STAT;
1765 		goto out;
1766 	}
1767 
1768 	/* Create a WIM dentry with an associated inode, which may be shared.
1769 	 *
1770 	 * However, we need to explicitly check for directories and files with
1771 	 * only 1 link and refuse to hard link them.  This is because Windows
1772 	 * has a bug where it can return duplicate File IDs for files and
1773 	 * directories on the FAT filesystem.
1774 	 *
1775 	 * Since we don't follow mount points on Windows, we don't need to query
1776 	 * the volume ID per-file.  Just once, for the root, is enough.  But we
1777 	 * can't simply pass 0, because then there could be inode collisions
1778 	 * among multiple calls to win32_build_dentry_tree() that are scanning
1779 	 * files on different volumes.  */
1780 	ret = inode_table_new_dentry(ctx->params->inode_table,
1781 				     filename,
1782 				     file_info.ino,
1783 				     ctx->params->capture_root_dev,
1784 				     (file_info.num_links <= 1),
1785 				     &root);
1786 	if (ret)
1787 		goto out;
1788 
1789 	/* Get the short (DOS) name of the file.  */
1790 	status = winnt_get_short_name(h, root);
1791 
1792 	/* If we can't read the short filename for any reason other than
1793 	 * out-of-memory, just ignore the error and assume the file has no short
1794 	 * name.  This shouldn't be an issue, since the short names are
1795 	 * essentially obsolete anyway.  */
1796 	if (unlikely(status == STATUS_NO_MEMORY)) {
1797 		ret = WIMLIB_ERR_NOMEM;
1798 		goto out;
1799 	}
1800 
1801 	inode = root->d_inode;
1802 
1803 	if (inode->i_nlink > 1) {
1804 		/* Shared inode (hard link); skip reading per-inode information.
1805 		 */
1806 		goto out_progress;
1807 	}
1808 
1809 	inode->i_attributes = file_info.attributes;
1810 	inode->i_creation_time = file_info.creation_time;
1811 	inode->i_last_write_time = file_info.last_write_time;
1812 	inode->i_last_access_time = file_info.last_access_time;
1813 
1814 	/* Get the file's security descriptor, unless we are capturing in
1815 	 * NO_ACLS mode or the volume does not support security descriptors.  */
1816 	if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)
1817 	    && (ctx->vol_flags & FILE_PERSISTENT_ACLS))
1818 	{
1819 		ret = winnt_load_security_descriptor(h, inode, ctx);
1820 		if (ret)
1821 			goto out;
1822 	}
1823 
1824 	/* Get the file's object ID.  */
1825 	ret = winnt_load_object_id(h, inode, ctx);
1826 	if (ret)
1827 		goto out;
1828 
1829 	/* Get the file's extended attributes.  */
1830 	if (unlikely(file_info.ea_size != 0)) {
1831 		ret = winnt_load_xattrs(h, inode, ctx, file_info.ea_size);
1832 		if (ret)
1833 			goto out;
1834 	}
1835 
1836 	/* If this is a reparse point, load the reparse data.  */
1837 	if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1838 		ret = winnt_load_reparse_data(h, inode, ctx);
1839 		if (ret)
1840 			goto out;
1841 	}
1842 
1843 	sort_key = get_sort_key(h);
1844 
1845 	if (unlikely(inode->i_attributes & FILE_ATTRIBUTE_ENCRYPTED)) {
1846 		/* Load information about the raw encrypted data.  This is
1847 		 * needed for any directory or non-directory that has
1848 		 * FILE_ATTRIBUTE_ENCRYPTED set.
1849 		 *
1850 		 * Note: since OpenEncryptedFileRaw() fails with
1851 		 * ERROR_SHARING_VIOLATION if there are any open handles to the
1852 		 * file, we have to close the file and re-open it later if
1853 		 * needed.  */
1854 		NtClose(h);
1855 		h = NULL;
1856 		ret = winnt_scan_efsrpc_raw_data(inode, ctx);
1857 		if (ret)
1858 			goto out;
1859 	} else {
1860 		/*
1861 		 * Load information about data streams (unnamed and named).
1862 		 *
1863 		 * Skip this step for encrypted files, since the data from
1864 		 * ReadEncryptedFileRaw() already contains all data streams (and
1865 		 * they do in fact all get restored by WriteEncryptedFileRaw().)
1866 		 *
1867 		 * Note: WIMGAPI (as of Windows 8.1) gets wrong and stores both
1868 		 * the EFSRPC data and the named data stream(s)...!
1869 		 */
1870 		ret = winnt_scan_data_streams(h,
1871 					      inode,
1872 					      file_info.end_of_file,
1873 					      ctx);
1874 		if (ret)
1875 			goto out;
1876 	}
1877 
1878 	if (unlikely(should_try_to_use_wimboot_hash(inode, ctx))) {
1879 		ret = try_to_use_wimboot_hash(h, inode, ctx);
1880 		if (ret)
1881 			goto out;
1882 	}
1883 
1884 	set_sort_key(inode, sort_key);
1885 
1886 	if (inode_is_directory(inode)) {
1887 
1888 		/* Directory: recurse to children.  */
1889 
1890 		/* Re-open the directory with FILE_LIST_DIRECTORY access.  */
1891 		if (h) {
1892 			NtClose(h);
1893 			h = NULL;
1894 		}
1895 		status = winnt_openat(cur_dir, relative_path,
1896 				      relative_path_nchars, FILE_LIST_DIRECTORY,
1897 				      &h);
1898 		if (!NT_SUCCESS(status)) {
1899 			winnt_error(status, L"\"%ls\": Can't open directory",
1900 				    printable_path(ctx));
1901 			ret = WIMLIB_ERR_OPEN;
1902 			goto out;
1903 		}
1904 		ret = winnt_recurse_directory(h, root, ctx);
1905 		if (ret)
1906 			goto out;
1907 	}
1908 
1909 out_progress:
1910 	if (likely(root))
1911 		ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
1912 	else
1913 		ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
1914 out:
1915 	if (likely(h))
1916 		NtClose(h);
1917 	if (unlikely(ret)) {
1918 		free_dentry_tree(root, ctx->params->blob_table);
1919 		root = NULL;
1920 		ret = report_scan_error(ctx->params, ret);
1921 	}
1922 	*root_ret = root;
1923 	return ret;
1924 }
1925 
1926 static void
winnt_do_scan_warnings(const wchar_t * path,const struct winnt_scan_ctx * ctx)1927 winnt_do_scan_warnings(const wchar_t *path, const struct winnt_scan_ctx *ctx)
1928 {
1929 	if (likely(ctx->num_get_sacl_priv_notheld == 0 &&
1930 		   ctx->num_get_sd_access_denied == 0))
1931 		return;
1932 
1933 	WARNING("Scan of \"%ls\" complete, but with one or more warnings:", path);
1934 	if (ctx->num_get_sacl_priv_notheld != 0) {
1935 		WARNING("- Could not capture SACL (System Access Control List)\n"
1936 			"            on %lu files or directories.",
1937 			ctx->num_get_sacl_priv_notheld);
1938 	}
1939 	if (ctx->num_get_sd_access_denied != 0) {
1940 		WARNING("- Could not capture security descriptor at all\n"
1941 			"            on %lu files or directories.",
1942 			ctx->num_get_sd_access_denied);
1943 	}
1944 	WARNING("To fully capture all security descriptors, run the program\n"
1945 		"          with Administrator rights.");
1946 }
1947 
1948 /*----------------------------------------------------------------------------*
1949  *                         Fast MFT scan implementation                       *
1950  *----------------------------------------------------------------------------*/
1951 
1952 #define ENABLE_FAST_MFT_SCAN	1
1953 
1954 #ifdef ENABLE_FAST_MFT_SCAN
1955 
1956 typedef struct {
1957 	u64 StartingCluster;
1958 	u64 ClusterCount;
1959 } CLUSTER_RANGE;
1960 
1961 typedef struct {
1962 	u64 StartingFileReferenceNumber;
1963 	u64 EndingFileReferenceNumber;
1964 } FILE_REFERENCE_RANGE;
1965 
1966 /* The FSCTL_QUERY_FILE_LAYOUT ioctl.  This ioctl can be used on Windows 8 and
1967  * later to scan the MFT of an NTFS volume.  */
1968 #define FSCTL_QUERY_FILE_LAYOUT		CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 157, METHOD_NEITHER, FILE_ANY_ACCESS)
1969 
1970 /* The input to FSCTL_QUERY_FILE_LAYOUT  */
1971 typedef struct {
1972 	u32 NumberOfPairs;
1973 #define QUERY_FILE_LAYOUT_RESTART					0x00000001
1974 #define QUERY_FILE_LAYOUT_INCLUDE_NAMES					0x00000002
1975 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS				0x00000004
1976 #define QUERY_FILE_LAYOUT_INCLUDE_EXTENTS				0x00000008
1977 #define QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO				0x00000010
1978 #define QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED	0x00000020
1979 	u32 Flags;
1980 #define QUERY_FILE_LAYOUT_FILTER_TYPE_NONE		0
1981 #define QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS		1
1982 #define QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID		2
1983 #define QUERY_FILE_LAYOUT_NUM_FILTER_TYPES		3
1984 	u32 FilterType;
1985 	u32 Reserved;
1986 	union {
1987 		CLUSTER_RANGE ClusterRanges[1];
1988 		FILE_REFERENCE_RANGE FileReferenceRanges[1];
1989 	} Filter;
1990 } QUERY_FILE_LAYOUT_INPUT;
1991 
1992 /* The header of the buffer returned by FSCTL_QUERY_FILE_LAYOUT  */
1993 typedef struct {
1994 	u32 FileEntryCount;
1995 	u32 FirstFileOffset;
1996 #define QUERY_FILE_LAYOUT_SINGLE_INSTANCED				0x00000001
1997 	u32 Flags;
1998 	u32 Reserved;
1999 } QUERY_FILE_LAYOUT_OUTPUT;
2000 
2001 /* Inode information returned by FSCTL_QUERY_FILE_LAYOUT  */
2002 typedef struct {
2003 	u32 Version;
2004 	u32 NextFileOffset;
2005 	u32 Flags;
2006 	u32 FileAttributes;
2007 	u64 FileReferenceNumber;
2008 	u32 FirstNameOffset;
2009 	u32 FirstStreamOffset;
2010 	u32 ExtraInfoOffset;
2011 	u32 Reserved;
2012 } FILE_LAYOUT_ENTRY;
2013 
2014 /* Extra inode information returned by FSCTL_QUERY_FILE_LAYOUT  */
2015 typedef struct {
2016 	struct {
2017 		u64 CreationTime;
2018 		u64 LastAccessTime;
2019 		u64 LastWriteTime;
2020 		u64 ChangeTime;
2021 		u32 FileAttributes;
2022 	} BasicInformation;
2023 	u32 OwnerId;
2024 	u32 SecurityId;
2025 	s64 Usn;
2026 } FILE_LAYOUT_INFO_ENTRY;
2027 
2028 /* Filename (or dentry) information returned by FSCTL_QUERY_FILE_LAYOUT  */
2029 typedef struct {
2030 	u32 NextNameOffset;
2031 #define FILE_LAYOUT_NAME_ENTRY_PRIMARY	0x00000001
2032 #define FILE_LAYOUT_NAME_ENTRY_DOS	0x00000002
2033 	u32 Flags;
2034 	u64 ParentFileReferenceNumber;
2035 	u32 FileNameLength;
2036 	u32 Reserved;
2037 	wchar_t FileName[1];
2038 } FILE_LAYOUT_NAME_ENTRY;
2039 
2040 /* Stream information returned by FSCTL_QUERY_FILE_LAYOUT  */
2041 typedef struct {
2042 	u32 Version;
2043 	u32 NextStreamOffset;
2044 #define STREAM_LAYOUT_ENTRY_IMMOVABLE			0x00000001
2045 #define STREAM_LAYOUT_ENTRY_PINNED			0x00000002
2046 #define STREAM_LAYOUT_ENTRY_RESIDENT			0x00000004
2047 #define STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED	0x00000008
2048 	u32 Flags;
2049 	u32 ExtentInformationOffset;
2050 	u64 AllocationSize;
2051 	u64 EndOfFile;
2052 	u64 Reserved;
2053 	u32 AttributeFlags;
2054 	u32 StreamIdentifierLength;
2055 	wchar_t StreamIdentifier[1];
2056 } STREAM_LAYOUT_ENTRY;
2057 
2058 
2059 typedef struct {
2060 #define STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS	0x00000001
2061 #define STREAM_EXTENT_ENTRY_ALL_EXTENTS			0x00000002
2062 	u32 Flags;
2063 	union {
2064 		RETRIEVAL_POINTERS_BUFFER RetrievalPointers;
2065 	} ExtentInformation;
2066 } STREAM_EXTENT_ENTRY;
2067 
2068 /* Extract the MFT number part of the full inode number  */
2069 #define NTFS_MFT_NO(ref)	((ref) & (((u64)1 << 48) - 1))
2070 
2071 /* Is the file the root directory of the NTFS volume?  The root directory always
2072  * occupies MFT record 5.  */
2073 #define NTFS_IS_ROOT_FILE(ino)	(NTFS_MFT_NO(ino) == 5)
2074 
2075 /* Is the file a special NTFS file, other than the root directory?  The special
2076  * files are the first 16 records in the MFT.  */
2077 #define NTFS_IS_SPECIAL_FILE(ino)			\
2078 	(NTFS_MFT_NO(ino) <= 15 && !NTFS_IS_ROOT_FILE(ino))
2079 
2080 #define NTFS_SPECIAL_STREAM_OBJECT_ID		0x00000001
2081 #define NTFS_SPECIAL_STREAM_EA			0x00000002
2082 #define NTFS_SPECIAL_STREAM_EA_INFORMATION	0x00000004
2083 
2084 /* Intermediate inode structure.  This is used to temporarily save information
2085  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_inode'.  */
2086 struct ntfs_inode {
2087 	struct avl_tree_node index_node;
2088 	u64 ino;
2089 	u64 creation_time;
2090 	u64 last_access_time;
2091 	u64 last_write_time;
2092 	u64 starting_lcn;
2093 	u32 attributes;
2094 	u32 security_id;
2095 	u32 num_aliases;
2096 	u32 num_streams;
2097 	u32 special_streams;
2098 	u32 first_stream_offset;
2099 	struct ntfs_dentry *first_child;
2100 	wchar_t short_name[13];
2101 };
2102 
2103 /* Intermediate dentry structure.  This is used to temporarily save information
2104  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct wim_dentry'. */
2105 struct ntfs_dentry {
2106 	u32 offset_from_inode : 31;
2107 	u32 is_primary : 1;
2108 	union {
2109 		/* Note: build_children_lists() replaces 'parent_ino' with
2110 		 * 'next_child'.  */
2111 		u64 parent_ino;
2112 		struct ntfs_dentry *next_child;
2113 	};
2114 	wchar_t name[0];
2115 };
2116 
2117 /* Intermediate stream structure.  This is used to temporarily save information
2118  * from FSCTL_QUERY_FILE_LAYOUT before creating the full 'struct
2119  * wim_inode_stream'.  */
2120 struct ntfs_stream {
2121 	u64 size;
2122 	wchar_t name[0];
2123 };
2124 
2125 /* Map of all known NTFS inodes, keyed by inode number  */
2126 struct ntfs_inode_map {
2127 	struct avl_tree_node *root;
2128 };
2129 
2130 #define NTFS_INODE(node)				\
2131 	avl_tree_entry((node), struct ntfs_inode, index_node)
2132 
2133 #define SKIP_ALIGNED(p, size)	((void *)(p) + ALIGN((size), 8))
2134 
2135 /* Get a pointer to the first dentry of the inode.  */
2136 #define FIRST_DENTRY(ni) SKIP_ALIGNED((ni), sizeof(struct ntfs_inode))
2137 
2138 /* Get a pointer to the first stream of the inode.  */
2139 #define FIRST_STREAM(ni) ((const void *)ni + ni->first_stream_offset)
2140 
2141 /* Advance to the next dentry of the inode.  */
2142 #define NEXT_DENTRY(nd)	 SKIP_ALIGNED((nd), sizeof(struct ntfs_dentry) +   \
2143 				(wcslen((nd)->name) + 1) * sizeof(wchar_t))
2144 
2145 /* Advance to the next stream of the inode.  */
2146 #define NEXT_STREAM(ns)	 SKIP_ALIGNED((ns), sizeof(struct ntfs_stream) +   \
2147 				(wcslen((ns)->name) + 1) * sizeof(wchar_t))
2148 
2149 static int
_avl_cmp_ntfs_inodes(const struct avl_tree_node * node1,const struct avl_tree_node * node2)2150 _avl_cmp_ntfs_inodes(const struct avl_tree_node *node1,
2151 		     const struct avl_tree_node *node2)
2152 {
2153 	return cmp_u64(NTFS_INODE(node1)->ino, NTFS_INODE(node2)->ino);
2154 }
2155 
2156 /* Adds an NTFS inode to the map.  */
2157 static void
ntfs_inode_map_add_inode(struct ntfs_inode_map * map,struct ntfs_inode * ni)2158 ntfs_inode_map_add_inode(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2159 {
2160 	if (avl_tree_insert(&map->root, &ni->index_node, _avl_cmp_ntfs_inodes)) {
2161 		WARNING("Inode 0x%016"PRIx64" is a duplicate!", ni->ino);
2162 		FREE(ni);
2163 	}
2164 }
2165 
2166 /* Find an ntfs_inode in the map by inode number.  Returns NULL if not found. */
2167 static struct ntfs_inode *
ntfs_inode_map_lookup(struct ntfs_inode_map * map,u64 ino)2168 ntfs_inode_map_lookup(struct ntfs_inode_map *map, u64 ino)
2169 {
2170 	struct ntfs_inode tmp;
2171 	struct avl_tree_node *res;
2172 
2173 	tmp.ino = ino;
2174 	res = avl_tree_lookup_node(map->root, &tmp.index_node, _avl_cmp_ntfs_inodes);
2175 	if (!res)
2176 		return NULL;
2177 	return NTFS_INODE(res);
2178 }
2179 
2180 /* Remove an ntfs_inode from the map and free it.  */
2181 static void
ntfs_inode_map_remove(struct ntfs_inode_map * map,struct ntfs_inode * ni)2182 ntfs_inode_map_remove(struct ntfs_inode_map *map, struct ntfs_inode *ni)
2183 {
2184 	avl_tree_remove(&map->root, &ni->index_node);
2185 	FREE(ni);
2186 }
2187 
2188 /* Free all ntfs_inodes in the map.  */
2189 static void
ntfs_inode_map_destroy(struct ntfs_inode_map * map)2190 ntfs_inode_map_destroy(struct ntfs_inode_map *map)
2191 {
2192 	struct ntfs_inode *ni;
2193 
2194 	avl_tree_for_each_in_postorder(ni, map->root, struct ntfs_inode, index_node)
2195 		FREE(ni);
2196 }
2197 
2198 static bool
file_has_streams(const FILE_LAYOUT_ENTRY * file)2199 file_has_streams(const FILE_LAYOUT_ENTRY *file)
2200 {
2201 	return (file->FirstStreamOffset != 0) &&
2202 		!(file->FileAttributes & FILE_ATTRIBUTE_ENCRYPTED);
2203 }
2204 
2205 static bool
is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY * name)2206 is_valid_name_entry(const FILE_LAYOUT_NAME_ENTRY *name)
2207 {
2208 	return name->FileNameLength > 0 &&
2209 		name->FileNameLength % 2 == 0 &&
2210 		!wmemchr(name->FileName, L'\0', name->FileNameLength / 2) &&
2211 		(!(name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) ||
2212 		 name->FileNameLength <= 24);
2213 }
2214 
2215 /* Validate the FILE_LAYOUT_NAME_ENTRYs of the specified file and compute the
2216  * total length in bytes of the ntfs_dentry structures needed to hold the name
2217  * information.  */
2218 static int
validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY * file,size_t * total_length_ret)2219 validate_names_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2220 					size_t *total_length_ret)
2221 {
2222 	const FILE_LAYOUT_NAME_ENTRY *name =
2223 		(const void *)file + file->FirstNameOffset;
2224 	size_t total = 0;
2225 	size_t num_long_names = 0;
2226 
2227 	for (;;) {
2228 		if (unlikely(!is_valid_name_entry(name))) {
2229 			ERROR("Invalid FILE_LAYOUT_NAME_ENTRY! "
2230 			      "FileReferenceNumber=0x%016"PRIx64", "
2231 			      "FileNameLength=%"PRIu32", "
2232 			      "FileName=%.*ls, Flags=0x%08"PRIx32,
2233 			      file->FileReferenceNumber,
2234 			      name->FileNameLength,
2235 			      (int)(name->FileNameLength / 2),
2236 			      name->FileName, name->Flags);
2237 			return WIMLIB_ERR_UNSUPPORTED;
2238 		}
2239 		if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2240 			num_long_names++;
2241 			total += ALIGN(sizeof(struct ntfs_dentry) +
2242 				       name->FileNameLength + sizeof(wchar_t),
2243 				       8);
2244 		}
2245 		if (name->NextNameOffset == 0)
2246 			break;
2247 		name = (const void *)name + name->NextNameOffset;
2248 	}
2249 
2250 	if (unlikely(num_long_names == 0)) {
2251 		ERROR("Inode 0x%016"PRIx64" has no long names!",
2252 		      file->FileReferenceNumber);
2253 		return WIMLIB_ERR_UNSUPPORTED;
2254 	}
2255 
2256 	*total_length_ret = total;
2257 	return 0;
2258 }
2259 
2260 static bool
is_valid_stream_entry(const STREAM_LAYOUT_ENTRY * stream)2261 is_valid_stream_entry(const STREAM_LAYOUT_ENTRY *stream)
2262 {
2263 	return stream->StreamIdentifierLength % 2 == 0 &&
2264 		!wmemchr(stream->StreamIdentifier , L'\0',
2265 			 stream->StreamIdentifierLength / 2);
2266 }
2267 
2268 /* assumes that 'id' is a wide string literal */
2269 #define stream_has_identifier(stream, id)				\
2270 	((stream)->StreamIdentifierLength == sizeof(id) - 2 &&		\
2271 	 !memcmp((stream)->StreamIdentifier, id, sizeof(id) - 2))
2272 /*
2273  * If the specified STREAM_LAYOUT_ENTRY represents a DATA stream as opposed to
2274  * some other type of NTFS stream such as a STANDARD_INFORMATION stream, return
2275  * true and set *stream_name_ret and *stream_name_nchars_ret to specify just the
2276  * stream name.  For example, ":foo:$DATA" would become "foo" with length 3
2277  * characters.  Otherwise return false.
2278  */
2279 static bool
use_stream(const FILE_LAYOUT_ENTRY * file,const STREAM_LAYOUT_ENTRY * stream,const wchar_t ** stream_name_ret,size_t * stream_name_nchars_ret)2280 use_stream(const FILE_LAYOUT_ENTRY *file, const STREAM_LAYOUT_ENTRY *stream,
2281 	   const wchar_t **stream_name_ret, size_t *stream_name_nchars_ret)
2282 {
2283 	const wchar_t *stream_name;
2284 	size_t stream_name_nchars;
2285 
2286 	if (stream->StreamIdentifierLength == 0) {
2287 		/* The unnamed data stream may be given as an empty string
2288 		 * rather than as "::$DATA".  Handle it both ways.  */
2289 		stream_name = L"";
2290 		stream_name_nchars = 0;
2291 	} else if (!get_data_stream_name(stream->StreamIdentifier,
2292 					 stream->StreamIdentifierLength / 2,
2293 					 &stream_name, &stream_name_nchars))
2294 		return false;
2295 
2296 	/* Skip the unnamed data stream for directories.  */
2297 	if (stream_name_nchars == 0 &&
2298 	    (file->FileAttributes & FILE_ATTRIBUTE_DIRECTORY))
2299 		return false;
2300 
2301 	*stream_name_ret = stream_name;
2302 	*stream_name_nchars_ret = stream_name_nchars;
2303 	return true;
2304 }
2305 
2306 /* Validate the STREAM_LAYOUT_ENTRYs of the specified file and compute the total
2307  * length in bytes of the ntfs_stream structures needed to hold the stream
2308  * information.  In addition, set *special_streams_ret to a bitmask of special
2309  * stream types that were found.  */
2310 static int
validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY * file,size_t * total_length_ret,u32 * special_streams_ret)2311 validate_streams_and_compute_total_length(const FILE_LAYOUT_ENTRY *file,
2312 					  size_t *total_length_ret,
2313 					  u32 *special_streams_ret)
2314 {
2315 	const STREAM_LAYOUT_ENTRY *stream =
2316 		(const void *)file + file->FirstStreamOffset;
2317 	size_t total = 0;
2318 	u32 special_streams = 0;
2319 
2320 	for (;;) {
2321 		const wchar_t *name;
2322 		size_t name_nchars;
2323 
2324 		if (unlikely(!is_valid_stream_entry(stream))) {
2325 			WARNING("Invalid STREAM_LAYOUT_ENTRY! "
2326 				"FileReferenceNumber=0x%016"PRIx64", "
2327 				"StreamIdentifierLength=%"PRIu32", "
2328 				"StreamIdentifier=%.*ls",
2329 				file->FileReferenceNumber,
2330 				stream->StreamIdentifierLength,
2331 				(int)(stream->StreamIdentifierLength / 2),
2332 				stream->StreamIdentifier);
2333 			return WIMLIB_ERR_UNSUPPORTED;
2334 		}
2335 
2336 		if (use_stream(file, stream, &name, &name_nchars)) {
2337 			total += ALIGN(sizeof(struct ntfs_stream) +
2338 				       (name_nchars + 1) * sizeof(wchar_t), 8);
2339 		} else if (stream_has_identifier(stream, L"::$OBJECT_ID")) {
2340 			special_streams |= NTFS_SPECIAL_STREAM_OBJECT_ID;
2341 		} else if (stream_has_identifier(stream, L"::$EA")) {
2342 			special_streams |= NTFS_SPECIAL_STREAM_EA;
2343 		} else if (stream_has_identifier(stream, L"::$EA_INFORMATION")) {
2344 			special_streams |= NTFS_SPECIAL_STREAM_EA_INFORMATION;
2345 		}
2346 		if (stream->NextStreamOffset == 0)
2347 			break;
2348 		stream = (const void *)stream + stream->NextStreamOffset;
2349 	}
2350 
2351 	*total_length_ret = total;
2352 	*special_streams_ret = special_streams;
2353 	return 0;
2354 }
2355 
2356 static void *
load_name_information(const FILE_LAYOUT_ENTRY * file,struct ntfs_inode * ni,void * p)2357 load_name_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2358 		      void *p)
2359 {
2360 	const FILE_LAYOUT_NAME_ENTRY *name =
2361 		(const void *)file + file->FirstNameOffset;
2362 	for (;;) {
2363 		struct ntfs_dentry *nd = p;
2364 		/* Note that a name may be just a short (DOS) name, just a long
2365 		 * name, or both a short name and a long name.  If there is a
2366 		 * short name, one name should also be marked as "primary" to
2367 		 * indicate which long name the short name is associated with.
2368 		 * Also, there should be at most one short name per inode.  */
2369 		if (name->Flags & FILE_LAYOUT_NAME_ENTRY_DOS) {
2370 			memcpy(ni->short_name,
2371 			       name->FileName, name->FileNameLength);
2372 			ni->short_name[name->FileNameLength / 2] = L'\0';
2373 		}
2374 		if (name->Flags != FILE_LAYOUT_NAME_ENTRY_DOS) {
2375 			ni->num_aliases++;
2376 			nd->offset_from_inode = (u8 *)nd - (u8 *)ni;
2377 			nd->is_primary = ((name->Flags &
2378 					   FILE_LAYOUT_NAME_ENTRY_PRIMARY) != 0);
2379 			nd->parent_ino = name->ParentFileReferenceNumber;
2380 			memcpy(nd->name, name->FileName, name->FileNameLength);
2381 			nd->name[name->FileNameLength / 2] = L'\0';
2382 			p += ALIGN(sizeof(struct ntfs_dentry) +
2383 				   name->FileNameLength + sizeof(wchar_t), 8);
2384 		}
2385 		if (name->NextNameOffset == 0)
2386 			break;
2387 		name = (const void *)name + name->NextNameOffset;
2388 	}
2389 	return p;
2390 }
2391 
2392 static u64
load_starting_lcn(const STREAM_LAYOUT_ENTRY * stream)2393 load_starting_lcn(const STREAM_LAYOUT_ENTRY *stream)
2394 {
2395 	const STREAM_EXTENT_ENTRY *entry;
2396 
2397 	if (stream->ExtentInformationOffset == 0)
2398 		return 0;
2399 
2400 	entry = (const void *)stream + stream->ExtentInformationOffset;
2401 
2402 	if (!(entry->Flags & STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS))
2403 		return 0;
2404 
2405 	return extract_starting_lcn(&entry->ExtentInformation.RetrievalPointers);
2406 }
2407 
2408 static void *
load_stream_information(const FILE_LAYOUT_ENTRY * file,struct ntfs_inode * ni,void * p)2409 load_stream_information(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode *ni,
2410 			void *p)
2411 {
2412 	const STREAM_LAYOUT_ENTRY *stream =
2413 		(const void *)file + file->FirstStreamOffset;
2414 	const u32 first_stream_offset = (const u8 *)p - (const u8 *)ni;
2415 	for (;;) {
2416 		struct ntfs_stream *ns = p;
2417 		const wchar_t *name;
2418 		size_t name_nchars;
2419 
2420 		if (use_stream(file, stream, &name, &name_nchars)) {
2421 			ni->first_stream_offset = first_stream_offset;
2422 			ni->num_streams++;
2423 			if (name_nchars == 0)
2424 				ni->starting_lcn = load_starting_lcn(stream);
2425 			ns->size = stream->EndOfFile;
2426 			wmemcpy(ns->name, name, name_nchars);
2427 			ns->name[name_nchars] = L'\0';
2428 			p += ALIGN(sizeof(struct ntfs_stream) +
2429 				   (name_nchars + 1) * sizeof(wchar_t), 8);
2430 		}
2431 		if (stream->NextStreamOffset == 0)
2432 			break;
2433 		stream = (const void *)stream + stream->NextStreamOffset;
2434 	}
2435 	return p;
2436 }
2437 
2438 /* Process the information for a file given by FSCTL_QUERY_FILE_LAYOUT.  */
2439 static int
load_one_file(const FILE_LAYOUT_ENTRY * file,struct ntfs_inode_map * inode_map)2440 load_one_file(const FILE_LAYOUT_ENTRY *file, struct ntfs_inode_map *inode_map)
2441 {
2442 	const FILE_LAYOUT_INFO_ENTRY *info =
2443 		(const void *)file + file->ExtraInfoOffset;
2444 	size_t inode_size;
2445 	struct ntfs_inode *ni;
2446 	size_t n;
2447 	int ret;
2448 	void *p;
2449 	u32 special_streams = 0;
2450 
2451 	inode_size = ALIGN(sizeof(struct ntfs_inode), 8);
2452 
2453 	/* The root file should have no names, and all other files should have
2454 	 * at least one name.  But just in case, we ignore the names of the root
2455 	 * file, and we ignore any non-root file with no names.  */
2456 	if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber)) {
2457 		if (file->FirstNameOffset == 0)
2458 			return 0;
2459 		ret = validate_names_and_compute_total_length(file, &n);
2460 		if (ret)
2461 			return ret;
2462 		inode_size += n;
2463 	}
2464 
2465 	if (file_has_streams(file)) {
2466 		ret = validate_streams_and_compute_total_length(file, &n,
2467 								&special_streams);
2468 		if (ret)
2469 			return ret;
2470 		inode_size += n;
2471 	}
2472 
2473 	/* To save memory, we allocate the ntfs_dentry's and ntfs_stream's in
2474 	 * the same memory block as their ntfs_inode.  */
2475 	ni = CALLOC(1, inode_size);
2476 	if (!ni)
2477 		return WIMLIB_ERR_NOMEM;
2478 
2479 	ni->ino = file->FileReferenceNumber;
2480 	ni->attributes = info->BasicInformation.FileAttributes;
2481 	ni->creation_time = info->BasicInformation.CreationTime;
2482 	ni->last_write_time = info->BasicInformation.LastWriteTime;
2483 	ni->last_access_time = info->BasicInformation.LastAccessTime;
2484 	ni->security_id = info->SecurityId;
2485 	ni->special_streams = special_streams;
2486 
2487 	p = FIRST_DENTRY(ni);
2488 
2489 	if (!NTFS_IS_ROOT_FILE(file->FileReferenceNumber))
2490 		p = load_name_information(file, ni, p);
2491 
2492 	if (file_has_streams(file))
2493 		p = load_stream_information(file, ni, p);
2494 
2495 	wimlib_assert((u8 *)p - (u8 *)ni == inode_size);
2496 
2497 	ntfs_inode_map_add_inode(inode_map, ni);
2498 	return 0;
2499 }
2500 
2501 /*
2502  * Quickly find all files on an NTFS volume by using FSCTL_QUERY_FILE_LAYOUT to
2503  * scan the MFT.  The NTFS volume is specified by the NT namespace path @path.
2504  * For each file, allocate an 'ntfs_inode' structure for each file and add it to
2505  * 'inode_map' keyed by inode number.  Include NTFS special files such as
2506  * $Bitmap (they will be removed later).
2507  */
2508 static int
load_files_from_mft(const wchar_t * path,struct ntfs_inode_map * inode_map)2509 load_files_from_mft(const wchar_t *path, struct ntfs_inode_map *inode_map)
2510 {
2511 	HANDLE h = NULL;
2512 	QUERY_FILE_LAYOUT_INPUT in = (QUERY_FILE_LAYOUT_INPUT) {
2513 		.NumberOfPairs = 0,
2514 		.Flags = QUERY_FILE_LAYOUT_RESTART |
2515 			 QUERY_FILE_LAYOUT_INCLUDE_NAMES |
2516 			 QUERY_FILE_LAYOUT_INCLUDE_STREAMS |
2517 			 QUERY_FILE_LAYOUT_INCLUDE_EXTENTS |
2518 			 QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO |
2519 			 QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED,
2520 		.FilterType = QUERY_FILE_LAYOUT_FILTER_TYPE_NONE,
2521 	};
2522 	size_t outsize = 32768;
2523 	QUERY_FILE_LAYOUT_OUTPUT *out = NULL;
2524 	int ret;
2525 	NTSTATUS status;
2526 
2527 	status = winnt_open(path, wcslen(path),
2528 			    FILE_READ_DATA | FILE_READ_ATTRIBUTES, &h);
2529 	if (!NT_SUCCESS(status)) {
2530 		ret = -1; /* Silently try standard recursive scan instead  */
2531 		goto out;
2532 	}
2533 
2534 	for (;;) {
2535 		/* Allocate a buffer for the output of the ioctl.  */
2536 		out = MALLOC(outsize);
2537 		if (!out) {
2538 			ret = WIMLIB_ERR_NOMEM;
2539 			goto out;
2540 		}
2541 
2542 		/* Execute FSCTL_QUERY_FILE_LAYOUT until it fails.  */
2543 		while (NT_SUCCESS(status = winnt_fsctl(h,
2544 						       FSCTL_QUERY_FILE_LAYOUT,
2545 						       &in, sizeof(in),
2546 						       out, outsize, NULL)))
2547 		{
2548 			const FILE_LAYOUT_ENTRY *file =
2549 				(const void *)out + out->FirstFileOffset;
2550 			for (;;) {
2551 				ret = load_one_file(file, inode_map);
2552 				if (ret)
2553 					goto out;
2554 				if (file->NextFileOffset == 0)
2555 					break;
2556 				file = (const void *)file + file->NextFileOffset;
2557 			}
2558 			in.Flags &= ~QUERY_FILE_LAYOUT_RESTART;
2559 		}
2560 
2561 		/* Enlarge the buffer if needed.  */
2562 		if (status != STATUS_BUFFER_TOO_SMALL)
2563 			break;
2564 		FREE(out);
2565 		outsize *= 2;
2566 	}
2567 
2568 	/* Normally, FSCTL_QUERY_FILE_LAYOUT fails with STATUS_END_OF_FILE after
2569 	 * all files have been enumerated.  */
2570 	if (status != STATUS_END_OF_FILE) {
2571 		if (status == STATUS_INVALID_DEVICE_REQUEST /* old OS */ ||
2572 		    status == STATUS_NOT_SUPPORTED /* Samba volume, WinXP */ ||
2573 		    status == STATUS_INVALID_PARAMETER /* not root directory */ )
2574 		{
2575 			/* Silently try standard recursive scan instead  */
2576 			ret = -1;
2577 		} else {
2578 			winnt_error(status,
2579 				    L"Error enumerating files on volume \"%ls\"",
2580 				    path);
2581 			/* Try standard recursive scan instead  */
2582 			ret = WIMLIB_ERR_UNSUPPORTED;
2583 		}
2584 		goto out;
2585 	}
2586 	ret = 0;
2587 out:
2588 	FREE(out);
2589 	NtClose(h);
2590 	return ret;
2591 }
2592 
2593 /* Build the list of child dentries for each inode in @map.  This is done by
2594  * iterating through each name of each inode and adding it to its parent's
2595  * children list.  Note that every name should have a parent, i.e. should belong
2596  * to some directory.  The root directory does not have any names.  */
2597 static int
build_children_lists(struct ntfs_inode_map * map,struct ntfs_inode ** root_ret)2598 build_children_lists(struct ntfs_inode_map *map, struct ntfs_inode **root_ret)
2599 {
2600 	struct ntfs_inode *ni;
2601 
2602 	avl_tree_for_each_in_order(ni, map->root, struct ntfs_inode, index_node)
2603 	{
2604 		struct ntfs_dentry *nd;
2605 		u32 n;
2606 
2607 		if (NTFS_IS_ROOT_FILE(ni->ino)) {
2608 			*root_ret = ni;
2609 			continue;
2610 		}
2611 
2612 		n = ni->num_aliases;
2613 		nd = FIRST_DENTRY(ni);
2614 		for (;;) {
2615 			struct ntfs_inode *parent;
2616 
2617 			parent = ntfs_inode_map_lookup(map, nd->parent_ino);
2618 			if (unlikely(!parent)) {
2619 				ERROR("Parent inode 0x%016"PRIx64" of"
2620 				      "directory entry \"%ls\" (inode "
2621 				      "0x%016"PRIx64") was missing from the "
2622 				      "MFT listing!",
2623 				      nd->parent_ino, nd->name, ni->ino);
2624 				return WIMLIB_ERR_UNSUPPORTED;
2625 			}
2626 			nd->next_child = parent->first_child;
2627 			parent->first_child = nd;
2628 			if (!--n)
2629 				break;
2630 			nd = NEXT_DENTRY(nd);
2631 		}
2632 	}
2633 	return 0;
2634 }
2635 
2636 struct security_map_node {
2637 	struct avl_tree_node index_node;
2638 	u32 disk_security_id;
2639 	u32 wim_security_id;
2640 };
2641 
2642 /* Map from disk security IDs to WIM security IDs  */
2643 struct security_map {
2644 	struct avl_tree_node *root;
2645 };
2646 
2647 #define SECURITY_MAP_NODE(node)				\
2648 	avl_tree_entry((node), struct security_map_node, index_node)
2649 
2650 static int
_avl_cmp_security_map_nodes(const struct avl_tree_node * node1,const struct avl_tree_node * node2)2651 _avl_cmp_security_map_nodes(const struct avl_tree_node *node1,
2652 			    const struct avl_tree_node *node2)
2653 {
2654 	return cmp_u32(SECURITY_MAP_NODE(node1)->disk_security_id,
2655 		       SECURITY_MAP_NODE(node2)->disk_security_id);
2656 }
2657 
2658 static s32
security_map_lookup(struct security_map * map,u32 disk_security_id)2659 security_map_lookup(struct security_map *map, u32 disk_security_id)
2660 {
2661 	struct security_map_node tmp;
2662 	const struct avl_tree_node *res;
2663 
2664 	if (disk_security_id == 0)  /* No on-disk security ID; uncacheable  */
2665 		return -1;
2666 
2667 	tmp.disk_security_id = disk_security_id;
2668 	res = avl_tree_lookup_node(map->root, &tmp.index_node,
2669 				   _avl_cmp_security_map_nodes);
2670 	if (!res)
2671 		return -1;
2672 	return SECURITY_MAP_NODE(res)->wim_security_id;
2673 }
2674 
2675 static int
security_map_insert(struct security_map * map,u32 disk_security_id,u32 wim_security_id)2676 security_map_insert(struct security_map *map, u32 disk_security_id,
2677 		    u32 wim_security_id)
2678 {
2679 	struct security_map_node *node;
2680 
2681 	if (disk_security_id == 0)  /* No on-disk security ID; uncacheable  */
2682 		return 0;
2683 
2684 	node = MALLOC(sizeof(*node));
2685 	if (!node)
2686 		return WIMLIB_ERR_NOMEM;
2687 
2688 	node->disk_security_id = disk_security_id;
2689 	node->wim_security_id = wim_security_id;
2690 	avl_tree_insert(&map->root, &node->index_node,
2691 			_avl_cmp_security_map_nodes);
2692 	return 0;
2693 }
2694 
2695 static void
security_map_destroy(struct security_map * map)2696 security_map_destroy(struct security_map *map)
2697 {
2698 	struct security_map_node *node;
2699 
2700 	avl_tree_for_each_in_postorder(node, map->root,
2701 				       struct security_map_node, index_node)
2702 		FREE(node);
2703 }
2704 
2705 /*
2706  * Turn our temporary NTFS structures into the final WIM structures:
2707  *
2708  *	ntfs_inode	=> wim_inode
2709  *	ntfs_dentry	=> wim_dentry
2710  *	ntfs_stream	=> wim_inode_stream
2711  *
2712  * This also handles things such as exclusions and issuing progress messages.
2713  * It's similar to winnt_build_dentry_tree_recursive(), but this is much faster
2714  * because almost all information we need is already loaded in memory in the
2715  * ntfs_* structures.  However, in some cases we still fall back to
2716  * winnt_build_dentry_tree_recursive() and/or opening the file.
2717  */
2718 static int
generate_wim_structures_recursive(struct wim_dentry ** root_ret,const wchar_t * filename,bool is_primary_name,struct ntfs_inode * ni,struct winnt_scan_ctx * ctx,struct ntfs_inode_map * inode_map,struct security_map * security_map)2719 generate_wim_structures_recursive(struct wim_dentry **root_ret,
2720 				  const wchar_t *filename, bool is_primary_name,
2721 				  struct ntfs_inode *ni,
2722 				  struct winnt_scan_ctx *ctx,
2723 				  struct ntfs_inode_map *inode_map,
2724 				  struct security_map *security_map)
2725 {
2726 	int ret = 0;
2727 	struct wim_dentry *root = NULL;
2728 	struct wim_inode *inode = NULL;
2729 	const struct ntfs_stream *ns;
2730 
2731 	/* Completely ignore NTFS special files.  */
2732 	if (NTFS_IS_SPECIAL_FILE(ni->ino))
2733 		goto out;
2734 
2735 	/* Fall back to a recursive scan for unhandled cases.  Reparse points,
2736 	 * in particular, can't be properly handled here because a commonly used
2737 	 * filter driver (WOF) hides reparse points from regular filesystem APIs
2738 	 * but not from FSCTL_QUERY_FILE_LAYOUT.  */
2739 	if (ni->attributes & (FILE_ATTRIBUTE_REPARSE_POINT |
2740 			      FILE_ATTRIBUTE_ENCRYPTED) ||
2741 	    ni->special_streams != 0)
2742 	{
2743 		ret = winnt_build_dentry_tree_recursive(&root,
2744 							NULL,
2745 							ctx->params->cur_path,
2746 							ctx->params->cur_path_nchars,
2747 							filename,
2748 							ctx);
2749 		goto out;
2750 	}
2751 
2752 	/* Test for exclusion based on path.  */
2753 	ret = try_exclude(ctx->params);
2754 	if (unlikely(ret < 0)) /* Excluded? */
2755 		goto out_progress;
2756 	if (unlikely(ret > 0)) /* Error? */
2757 		goto out;
2758 
2759 	/* Create the WIM dentry and possibly a new WIM inode  */
2760 	ret = inode_table_new_dentry(ctx->params->inode_table, filename,
2761 				     ni->ino, ctx->params->capture_root_dev,
2762 				     false, &root);
2763 	if (ret)
2764 		goto out;
2765 
2766 	inode = root->d_inode;
2767 
2768 	/* Set the short name if needed.  */
2769 	if (is_primary_name && *ni->short_name) {
2770 		size_t nbytes = wcslen(ni->short_name) * sizeof(wchar_t);
2771 		root->d_short_name = memdup(ni->short_name,
2772 					    nbytes + sizeof(wchar_t));
2773 		if (!root->d_short_name) {
2774 			ret = WIMLIB_ERR_NOMEM;
2775 			goto out;
2776 		}
2777 		root->d_short_name_nbytes = nbytes;
2778 	}
2779 
2780 	if (inode->i_nlink > 1) { /* Already seen this inode?  */
2781 		ret = 0;
2782 		goto out_progress;
2783 	}
2784 
2785 	/* The file attributes and timestamps were cached from the MFT.  */
2786 	inode->i_attributes = ni->attributes;
2787 	inode->i_creation_time = ni->creation_time;
2788 	inode->i_last_write_time = ni->last_write_time;
2789 	inode->i_last_access_time = ni->last_access_time;
2790 
2791 	/* Set the security descriptor if needed.  */
2792 	if (!(ctx->params->add_flags & WIMLIB_ADD_FLAG_NO_ACLS)) {
2793 		/* Look up the WIM security ID that corresponds to the on-disk
2794 		 * security ID.  */
2795 		s32 wim_security_id =
2796 			security_map_lookup(security_map, ni->security_id);
2797 		if (likely(wim_security_id >= 0)) {
2798 			/* The mapping for this security ID is already cached.*/
2799 			inode->i_security_id = wim_security_id;
2800 		} else {
2801 			HANDLE h;
2802 			NTSTATUS status;
2803 
2804 			/* Create a mapping for this security ID and insert it
2805 			 * into the security map.  */
2806 
2807 			status = winnt_open(ctx->params->cur_path,
2808 					    ctx->params->cur_path_nchars,
2809 					    READ_CONTROL |
2810 						ACCESS_SYSTEM_SECURITY, &h);
2811 			if (!NT_SUCCESS(status)) {
2812 				winnt_error(status, L"Can't open \"%ls\" to "
2813 					    "read security descriptor",
2814 					    printable_path(ctx));
2815 				ret = WIMLIB_ERR_OPEN;
2816 				goto out;
2817 			}
2818 			ret = winnt_load_security_descriptor(h, inode, ctx);
2819 			NtClose(h);
2820 			if (ret)
2821 				goto out;
2822 
2823 			ret = security_map_insert(security_map, ni->security_id,
2824 						  inode->i_security_id);
2825 			if (ret)
2826 				goto out;
2827 		}
2828 	}
2829 
2830 	/* Add data streams based on the cached information from the MFT.  */
2831 	ns = FIRST_STREAM(ni);
2832 	for (u32 i = 0; i < ni->num_streams; i++) {
2833 		struct windows_file *windows_file;
2834 
2835 		/* Reference the stream by path if it's a named data stream, or
2836 		 * if the volume doesn't support "open by file ID", or if the
2837 		 * application hasn't explicitly opted in to "open by file ID".
2838 		 * Otherwise, only save the inode number (file ID).  */
2839 		if (*ns->name ||
2840 		    !(ctx->vol_flags & FILE_SUPPORTS_OPEN_BY_FILE_ID) ||
2841 		    !(ctx->params->add_flags & WIMLIB_ADD_FLAG_FILE_PATHS_UNNEEDED))
2842 		{
2843 			windows_file = alloc_windows_file(ctx->params->cur_path,
2844 							  ctx->params->cur_path_nchars,
2845 							  ns->name,
2846 							  wcslen(ns->name),
2847 							  ctx->snapshot,
2848 							  false);
2849 		} else {
2850 			windows_file = alloc_windows_file_for_file_id(ni->ino,
2851 								      ctx->params->cur_path,
2852 								      ctx->params->root_path_nchars,
2853 								      ctx->snapshot);
2854 		}
2855 
2856 		ret = add_stream(inode, windows_file, ns->size,
2857 				 STREAM_TYPE_DATA, ns->name,
2858 				 ctx->params->unhashed_blobs);
2859 		if (ret)
2860 			goto out;
2861 		ns = NEXT_STREAM(ns);
2862 	}
2863 
2864 	set_sort_key(inode, ni->starting_lcn);
2865 
2866 	/* If processing a directory, then recurse to its children.  In this
2867 	 * version there is no need to go to disk, as we already have the list
2868 	 * of children cached from the MFT.  */
2869 	if (inode_is_directory(inode)) {
2870 		const struct ntfs_dentry *nd = ni->first_child;
2871 
2872 		while (nd != NULL) {
2873 			size_t orig_path_nchars;
2874 			struct wim_dentry *child;
2875 			const struct ntfs_dentry *next = nd->next_child;
2876 
2877 			ret = WIMLIB_ERR_NOMEM;
2878 			if (!pathbuf_append_name(ctx->params, nd->name,
2879 						 wcslen(nd->name),
2880 						 &orig_path_nchars))
2881 				goto out;
2882 
2883 			ret = generate_wim_structures_recursive(
2884 					&child,
2885 					nd->name,
2886 					nd->is_primary,
2887 					(void *)nd - nd->offset_from_inode,
2888 					ctx,
2889 					inode_map,
2890 					security_map);
2891 
2892 			pathbuf_truncate(ctx->params, orig_path_nchars);
2893 
2894 			if (ret)
2895 				goto out;
2896 
2897 			attach_scanned_tree(root, child, ctx->params->blob_table);
2898 			nd = next;
2899 		}
2900 	}
2901 
2902 out_progress:
2903 	if (likely(root))
2904 		ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_OK, inode);
2905 	else
2906 		ret = do_scan_progress(ctx->params, WIMLIB_SCAN_DENTRY_EXCLUDED, NULL);
2907 out:
2908 	if (--ni->num_aliases == 0) {
2909 		/* Memory usage optimization: when we don't need the ntfs_inode
2910 		 * (and its names and streams) anymore, free it.  */
2911 		ntfs_inode_map_remove(inode_map, ni);
2912 	}
2913 	if (unlikely(ret)) {
2914 		free_dentry_tree(root, ctx->params->blob_table);
2915 		root = NULL;
2916 	}
2917 	*root_ret = root;
2918 	return ret;
2919 }
2920 
2921 static int
winnt_build_dentry_tree_fast(struct wim_dentry ** root_ret,struct winnt_scan_ctx * ctx)2922 winnt_build_dentry_tree_fast(struct wim_dentry **root_ret,
2923 			     struct winnt_scan_ctx *ctx)
2924 {
2925 	struct ntfs_inode_map inode_map = { .root = NULL };
2926 	struct security_map security_map = { .root = NULL };
2927 	struct ntfs_inode *root = NULL;
2928 	wchar_t *path = ctx->params->cur_path;
2929 	size_t path_nchars = ctx->params->cur_path_nchars;
2930 	bool adjust_path;
2931 	int ret;
2932 
2933 	adjust_path = (path[path_nchars - 1] == L'\\');
2934 	if (adjust_path)
2935 		path[path_nchars - 1] = L'\0';
2936 
2937 	ret = load_files_from_mft(path, &inode_map);
2938 
2939 	if (adjust_path)
2940 		path[path_nchars - 1] = L'\\';
2941 
2942 	if (ret)
2943 		goto out;
2944 
2945 	ret = build_children_lists(&inode_map, &root);
2946 	if (ret)
2947 		goto out;
2948 
2949 	if (!root) {
2950 		ERROR("The MFT listing for volume \"%ls\" did not include a "
2951 		      "root directory!", path);
2952 		ret = WIMLIB_ERR_UNSUPPORTED;
2953 		goto out;
2954 	}
2955 
2956 	root->num_aliases = 1;
2957 
2958 	ret = generate_wim_structures_recursive(root_ret, L"", false, root, ctx,
2959 						&inode_map, &security_map);
2960 out:
2961 	ntfs_inode_map_destroy(&inode_map);
2962 	security_map_destroy(&security_map);
2963 	return ret;
2964 }
2965 
2966 #endif /* ENABLE_FAST_MFT_SCAN */
2967 
2968 /*----------------------------------------------------------------------------*
2969  *                 Entry point for directory tree scans on Windows            *
2970  *----------------------------------------------------------------------------*/
2971 
2972 int
win32_build_dentry_tree(struct wim_dentry ** root_ret,const wchar_t * root_disk_path,struct scan_params * params)2973 win32_build_dentry_tree(struct wim_dentry **root_ret,
2974 			const wchar_t *root_disk_path,
2975 			struct scan_params *params)
2976 {
2977 	struct winnt_scan_ctx ctx = { .params = params };
2978 	UNICODE_STRING ntpath;
2979 	HANDLE h = NULL;
2980 	NTSTATUS status;
2981 	int ret;
2982 
2983 	if (params->add_flags & WIMLIB_ADD_FLAG_SNAPSHOT)
2984 		ret = vss_create_snapshot(root_disk_path, &ntpath, &ctx.snapshot);
2985 	else
2986 		ret = win32_path_to_nt_path(root_disk_path, &ntpath);
2987 
2988 	if (ret)
2989 		goto out;
2990 
2991 	if (ntpath.Length < 4 * sizeof(wchar_t) ||
2992 	    wmemcmp(ntpath.Buffer, L"\\??\\", 4))
2993 	{
2994 		ERROR("\"%ls\": unrecognized path format", root_disk_path);
2995 		ret = WIMLIB_ERR_INVALID_PARAM;
2996 	} else {
2997 		ret = pathbuf_init(params, ntpath.Buffer);
2998 	}
2999 	HeapFree(GetProcessHeap(), 0, ntpath.Buffer);
3000 	if (ret)
3001 		goto out;
3002 
3003 	status = winnt_open(params->cur_path, params->cur_path_nchars,
3004 			    FILE_READ_ATTRIBUTES, &h);
3005 	if (!NT_SUCCESS(status)) {
3006 		winnt_error(status, L"Can't open \"%ls\"", root_disk_path);
3007 		if (status == STATUS_FVE_LOCKED_VOLUME)
3008 			ret = WIMLIB_ERR_FVE_LOCKED_VOLUME;
3009 		else
3010 			ret = WIMLIB_ERR_OPEN;
3011 		goto out;
3012 	}
3013 
3014 	get_volume_information(h, &ctx);
3015 
3016 	NtClose(h);
3017 
3018 #ifdef ENABLE_FAST_MFT_SCAN
3019 	if (ctx.is_ntfs && !_wgetenv(L"WIMLIB_DISABLE_QUERY_FILE_LAYOUT")) {
3020 		ret = winnt_build_dentry_tree_fast(root_ret, &ctx);
3021 		if (ret >= 0 && ret != WIMLIB_ERR_UNSUPPORTED)
3022 			goto out;
3023 		if (ret >= 0) {
3024 			WARNING("A problem occurred during the fast MFT scan.\n"
3025 				"          Falling back to the standard "
3026 				"recursive directory tree scan.");
3027 		}
3028 	}
3029 #endif
3030 	ret = winnt_build_dentry_tree_recursive(root_ret, NULL,
3031 						params->cur_path,
3032 						params->cur_path_nchars,
3033 						L"", &ctx);
3034 out:
3035 	vss_put_snapshot(ctx.snapshot);
3036 	if (ret == 0)
3037 		winnt_do_scan_warnings(root_disk_path, &ctx);
3038 	return ret;
3039 }
3040 
3041 #endif /* __WIN32__ */
3042