Welcome to mirror list, hosted at ThFree Co, Russian Federation.

attribute_list.rs « structured_values « src - github.com/windirstat/ntfs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 27b502f117af0bb2c06a1b0a8d185f9ee1500893 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright 2021 Colin Finck <colin@reactos.org>
// SPDX-License-Identifier: GPL-2.0-or-later

use crate::attribute::{NtfsAttribute, NtfsAttributeType};
use crate::error::{NtfsError, Result};
use crate::file::NtfsFile;
use crate::file_reference::NtfsFileReference;
use crate::ntfs::Ntfs;
use crate::string::NtfsString;
use crate::structured_values::NtfsStructuredValue;
use crate::traits::NtfsReadSeek;
use crate::types::Vcn;
use crate::value::non_resident_attribute::NtfsNonResidentAttributeValue;
use crate::value::NtfsValue;
use arrayvec::ArrayVec;
use binread::io::{Cursor, Read, Seek, SeekFrom};
use binread::{BinRead, BinReaderExt};
use core::mem;

/// Size of all [`AttributeListEntryHeader`] fields.
const ATTRIBUTE_LIST_ENTRY_HEADER_SIZE: usize = 26;

/// [`AttributeListEntryHeader::name_length`] is an `u8` length field specifying the number of UTF-16 code points.
/// Hence, the name occupies up to 510 bytes.
const NAME_MAX_SIZE: usize = (u8::MAX as usize) * mem::size_of::<u16>();

#[allow(unused)]
#[derive(BinRead, Clone, Debug)]
struct AttributeListEntryHeader {
    /// Type of the attribute, known types are in [`NtfsAttributeType`].
    ty: u32,
    /// Length of this attribute list entry, in bytes.
    list_entry_length: u16,
    /// Length of the name, in UTF-16 code points (every code point is 2 bytes).
    name_length: u8,
    /// Offset to the beginning of the name, in bytes from the beginning of this header.
    name_offset: u8,
    /// Lower boundary of Virtual Cluster Numbers (VCNs) referenced by this attribute.
    /// This becomes relevant when file data is split over multiple attributes.
    /// Otherwise, it's zero.
    lowest_vcn: Vcn,
    /// Reference to the [`NtfsFile`] record where this attribute is stored.
    base_file_reference: NtfsFileReference,
    /// Identifier of this attribute that is unique within the [`NtfsFile`].
    instance: u16,
}

#[derive(Clone, Debug)]
pub enum NtfsAttributeList<'n, 'f> {
    Resident(&'f [u8], u64),
    NonResident(NtfsNonResidentAttributeValue<'n, 'f>),
}

impl<'n, 'f> NtfsAttributeList<'n, 'f> {
    pub fn iter(&self) -> NtfsAttributeListEntries<'n, 'f> {
        NtfsAttributeListEntries::new(self.clone())
    }

    pub fn position(&self) -> u64 {
        match self {
            Self::Resident(_slice, position) => *position,
            Self::NonResident(value) => value.data_position().unwrap(),
        }
    }
}

impl<'n, 'f> NtfsStructuredValue<'n, 'f> for NtfsAttributeList<'n, 'f> {
    const TY: NtfsAttributeType = NtfsAttributeType::AttributeList;

    fn from_value<T>(_fs: &mut T, value: NtfsValue<'n, 'f>) -> Result<Self>
    where
        T: Read + Seek,
    {
        match value {
            NtfsValue::Slice(value) => {
                let slice = value.data();
                let position = value.data_position().unwrap();
                Ok(Self::Resident(slice, position))
            }
            NtfsValue::NonResidentAttribute(value) => Ok(Self::NonResident(value)),
            NtfsValue::AttributeListNonResidentAttribute(value) => {
                // Attribute Lists are never nested.
                // Hence, we must not create this attribute from an attribute that is already part of Attribute List.
                let position = value.data_position().unwrap();
                Err(NtfsError::UnexpectedAttributeListAttribute { position })
            }
        }
    }
}

#[derive(Clone, Debug)]
pub struct NtfsAttributeListEntries<'n, 'f> {
    attribute_list: NtfsAttributeList<'n, 'f>,
}

impl<'n, 'f> NtfsAttributeListEntries<'n, 'f> {
    fn new(attribute_list: NtfsAttributeList<'n, 'f>) -> Self {
        Self { attribute_list }
    }

    pub fn next<T>(&mut self, fs: &mut T) -> Option<Result<NtfsAttributeListEntry>>
    where
        T: Read + Seek,
    {
        match &mut self.attribute_list {
            NtfsAttributeList::Resident(slice, position) => Self::next_resident(slice, position),
            NtfsAttributeList::NonResident(value) => Self::next_non_resident(fs, value),
        }
    }

