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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
use std::cmp::min;
use std::convert::TryInto;
use std::ffi::OsString;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use anyhow::{bail, Result};
use hmac_sha256::Hash;
mod cdrom;
use crate::cdrom::CDRomImage;
pub const DESIRED_SATURN_DISC: SaturnDisc = SaturnDisc {
desired_region_bytes: *br"JUBLKTEA",
desired_mfr_bytes: *br"SEGA TP T-81 ",
};
const SEGA_SATURN_BYTES: &[u8; 16] = br"SEGA SEGASATURN ";
const BACKUP_FILE_EXT: &str = ".saturnpatchbak";
const REGION_CODES: &[u8; 8] = br"JTUBKAEL";
const REGION_STRING_LEN: usize = 32;
const REGION_STRINGS: &[&[u8; REGION_STRING_LEN]] = &[
b"\xA0\x0E\x00\x09For JAPAN. ",
b"\xA0\x0E\x00\x09For TAIWAN and PHILIPINES. ",
b"\xA0\x0E\x00\x09For USA and CANADA. ",
b"\xA0\x0E\x00\x09For BRAZIL. ",
b"\xA0\x0E\x00\x09For KOREA. ",
b"\xA0\x0E\x00\x09For ASIA PAL area. ",
b"\xA0\x0E\x00\x09For EUROPE. ",
b"\xA0\x0E\x00\x09For LATIN AMERICA. ",
];
const MIN_BACKUP_SIZE: usize = 1 + 32 + 1;
fn region_index(region: &u8) -> Result<usize> {
let mut i = 0;
for c in REGION_CODES {
if c == region {
return Ok(i);
}
i += 1;
}
bail!("invalid region: {}", *region as char);
}
fn region_copy_sort_pad(regions: &[u8]) -> Vec<u8> {
let mut ret = regions.to_vec();
ret.sort_by(|a, b| region_index(a).unwrap_or(10).cmp(®ion_index(b).unwrap_or(10)));
while ret.len() < 16 {
ret.push(b' ');
}
ret
}
fn region_count(regions: &[u8]) -> usize {
let mut ret = 0;
while ret < regions.len() {
if regions[ret] == b' ' {
return ret;
}
ret += 1;
}
ret
}
fn first_index_of(file_name: &OsString, haystack: &[u8], needle: &[u8]) -> Result<usize> {
for i in 0..haystack.len() - needle.len() + 1 {
if haystack[i..i + needle.len()] == needle[..] {
return Ok(i);
}
}
bail!("not saturn image? {:?}", file_name);
}
pub struct SaturnDisc {
pub desired_region_bytes: [u8; 8],
pub desired_mfr_bytes: [u8; 16],
}
impl SaturnDisc {
pub fn from_env_args() -> Result<SaturnDisc> {
let desired_mfr_bytes = match std::env::var("SATURN_MANUFACTURER") {
Ok(k) => {
let mfr_bytes = k.as_bytes();
if mfr_bytes.len() == 0 {
DESIRED_SATURN_DISC.desired_mfr_bytes
} else {
if mfr_bytes.len() > 16 {
bail!("SATURN_MANUFACTURER length {} exceeds max length of 16", mfr_bytes.len());
}
let mut ret = [20u8; 16];
ret[0..mfr_bytes.len()].copy_from_slice(mfr_bytes);
ret
}
}
Err(_) => DESIRED_SATURN_DISC.desired_mfr_bytes,
};
let desired_region_bytes = match std::env::var("SATURN_REGION") {
Ok(k) => {
let k = k.to_ascii_uppercase();
let region_bytes = k.as_bytes();
if region_bytes.len() == 0 {
DESIRED_SATURN_DISC.desired_region_bytes
} else {
if region_bytes.len() > 8 {
bail!("SATURN_REGION length {} exceeds max length of 8", region_bytes.len());
}
for region in region_bytes {
region_index(region)?;
}
{
let mut region_vec = region_bytes.to_vec();
region_vec.sort();
region_vec.dedup();
if region_bytes.len() != region_bytes.len() {
bail!("SATURN_REGION must not have duplicate regions");
}
}
let mut empty = [20u8; 8];
empty[0..region_bytes.len()].copy_from_slice(region_bytes);
if region_bytes.len() != 8 {
let mut x = region_bytes.len();
REGION_CODES.iter().filter(|r| !region_bytes.contains(r)).for_each(|r| {
empty[x] = *r;
x += 1;
});
}
println!("SATURN_REGION: {}", String::from_utf8_lossy(&empty));
empty
}
}
Err(_) => DESIRED_SATURN_DISC.desired_region_bytes,
};
Ok(SaturnDisc {
desired_region_bytes,
desired_mfr_bytes,
})
}
pub fn patch(&self, file_name: &OsString) -> Result<()> {
let path = Path::new(file_name);
if !path.is_file() {
bail!("file does not exist: {:?}", file_name);
}
let mut file = File::open(file_name)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
let header_offset = first_index_of(file_name, &bytes[0..min(bytes.len(), 256)], SEGA_SATURN_BYTES)?;
let cdrom = CDRomImage::new(&bytes)?;
let orig_hash = Hash::hash(&bytes);
cdrom.update_sectors(&mut bytes);
if orig_hash != Hash::hash(&bytes) {
bail!("existing CD has bad sectors? refusing to update because won't be able to restore original file: {:?}", file_name);
}
let change_mfr = self.desired_mfr_bytes != &bytes[(header_offset + 16)..(header_offset + 32)];
let region_bytes = &bytes[(header_offset + 64)..(header_offset + 80)];
let region_count = region_count(®ion_bytes);
let new_region = region_copy_sort_pad(&self.desired_region_bytes[0..region_count]);
let change_region = new_region != region_bytes;
let region_bytes = ®ion_bytes[0..region_count].to_vec();
if change_mfr || change_region {
let mut first_region_string_index = bytes.len();
let mut region_string_indices = Vec::with_capacity(region_count);
let mut string_begin = header_offset + 80 + 16;
let mut string_end = bytes.len();
for i in 0..region_count {
let region_string = REGION_STRINGS[region_index(®ion_bytes[i])?];
let string_offset = first_index_of(file_name, &bytes[string_begin..string_end], region_string)? + string_begin;
if i == 0 && region_count > 1 {
string_begin = string_offset - ((region_count - 1) * REGION_STRING_LEN);
string_end = string_begin + (region_count * REGION_STRING_LEN * 2);
}
if string_offset < first_region_string_index {
first_region_string_index = string_offset;
}
region_string_indices.push(string_offset);
}
let mut backup_file_path = file_name.clone();
backup_file_path.push(BACKUP_FILE_EXT);
let backup_file_path = Path::new(&backup_file_path);
let write_header = !backup_file_path.is_file();
let mut backup_vec = Vec::new();
if write_header {
backup_vec.write_all(&orig_hash)?;
backup_vec.push(region_count as u8);
backup_vec.write_all(&(first_region_string_index as u32).to_be_bytes())?;
backup_vec.write_all(&bytes[(header_offset + 16)..(header_offset + 32)])?;
backup_vec.write_all(&bytes[(header_offset + 64)..(header_offset + 80)])?;
backup_vec.write_all(&bytes[first_region_string_index..(first_region_string_index + (region_count * REGION_STRING_LEN))])?;
}
if change_mfr {
&bytes[(header_offset + 16)..(header_offset + 32)].copy_from_slice(&self.desired_mfr_bytes);
}
if change_region {
&bytes[(header_offset + 64)..(header_offset + 80)].copy_from_slice(&new_region);
for i in 0..region_count {
let new_region_string = REGION_STRINGS[region_index(&new_region[i])?];
let string_offset = region_string_indices[i];
&bytes[string_offset..(string_offset + REGION_STRING_LEN)].copy_from_slice(new_region_string);
}
}
cdrom.update_sectors(&mut bytes);
if write_header {
let mut backup_file = File::create(backup_file_path)?;
backup_file.write_all(&[0])?;
backup_file.write_all(&Hash::hash(&backup_vec))?;
backup_file.write_all(&backup_vec)?;
drop(backup_vec);
}
let mut file = File::create(file_name)?;
file.write_all(&bytes)?;
print!("SUCCESS: ");
if write_header {
print!("wrote header backup, ");
}
if change_mfr {
print!("changed manufacturer, ");
}
if change_region {
print!("changed regions, ");
}
println!("patched: {:?}", file_name);
} else {
println!("SUCCESS: already desired manufacturer and regions {:?}", file_name);
}
Ok(())
}
pub fn unpatch(file_name: &OsString) -> Result<()> {
let path = Path::new(file_name);
if !path.is_file() {
bail!("file does not exist: {:?}", file_name);
}
let (file_name, header_backup_str) = if path.extension().map_or(false, |ext| ext.eq(&BACKUP_FILE_EXT[1..])) {
let mut new_path = path.to_path_buf();
new_path.set_file_name(path.file_stem().expect("no file name? impossible without extension I think..."));
(new_path.into_os_string(), file_name.to_owned())
} else {
let mut header_backup_str = file_name.clone();
header_backup_str.push(BACKUP_FILE_EXT);
(file_name.to_owned(), header_backup_str)
};
let path = Path::new(&file_name);
if !path.is_file() {
bail!("file {:?} does not exist for backup file {:?}", file_name, header_backup_str);
}
let header_backup = Path::new(&header_backup_str);
if !header_backup.is_file() {
bail!("backup file {:?} does not exist for file {:?}", header_backup_str, file_name);
}
let mut file = File::open(path)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
let mut header_backup = File::open(header_backup)?;
let mut header_bytes = Vec::new();
header_backup.read_to_end(&mut header_bytes)?;
if header_bytes.len() < MIN_BACKUP_SIZE {
bail!(
"backup file {:?} length {} is less than minimum length of {} for file {:?}",
header_backup_str,
header_bytes.len(),
MIN_BACKUP_SIZE,
file_name
);
}
if header_bytes[0] != 0 {
bail!("corrupt backup file or unsupported version {}, only version 0 supported: {:?}", header_bytes[0], header_backup_str);
}
if header_bytes[1..33] != Hash::hash(&header_bytes[33..]) {
bail!("corrupt backup file, hash mismatch: {:?}", header_backup_str);
}
let header_bytes = &header_bytes[33..];
let header_offset = first_index_of(&file_name, &bytes[0..min(bytes.len(), 256)], SEGA_SATURN_BYTES)?;
let cdrom = CDRomImage::new(&bytes)?;
let orig_hash = &header_bytes[0..32];
let region_count = header_bytes[32] as usize;
let first_region_string_index = u32::from_be_bytes(header_bytes[33..37].try_into()?) as usize;
let header_bytes = &header_bytes[37..];
let manufacturer = &header_bytes[0..16];
let regions = &header_bytes[16..32];
let region_strings = &header_bytes[32..];
if &bytes[(header_offset + 16)..(header_offset + 32)] != manufacturer
|| &bytes[(header_offset + 64)..(header_offset + 80)] != regions
|| &bytes[first_region_string_index..(first_region_string_index + (region_count * REGION_STRING_LEN))] != region_strings
{
&bytes[(header_offset + 16)..(header_offset + 32)].copy_from_slice(manufacturer);
&bytes[(header_offset + 64)..(header_offset + 80)].copy_from_slice(regions);
&bytes[first_region_string_index..(first_region_string_index + (region_count * REGION_STRING_LEN))].copy_from_slice(region_strings);
cdrom.update_sectors(&mut bytes);
if orig_hash != Hash::hash(&bytes) {
bail!("restore failed, hash mismatch: {:?}", file_name);
}
let mut file = File::create(&file_name)?;
file.write_all(&bytes)?;
file.flush()?;
drop(file);
std::fs::remove_file(header_backup_str).ok();
println!("SUCCESS: unpatched: {:?}", file_name);
} else if orig_hash == Hash::hash(&bytes) {
std::fs::remove_file(header_backup_str).ok();
println!("SUCCESS: already unpatched: {:?}", file_name);
} else {
bail!("restore failed, unknown problem: {:?}", file_name);
}
Ok(())
}
}