1use std::collections::HashMap;
10use std::fs;
11use std::io;
12use std::path::Path;
13
14pub const FLAG_BY_ID: u8 = 0x01;
15pub const FLAG_EXTERNAL: u8 = 0x02;
16pub const FLAG_PRELOAD: u8 = 0x04;
17pub const FLAG_PRELOCK: u8 = 0x08;
18pub const FLAG_ENCRYPTED: u8 = 0x10;
19
20const ENTRY_SIZE: usize = 48;
21
22#[derive(Debug, Clone)]
23pub struct RffEntry {
24 pub offset: u32,
25 pub size: u32,
26 pub time: u32,
27 pub flags: u8,
28 pub ext: String,
30 pub name: String,
32 pub id: u32,
33}
34
35impl RffEntry {
36 pub fn file_name(&self) -> String {
37 format!("{}.{}", self.name, self.ext)
38 }
39}
40
41pub struct Rff {
42 data: Vec<u8>,
43 pub version: u16,
44 pub entries: Vec<RffEntry>,
45 by_name: HashMap<String, usize>,
46 by_id: HashMap<(String, u32), usize>,
47}
48
49fn invalid(msg: impl Into<String>) -> io::Error {
50 io::Error::new(io::ErrorKind::InvalidData, msg.into())
51}
52
53fn cstr(bytes: &[u8]) -> String {
54 let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
55 String::from_utf8_lossy(&bytes[..end]).to_ascii_uppercase()
56}
57
58pub fn crypt(buf: &mut [u8], key: u32) {
61 for (i, b) in buf.iter_mut().enumerate() {
62 *b ^= (key.wrapping_add(i as u32) >> 1) as u8;
63 }
64}
65
66fn crypt_v300(buf: &mut [u8], key: u32) {
68 for (i, b) in buf.iter_mut().enumerate() {
69 *b ^= ((key.wrapping_add(i as u32) & 0xff) >> 1) as u8;
70 }
71}
72
73impl Rff {
74 pub fn open(path: impl AsRef<Path>) -> io::Result<Self> {
75 Self::from_bytes(fs::read(path)?)
76 }
77
78 pub fn from_bytes(data: Vec<u8>) -> io::Result<Self> {
79 if data.len() < 32 || &data[0..4] != b"RFF\x1a" {
80 return Err(invalid("not an RFF archive"));
81 }
82 let version = u16::from_le_bytes([data[4], data[5]]);
83 let dict_off = u32::from_le_bytes(data[8..12].try_into().unwrap()) as usize;
84 let count = u32::from_le_bytes(data[12..16].try_into().unwrap()) as usize;
85 let dict_len = count * ENTRY_SIZE;
86 if dict_off + dict_len > data.len() {
87 return Err(invalid("RFF dictionary out of range"));
88 }
89 let mut dict = data[dict_off..dict_off + dict_len].to_vec();
90 let key0 = (dict_off & 0xff) as u32;
91 match version {
92 0x0200 => {}
93 0x0300 => crypt_v300(&mut dict, key0),
94 0x0301 => crypt(&mut dict, key0 * 2),
95 _ => return Err(invalid(format!("unsupported RFF version {version:#x}"))),
96 }
97
98 let mut entries = Vec::with_capacity(count);
99 let mut by_name = HashMap::new();
100 let mut by_id = HashMap::new();
101 for (i, e) in dict.as_chunks::<ENTRY_SIZE>().0.iter().enumerate() {
102 let rd = |o: usize| u32::from_le_bytes(e[o..o + 4].try_into().unwrap());
103 let entry = RffEntry {
104 offset: rd(16),
105 size: rd(20),
106 time: rd(28),
107 flags: e[32],
108 ext: cstr(&e[33..36]),
109 name: cstr(&e[36..44]),
110 id: rd(44),
111 };
112 by_name.insert(entry.file_name(), i);
113 by_id.insert((entry.ext.clone(), entry.id), i);
114 entries.push(entry);
115 }
116 Ok(Rff {
117 data,
118 version,
119 entries,
120 by_name,
121 by_id,
122 })
123 }
124
125 pub fn find(&self, file_name: &str) -> Option<&RffEntry> {
126 self.by_name
127 .get(&file_name.to_ascii_uppercase())
128 .map(|&i| &self.entries[i])
129 }
130
131 pub fn find_id(&self, ext: &str, id: u32) -> Option<&RffEntry> {
132 self.by_id
133 .get(&(ext.to_ascii_uppercase(), id))
134 .map(|&i| &self.entries[i])
135 }
136
137 pub fn read(&self, entry: &RffEntry) -> io::Result<Vec<u8>> {
139 let start = entry.offset as usize;
140 let end = start + entry.size as usize;
141 if end > self.data.len() {
142 return Err(invalid(format!("entry {} out of range", entry.file_name())));
143 }
144 let mut out = self.data[start..end].to_vec();
145 if entry.flags & FLAG_ENCRYPTED != 0 {
146 let n = out.len().min(256);
147 crypt(&mut out[..n], 0);
148 }
149 Ok(out)
150 }
151
152 pub fn read_name(&self, file_name: &str) -> Option<Vec<u8>> {
153 self.find(file_name).and_then(|e| self.read(e).ok())
154 }
155
156 pub fn read_id(&self, ext: &str, id: u32) -> Option<Vec<u8>> {
157 self.find_id(ext, id).and_then(|e| self.read(e).ok())
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164
165 #[test]
166 fn crypt_roundtrip() {
167 let orig: Vec<u8> = (0..300u32).map(|i| (i * 7) as u8).collect();
168 let mut b = orig.clone();
169 crypt(&mut b, 17);
170 assert_ne!(b, orig);
171 crypt(&mut b, 17);
172 assert_eq!(b, orig);
173 }
174
175 #[test]
176 fn parse_synthetic_v301() {
177 let payload: Vec<u8> = b"HELLO BLOOD".to_vec();
178 let mut file = vec![0u8; 32];
179 file[0..4].copy_from_slice(b"RFF\x1a");
180 file[4..6].copy_from_slice(&0x0301u16.to_le_bytes());
181 let data_off = file.len() as u32;
182 let mut enc = payload.clone();
183 crypt(&mut enc, 0);
184 file.extend_from_slice(&enc);
185 let dict_off = file.len() as u32;
186 let mut e = vec![0u8; 48];
187 e[16..20].copy_from_slice(&data_off.to_le_bytes());
188 e[20..24].copy_from_slice(&(payload.len() as u32).to_le_bytes());
189 e[32] = FLAG_ENCRYPTED;
190 e[33..36].copy_from_slice(b"TXT");
191 e[36..40].copy_from_slice(b"TEST");
192 e[44..48].copy_from_slice(&5u32.to_le_bytes());
193 crypt(&mut e, (dict_off & 0xff) * 2);
194 file.extend_from_slice(&e);
195 file[8..12].copy_from_slice(&dict_off.to_le_bytes());
196 file[12..16].copy_from_slice(&1u32.to_le_bytes());
197
198 let rff = Rff::from_bytes(file).unwrap();
199 assert_eq!(rff.entries[0].file_name(), "TEST.TXT");
200 assert_eq!(rff.read_name("test.txt").unwrap(), payload);
201 assert_eq!(rff.read_id("TXT", 5).unwrap(), payload);
202 }
203}