    pub fn next_non_resident<T>(
        fs: &mut T,
        value: &mut NtfsNonResidentAttributeValue<'n, 'f>,
    ) -> Option<Result<NtfsAttributeListEntry>>
    where
        T: Read + Seek,
    {
        if value.stream_position() >= value.len() {
            return None;
        }

        // Get the current entry.
        let mut value_attached = value.clone().attach(fs);
        let position = value.data_position().unwrap();
        let entry = iter_try!(NtfsAttributeListEntry::new(&mut value_attached, position));

        // Advance our iterator to the next entry.
        iter_try!(value.seek(fs, SeekFrom::Current(entry.list_entry_length() as i64)));

        Some(Ok(entry))
    }

    pub fn next_resident(
        slice: &mut &'f [u8],
        position: &mut u64,
    ) -> Option<Result<NtfsAttributeListEntry>> {
        if slice.is_empty() {
            return None;
        }

        // Get the current entry.
        let mut cursor = Cursor::new(*slice);
        let entry = iter_try!(NtfsAttributeListEntry::new(&mut cursor, *position));

        // Advance our iterator to the next entry.
        let bytes_to_advance = entry.list_entry_length() as usize;
        *slice = &slice[bytes_to_advance..];
        *position += bytes_to_advance as u64;

        Some(Ok(entry))
    }
}

#[derive(Clone, Debug)]
pub struct NtfsAttributeListEntry {
    header: AttributeListEntryHeader,
    name: ArrayVec<u8, NAME_MAX_SIZE>,
    position: u64,
}

impl NtfsAttributeListEntry {
    fn new<T>(r: &mut T, position: u64) -> Result<Self>
    where
        T: Read + Seek,
    {
        let header = r.read_le::<AttributeListEntryHeader>()?;

        let mut entry = Self {
            header,
            name: ArrayVec::from([0u8; NAME_MAX_SIZE]),
            position,
        };
        entry.validate_name_length()?;
        entry.read_name(r)?;

        Ok(entry)
    }

    pub fn base_file_reference(&self) -> NtfsFileReference {
        self.header.base_file_reference
    }

    pub fn instance(&self) -> u16 {
        self.header.instance
    }

    pub fn list_entry_length(&self) -> u16 {
        self.header.list_entry_length
    }

    pub fn lowest_vcn(&self) -> Vcn {
        self.header.lowest_vcn
    }

    /// Gets the attribute name and returns it wrapped in an [`NtfsString`].
    pub fn name<'s>(&'s self) -> NtfsString<'s> {
        NtfsString(&self.name)
    }

    /// Returns the file name length, in bytes.
    ///
    /// A file name has a maximum length of 255 UTF-16 code points (510 bytes).
    pub fn name_length(&self) -> usize {
        self.header.name_length as usize * mem::size_of::<u16>()
    }

    pub fn position(&self) -> u64 {
        self.position
    }

    fn read_name<T>(&mut self, r: &mut T) -> Result<()>
    where
        T: Read + Seek,
    {
        debug_assert_eq!(self.name.len(), NAME_MAX_SIZE);

        let name_length = self.name_length();
        r.read_exact(&mut self.name[..name_length])?;
        self.name.truncate(name_length);

        Ok(())
    }

    pub fn to_attribute<'n, 'f>(&self, file: &'f NtfsFile<'n>) -> Result<NtfsAttribute<'n, 'f>> {
        let file_record_number = self.base_file_reference().file_record_number();
        assert_eq!(
            file.file_record_number(),
            file_record_number,
            "The given NtfsFile's record number does not match the expected record number. \
            Always use NtfsAttributeListEntry::to_file to retrieve the correct NtfsFile."
        );

        let instance = self.instance();
        let ty = self.ty()?;

        file.attributes_raw()
            .find(|attribute| {
                attribute.instance() == instance
                    && attribute.ty().map(|attr_ty| attr_ty == ty).unwrap_or(false)
            })
            .ok_or(NtfsError::AttributeNotFound {
                position: file.position(),
                ty,
            })
    }

    pub fn to_file<'n, T>(&self, ntfs: &'n Ntfs, fs: &mut T) -> Result<NtfsFile<'n>>
    where
        T: Read + Seek,
    {
        let file_record_number = self.base_file_reference().file_record_number();
        ntfs.file(fs, file_record_number)
    }

    /// Returns the type of this NTFS attribute, or [`NtfsError::UnsupportedAttributeType`]
    /// if it's an unknown type.
    pub fn ty(&self) -> Result<NtfsAttributeType> {
        NtfsAttributeType::n(self.header.ty).ok_or(NtfsError::UnsupportedAttributeType {
            position: self.position(),
            actual: self.header.ty,
        })
    }

    fn validate_name_length(&self) -> Result<()> {
        let total_size = ATTRIBUTE_LIST_ENTRY_HEADER_SIZE + self.name_length();

        if total_size > self.list_entry_length() as usize {
            return Err(NtfsError::InvalidStructuredValueSize {
                position: self.position(),
                ty: NtfsAttributeType::AttributeList,
                expected: self.list_entry_length() as u64,
                actual: total_size as u64,
            });
        }

        Ok(())
    }
}