4 * Capture a WIM image from a NTFS volume. We capture everything we can,
5 * including security data and alternate data streams.
9 * Copyright (C) 2012 Eric Biggers
11 * This file is part of wimlib, a library for working with WIM files.
13 * wimlib is free software; you can redistribute it and/or modify it under the
14 * terms of the GNU General Public License as published by the Free
15 * Software Foundation; either version 3 of the License, or (at your option)
18 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 * A PARTICULAR PURPOSE. See the GNU General Public License for more
23 * You should have received a copy of the GNU General Public License
24 * along with wimlib; if not, see http://www.gnu.org/licenses/.
30 #include <ntfs-3g/endians.h>
31 #include <ntfs-3g/types.h>
33 #include "wimlib_internal.h"
37 #include "lookup_table.h"
38 #include "buffer_io.h"
39 #include <ntfs-3g/layout.h>
40 #include <ntfs-3g/acls.h>
41 #include <ntfs-3g/attrib.h>
42 #include <ntfs-3g/misc.h>
43 #include <ntfs-3g/reparse.h>
44 #include <ntfs-3g/security.h> /* security.h before xattrs.h */
45 #include <ntfs-3g/xattrs.h>
46 #include <ntfs-3g/volume.h>
52 /* Structure that allows searching the security descriptors by SHA1 message
55 struct wim_security_data *sd;
56 struct rb_root rb_root;
59 /* Binary tree node of security descriptors, indexed by the @hash field. */
62 u8 hash[SHA1_HASH_SIZE];
63 struct rb_node rb_node;
66 static void free_sd_tree(struct rb_node *node)
69 free_sd_tree(node->rb_left);
70 free_sd_tree(node->rb_right);
71 FREE(container_of(node, struct sd_node, rb_node));
74 /* Frees a security descriptor index set. */
75 static void destroy_sd_set(struct sd_set *sd_set)
77 free_sd_tree(sd_set->rb_root.rb_node);
80 /* Inserts a a new node into the security descriptor index tree. */
81 static void insert_sd_node(struct sd_set *set, struct sd_node *new)
83 struct rb_root *root = &set->rb_root;
84 struct rb_node **p = &(root->rb_node);
85 struct rb_node *rb_parent = NULL;
88 struct sd_node *this = container_of(*p, struct sd_node, rb_node);
89 int cmp = hashes_cmp(new->hash, this->hash);
95 p = &((*p)->rb_right);
97 wimlib_assert(0); /* Duplicate SHA1 message digest */
99 rb_link_node(&new->rb_node, rb_parent, p);
100 rb_insert_color(&new->rb_node, root);
103 /* Returns the index of the security descriptor having a SHA1 message digest of
104 * @hash. If not found, return -1. */
105 static int lookup_sd(struct sd_set *set, const u8 hash[SHA1_HASH_SIZE])
107 struct rb_node *node = set->rb_root.rb_node;
110 struct sd_node *sd_node = container_of(node, struct sd_node, rb_node);
111 int cmp = hashes_cmp(hash, sd_node->hash);
113 node = node->rb_left;
115 node = node->rb_right;
117 return sd_node->security_id;
123 * Adds a security descriptor to the indexed security descriptor set as well as
124 * the corresponding `struct wim_security_data', and returns the new security
125 * ID; or, if there is an existing security descriptor that is the same, return
126 * the security ID for it. If a new security descriptor cannot be allocated,
129 static int sd_set_add_sd(struct sd_set *sd_set, const char descriptor[],
132 u8 hash[SHA1_HASH_SIZE];
138 struct wim_security_data *sd;
140 sha1_buffer((const u8*)descriptor, size, hash);
142 security_id = lookup_sd(sd_set, hash);
143 if (security_id >= 0) /* Identical descriptor already exists */
146 /* Need to add a new security descriptor */
147 new = MALLOC(sizeof(*new));
150 descr_copy = MALLOC(size);
156 memcpy(descr_copy, descriptor, size);
157 new->security_id = sd->num_entries;
158 copy_hash(new->hash, hash);
160 descriptors = REALLOC(sd->descriptors,
161 (sd->num_entries + 1) * sizeof(sd->descriptors[0]));
164 sd->descriptors = descriptors;
165 sizes = REALLOC(sd->sizes,
166 (sd->num_entries + 1) * sizeof(sd->sizes[0]));
170 sd->descriptors[sd->num_entries] = descr_copy;
171 sd->sizes[sd->num_entries] = size;
173 DEBUG("There are now %d security descriptors", sd->num_entries);
174 sd->total_length += size + sizeof(sd->sizes[0]);
175 insert_sd_node(sd_set, new);
176 return new->security_id;
185 static inline ntfschar *attr_record_name(ATTR_RECORD *ar)
187 return (ntfschar*)((u8*)ar + le16_to_cpu(ar->name_offset));
190 /* Calculates the SHA1 message digest of a NTFS attribute.
192 * @ni: The NTFS inode containing the attribute.
193 * @ar: The ATTR_RECORD describing the attribute.
194 * @md: If successful, the returned SHA1 message digest.
195 * @reparse_tag_ret: Optional pointer into which the first 4 bytes of the
196 * attribute will be written (to get the reparse
199 * Return 0 on success or nonzero on error.
201 static int ntfs_attr_sha1sum(ntfs_inode *ni, ATTR_RECORD *ar,
202 u8 md[SHA1_HASH_SIZE],
203 bool is_reparse_point,
204 u32 *reparse_tag_ret)
208 char buf[BUFFER_SIZE];
212 na = ntfs_attr_open(ni, ar->type, attr_record_name(ar),
215 ERROR_WITH_ERRNO("Failed to open NTFS attribute");
216 return WIMLIB_ERR_NTFS_3G;
219 bytes_remaining = na->data_size;
221 if (is_reparse_point) {
222 if (ntfs_attr_pread(na, 0, 8, buf) != 8)
224 *reparse_tag_ret = le32_to_cpu(*(u32*)buf);
226 bytes_remaining -= 8;
230 while (bytes_remaining) {
231 s64 to_read = min(bytes_remaining, sizeof(buf));
232 if (ntfs_attr_pread(na, pos, to_read, buf) != to_read)
234 sha1_update(&ctx, buf, to_read);
236 bytes_remaining -= to_read;
238 sha1_final(md, &ctx);
242 ERROR_WITH_ERRNO("Error reading NTFS attribute");
243 return WIMLIB_ERR_NTFS_3G;
246 /* Load the streams from a file or reparse point in the NTFS volume into the WIM
248 static int capture_ntfs_streams(struct wim_dentry *dentry, ntfs_inode *ni,
249 char path[], size_t path_len,
250 struct wim_lookup_table *lookup_table,
251 ntfs_volume **ntfs_vol_p,
254 ntfs_attr_search_ctx *actx;
255 u8 attr_hash[SHA1_HASH_SIZE];
256 struct ntfs_location *ntfs_loc = NULL;
258 struct wim_lookup_table_entry *lte;
260 DEBUG2("Capturing NTFS data streams from `%s'", path);
262 /* Get context to search the streams of the NTFS file. */
263 actx = ntfs_attr_get_search_ctx(ni, NULL);
265 ERROR_WITH_ERRNO("Cannot get NTFS attribute search "
267 return WIMLIB_ERR_NTFS_3G;
270 /* Capture each data stream or reparse data stream. */
271 while (!ntfs_attr_lookup(type, NULL, 0,
272 CASE_SENSITIVE, 0, NULL, 0, actx))
274 char *stream_name_utf8;
276 u64 data_size = ntfs_get_attribute_value_length(actx->attr);
277 u64 name_length = actx->attr->name_length;
279 if (data_size == 0) {
281 ERROR_WITH_ERRNO("Failed to get size of attribute of "
283 ret = WIMLIB_ERR_NTFS_3G;
286 /* Empty stream. No lookup table entry is needed. */
289 if (type == AT_REPARSE_POINT && data_size < 8) {
290 ERROR("`%s': reparse point buffer too small",
292 ret = WIMLIB_ERR_NTFS_3G;
295 /* Checksum the stream. */
296 ret = ntfs_attr_sha1sum(ni, actx->attr, attr_hash,
297 type == AT_REPARSE_POINT, &reparse_tag);
301 /* Make a lookup table entry for the stream, or use an existing
302 * one if there's already an identical stream. */
303 lte = __lookup_resource(lookup_table, attr_hash);
304 ret = WIMLIB_ERR_NOMEM;
308 ntfs_loc = CALLOC(1, sizeof(*ntfs_loc));
311 ntfs_loc->ntfs_vol_p = ntfs_vol_p;
312 ntfs_loc->path_utf8 = MALLOC(path_len + 1);
313 if (!ntfs_loc->path_utf8)
314 goto out_free_ntfs_loc;
315 memcpy(ntfs_loc->path_utf8, path, path_len + 1);
317 ntfs_loc->stream_name_utf16 = MALLOC(name_length * 2);
318 if (!ntfs_loc->stream_name_utf16)
319 goto out_free_ntfs_loc;
320 memcpy(ntfs_loc->stream_name_utf16,
321 attr_record_name(actx->attr),
322 actx->attr->name_length * 2);
323 ntfs_loc->stream_name_utf16_num_chars = name_length;
326 lte = new_lookup_table_entry();
328 goto out_free_ntfs_loc;
329 lte->ntfs_loc = ntfs_loc;
330 lte->resource_location = RESOURCE_IN_NTFS_VOLUME;
331 if (type == AT_REPARSE_POINT) {
332 dentry->d_inode->i_reparse_tag = reparse_tag;
333 ntfs_loc->is_reparse_point = true;
334 lte->resource_entry.original_size = data_size - 8;
335 lte->resource_entry.size = data_size - 8;
337 ntfs_loc->is_reparse_point = false;
338 lte->resource_entry.original_size = data_size;
339 lte->resource_entry.size = data_size;
342 DEBUG("Add resource for `%s' (size = %"PRIu64")",
343 dentry->file_name_utf8,
344 lte->resource_entry.original_size);
345 copy_hash(lte->hash, attr_hash);
346 lookup_table_insert(lookup_table, lte);
349 if (name_length == 0) {
350 /* Unnamed data stream. Put the reference to it in the
352 if (dentry->d_inode->i_lte) {
353 ERROR("Found two un-named data streams for "
355 ret = WIMLIB_ERR_NTFS_3G;
358 dentry->d_inode->i_lte = lte;
360 /* Named data stream. Put the reference to it in the
361 * alternate data stream entries */
362 struct wim_ads_entry *new_ads_entry;
363 size_t stream_name_utf8_len;
365 ret = utf16_to_utf8((const char*)attr_record_name(actx->attr),
368 &stream_name_utf8_len);
371 new_ads_entry = inode_add_ads(dentry->d_inode, stream_name_utf8);
372 FREE(stream_name_utf8);
376 wimlib_assert(new_ads_entry->stream_name_len == name_length * 2);
378 new_ads_entry->lte = lte;
384 free_lookup_table_entry(lte);
387 FREE(ntfs_loc->path_utf8);
388 FREE(ntfs_loc->stream_name_utf16);
392 ntfs_attr_put_search_ctx(actx);
394 DEBUG2("Successfully captured NTFS streams from `%s'", path);
396 ERROR("Failed to capture NTFS streams from `%s", path);
400 /* Red-black tree that maps NTFS inode numbers to DOS names */
401 struct dos_name_map {
402 struct rb_root rb_root;
405 struct dos_name_node {
406 struct rb_node rb_node;
412 /* Inserts a new DOS name into the map */
413 static int insert_dos_name(struct dos_name_map *map,
414 const ntfschar *dos_name, int name_len,
417 struct dos_name_node *new_node;
419 struct rb_root *root;
420 struct rb_node *rb_parent;
422 DEBUG("DOS name_len = %d", name_len);
423 new_node = MALLOC(sizeof(struct dos_name_node));
427 /* DOS names are supposed to be 12 characters max (that's 24 bytes,
428 * assuming 2-byte ntfs characters) */
429 wimlib_assert(name_len * sizeof(ntfschar) <= sizeof(new_node->dos_name));
431 /* Initialize the DOS name, DOS name length, and NTFS inode number of
432 * the red-black tree node */
433 memcpy(new_node->dos_name, dos_name, name_len * sizeof(ntfschar));
434 new_node->name_len_bytes = name_len * sizeof(ntfschar);
435 new_node->ntfs_ino = ntfs_ino;
437 /* Insert the red-black tree node */
438 root = &map->rb_root;
442 struct dos_name_node *this;
444 this = container_of(*p, struct dos_name_node, rb_node);
446 if (new_node->ntfs_ino < this->ntfs_ino)
447 p = &((*p)->rb_left);
448 else if (new_node->ntfs_ino > this->ntfs_ino)
449 p = &((*p)->rb_right);
451 /* This should be impossible since a NTFS inode cannot
452 * have multiple DOS names, and we only should get each
453 * DOS name entry once from the ntfs_readdir() calls. */
454 ERROR("NTFS inode %"PRIu64" has multiple DOS names",
459 rb_link_node(&new_node->rb_node, rb_parent, p);
460 rb_insert_color(&new_node->rb_node, root);
461 DEBUG("Inserted DOS name for inode %"PRIu64, ntfs_ino);
465 /* Returns a structure that contains the DOS name and its length for a NTFS
466 * inode, or NULL if the inode has no DOS name. */
467 static struct dos_name_node *
468 lookup_dos_name(const struct dos_name_map *map, u64 ntfs_ino)
470 struct rb_node *node = map->rb_root.rb_node;
472 struct dos_name_node *this;
473 this = container_of(node, struct dos_name_node, rb_node);
474 if (ntfs_ino < this->ntfs_ino)
475 node = node->rb_left;
476 else if (ntfs_ino > this->ntfs_ino)
477 node = node->rb_right;
484 static int set_dentry_dos_name(struct wim_dentry *dentry, void *arg)
486 const struct dos_name_map *map = arg;
487 const struct dos_name_node *node;
489 if (dentry->is_win32_name) {
490 node = lookup_dos_name(map, dentry->d_inode->i_ino);
492 dentry->short_name = MALLOC(node->name_len_bytes + 2);
493 if (!dentry->short_name)
494 return WIMLIB_ERR_NOMEM;
495 memcpy(dentry->short_name, node->dos_name,
496 node->name_len_bytes);
497 *(u16*)&dentry->short_name[node->name_len_bytes] = 0;
498 dentry->short_name_len = node->name_len_bytes;
499 DEBUG("Assigned DOS name to ino %"PRIu64,
500 dentry->d_inode->i_ino);
502 DEBUG("ino %"PRIu64" has Win32 name with no "
503 "corresponding DOS name",
504 dentry->d_inode->i_ino);
510 static void free_dos_name_tree(struct rb_node *node) {
512 free_dos_name_tree(node->rb_left);
513 free_dos_name_tree(node->rb_right);
514 FREE(container_of(node, struct dos_name_node, rb_node));
518 static void destroy_dos_name_map(struct dos_name_map *map)
520 free_dos_name_tree(map->rb_root.rb_node);
524 struct wim_dentry *parent;
528 struct wim_lookup_table *lookup_table;
529 struct sd_set *sd_set;
530 struct dos_name_map *dos_name_map;
531 const struct capture_config *config;
532 ntfs_volume **ntfs_vol_p;
534 wimlib_progress_func_t progress_func;
538 build_dentry_tree_ntfs_recursive(struct wim_dentry **root_p, ntfs_inode *dir_ni,
539 ntfs_inode *ni, char path[], size_t path_len,
541 struct wim_lookup_table *lookup_table,
542 struct sd_set *sd_set,
543 const struct capture_config *config,
544 ntfs_volume **ntfs_vol_p,
546 wimlib_progress_func_t progress_func);
548 static int wim_ntfs_capture_filldir(void *dirent, const ntfschar *name,
549 const int name_len, const int name_type,
550 const s64 pos, const MFT_REF mref,
551 const unsigned dt_type)
553 struct readdir_ctx *ctx;
554 size_t utf8_name_len;
556 struct wim_dentry *child;
561 if (name_type & FILE_NAME_DOS) {
562 /* Special case: If this is the entry for a DOS name, store it
564 ret = insert_dos_name(ctx->dos_name_map, name,
565 name_len, mref & MFT_REF_MASK_CPU);
568 if (name_type == FILE_NAME_DOS) /* DOS only, not Win32 + DOS */
571 ret = utf16_to_utf8((const char*)name, name_len * 2,
572 &utf8_name, &utf8_name_len);
576 if (utf8_name[0] == '.' &&
577 (utf8_name[1] == '\0' ||
578 (utf8_name[1] == '.' && utf8_name[2] == '\0'))) {
581 * note: name_type is POSIX for these, so DOS names will not
582 * have been inserted for them. */
584 goto out_free_utf8_name;
587 /* Open the inode for this directory entry and recursively capture the
588 * directory tree rooted at it */
589 ntfs_inode *ni = ntfs_inode_open(ctx->dir_ni->vol, mref);
591 ERROR_WITH_ERRNO("Failed to open NTFS inode");
592 goto out_free_utf8_name;
594 path_len = ctx->path_len;
596 ctx->path[path_len++] = '/';
597 memcpy(ctx->path + path_len, utf8_name, utf8_name_len + 1);
598 path_len += utf8_name_len;
600 ret = build_dentry_tree_ntfs_recursive(&child, ctx->dir_ni,
601 ni, ctx->path, path_len, name_type,
602 ctx->lookup_table, ctx->sd_set,
603 ctx->config, ctx->ntfs_vol_p,
604 ctx->add_image_flags,
607 dentry_add_child(ctx->parent, child);
608 ntfs_inode_close(ni);
614 /* Recursively build a WIM dentry tree corresponding to a NTFS volume.
615 * At the same time, update the WIM lookup table with lookup table entries for
616 * the NTFS streams, and build an array of security descriptors.
618 static int build_dentry_tree_ntfs_recursive(struct wim_dentry **root_p,
624 struct wim_lookup_table *lookup_table,
625 struct sd_set *sd_set,
626 const struct capture_config *config,
627 ntfs_volume **ntfs_vol_p,
629 wimlib_progress_func_t progress_func)
633 struct wim_dentry *root;
635 if (exclude_path(path, config, false)) {
636 /* Exclude a file or directory tree based on the capture
637 * configuration file */
638 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
641 union wimlib_progress_info info;
642 info.scan.cur_path = path;
643 info.scan.excluded = true;
644 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
650 /* Get file attributes */
651 struct SECURITY_CONTEXT ctx;
652 memset(&ctx, 0, sizeof(ctx));
654 ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ATTRIB,
655 ni, dir_ni, (char *)&attributes,
658 ERROR_WITH_ERRNO("Failed to get NTFS attributes from `%s'",
660 return WIMLIB_ERR_NTFS_3G;
663 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
666 union wimlib_progress_info info;
667 info.scan.cur_path = path;
668 info.scan.excluded = false;
669 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
672 /* Create the new WIM dentry */
673 root = new_dentry_with_timeless_inode(path_basename(path));
676 return WIMLIB_ERR_INVALID_UTF8_STRING;
677 else if (errno == ENOMEM)
678 return WIMLIB_ERR_NOMEM;
680 return WIMLIB_ERR_ICONV_NOT_AVAILABLE;
684 if (name_type & FILE_NAME_WIN32) /* Win32 or Win32+DOS name */
685 root->is_win32_name = 1;
686 root->d_inode->i_creation_time = le64_to_cpu(ni->creation_time);
687 root->d_inode->i_last_write_time = le64_to_cpu(ni->last_data_change_time);
688 root->d_inode->i_last_access_time = le64_to_cpu(ni->last_access_time);
689 root->d_inode->i_attributes = le32_to_cpu(attributes);
690 root->d_inode->i_ino = ni->mft_no;
691 root->d_inode->i_resolved = 1;
693 if (attributes & FILE_ATTR_REPARSE_POINT) {
694 /* Junction point, symbolic link, or other reparse point */
695 ret = capture_ntfs_streams(root, ni, path, path_len,
696 lookup_table, ntfs_vol_p,
698 } else if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY) {
700 /* Normal directory */
702 struct dos_name_map dos_name_map = { .rb_root = {.rb_node = NULL} };
703 struct readdir_ctx ctx = {
707 .path_len = path_len,
708 .lookup_table = lookup_table,
710 .dos_name_map = &dos_name_map,
712 .ntfs_vol_p = ntfs_vol_p,
713 .add_image_flags = add_image_flags,
714 .progress_func = progress_func,
716 ret = ntfs_readdir(ni, &pos, &ctx, wim_ntfs_capture_filldir);
718 ERROR_WITH_ERRNO("ntfs_readdir()");
719 ret = WIMLIB_ERR_NTFS_3G;
721 ret = for_dentry_child(root, set_dentry_dos_name,
724 destroy_dos_name_map(&dos_name_map);
727 ret = capture_ntfs_streams(root, ni, path, path_len,
728 lookup_table, ntfs_vol_p,
734 /* Get security descriptor */
738 ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ACL,
741 if (ret > sizeof(sd)) {
743 ret = ntfs_xattr_system_getxattr(&ctx, XATTR_NTFS_ACL,
744 ni, dir_ni, sd, ret);
747 root->d_inode->i_security_id = sd_set_add_sd(sd_set, sd, ret);
748 if (root->d_inode->i_security_id == -1) {
749 ERROR("Out of memory");
750 return WIMLIB_ERR_NOMEM;
752 DEBUG("Added security ID = %u for `%s'",
753 root->d_inode->i_security_id, path);
755 } else if (ret < 0) {
756 ERROR_WITH_ERRNO("Failed to get security information from "
758 ret = WIMLIB_ERR_NTFS_3G;
760 root->d_inode->i_security_id = -1;
761 DEBUG("No security ID for `%s'", path);
766 int build_dentry_tree_ntfs(struct wim_dentry **root_p,
768 struct wim_lookup_table *lookup_table,
769 struct wim_security_data *sd,
770 const struct capture_config *config,
772 wimlib_progress_func_t progress_func,
778 struct sd_set sd_set = {
782 ntfs_volume **ntfs_vol_p = extra_arg;
784 DEBUG("Mounting NTFS volume `%s' read-only", device);
786 #ifdef HAVE_NTFS_MNT_RDONLY
788 vol = ntfs_mount(device, NTFS_MNT_RDONLY);
790 /* NTFS-3g 2011, 2012 */
791 vol = ntfs_mount(device, MS_RDONLY);
794 ERROR_WITH_ERRNO("Failed to mount NTFS volume `%s' read-only",
796 return WIMLIB_ERR_NTFS_3G;
798 ntfs_open_secure(vol);
800 /* We don't want to capture the special NTFS files such as $Bitmap. Not
801 * to be confused with "hidden" or "system" files which are real files
802 * that we do need to capture. */
803 NVolClearShowSysFiles(vol);
805 DEBUG("Opening root NTFS dentry");
806 root_ni = ntfs_inode_open(vol, FILE_root);
808 ERROR_WITH_ERRNO("Failed to open root inode of NTFS volume "
810 ret = WIMLIB_ERR_NTFS_3G;
814 /* Currently we assume that all the UTF-8 paths fit into this length and
815 * there is no check for overflow. */
816 char *path = MALLOC(32768);
818 ERROR("Could not allocate memory for NTFS pathname");
819 ret = WIMLIB_ERR_NOMEM;
825 ret = build_dentry_tree_ntfs_recursive(root_p, NULL, root_ni, path, 1,
826 FILE_NAME_POSIX, lookup_table,
833 ntfs_inode_close(root_ni);
834 destroy_sd_set(&sd_set);
836 ntfs_index_ctx_put(vol->secure_xsii);
837 ntfs_index_ctx_put(vol->secure_xsdh);
838 ntfs_inode_close(vol->secure_ni);
841 if (ntfs_umount(vol, FALSE) != 0) {
842 ERROR_WITH_ERRNO("Failed to unmount NTFS volume `%s'",
845 ret = WIMLIB_ERR_NTFS_3G;
848 /* We need to leave the NTFS volume mounted so that we can read
849 * the NTFS files again when we are actually writing the WIM */