-
Notifications
You must be signed in to change notification settings - Fork 2
/
lib.rs
563 lines (523 loc) · 16.7 KB
/
lib.rs
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
use gvariant::{
aligned_bytes::{copy_to_align, read_to_slice, AlignedSlice, Alignment, AsAligned, A1, A4, A8},
gv, Marker, Structure,
};
use hex::{FromHex, ToHex};
use itertools::Either;
use nix::{dir::Dir, fcntl::OFlag, sys::stat::Mode};
use ref_cast::RefCast;
use std::{
convert::TryInto,
error::Error,
ffi::{CStr, OsStr},
fmt::Display,
fs::File,
io::{ErrorKind, Read},
iter::empty,
os::unix::io::{AsRawFd, FromRawFd},
path::{Path, PathBuf},
};
use xattr::FileExt;
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, RefCast, Copy, Clone)]
#[repr(transparent)]
pub struct Oid(pub [u8; 32]);
impl Oid {
pub const ZERO: Oid = Oid([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0,
]);
pub fn try_from_slice(s: &[u8]) -> Option<&Self> {
let x: &[u8; 32] = s.try_into().ok()?;
Some(Self::ref_cast(x))
}
fn from_prefix_suffix(prefix: u8, suffix: &[u8; 31]) -> Oid {
let mut out = Oid::ZERO;
out.0[0] = prefix;
out.0[1..].copy_from_slice(suffix);
out
}
pub fn to_hex(&self) -> OidHex {
let mut out = [0u8; 65];
hex::encode_to_slice(&self.0, &mut out[..64]).unwrap();
OidHex(out)
}
}
impl Display for Oid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Oid::from_hex(\"{}\")", hex::encode(self.0))
}
}
impl FromHex for Oid {
type Error = hex::FromHexError;
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
Ok(Self(<[u8; 32]>::from_hex(hex)?))
}
}
impl ToHex for Oid {
fn encode_hex<T: std::iter::FromIterator<char>>(&self) -> T {
self.0.encode_hex()
}
fn encode_hex_upper<T: std::iter::FromIterator<char>>(&self) -> T {
self.0.encode_hex_upper()
}
}
impl AsRef<Oid> for [u8] {
fn as_ref(&self) -> &Oid {
match self.try_into() {
Ok(a) => Oid::ref_cast(a),
Err(_) => &Oid::ZERO,
}
}
}
pub struct OidHex([u8; 65]);
impl From<Oid> for OidHex {
fn from(oid: Oid) -> Self {
oid.to_hex()
}
}
impl AsRef<CStr> for OidHex {
fn as_ref(&self) -> &CStr {
CStr::from_bytes_with_nul(&self.0).unwrap()
}
}
impl AsRef<str> for OidHex {
fn as_ref(&self) -> &str {
std::str::from_utf8(&self.0[..64]).unwrap()
}
}
impl AsRef<OsStr> for OidHex {
fn as_ref(&self) -> &OsStr {
let x: &str = self.as_ref();
x.as_ref()
}
}
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, RefCast, Copy, Clone)]
#[repr(transparent)]
pub struct CommitId(pub Oid);
impl CommitId {
pub fn try_from_slice(s: &[u8]) -> Option<&Self> {
Some(Self::ref_cast(Oid::try_from_slice(s)?))
}
}
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, RefCast, Copy, Clone)]
#[repr(transparent)]
pub struct DirTreeId(pub Oid);
impl DirTreeId {
pub fn try_from_slice(s: &[u8]) -> Option<&Self> {
Some(Self::ref_cast(Oid::try_from_slice(s)?))
}
}
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, RefCast, Copy, Clone)]
#[repr(transparent)]
pub struct DirMetaId(pub Oid);
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, RefCast, Copy, Clone)]
#[repr(transparent)]
pub struct ContentId(pub Oid);
impl ContentId {
pub fn try_from_slice(s: &[u8]) -> Option<&Self> {
Some(Self::ref_cast(Oid::try_from_slice(s)?))
}
}
fn open_file_at(d: &Dir, path: &impl AsRef<Path>) -> nix::Result<File> {
let fd = nix::fcntl::openat(
d.as_raw_fd(),
path.as_ref(),
OFlag::O_CLOEXEC | OFlag::O_RDONLY,
Mode::empty(),
)?;
// The invariant that we need to uphold for this unsafe block is that the fd
// must be owned by only one object. As we've just created this fd this is
// safe:
Ok(unsafe { File::from_raw_fd(fd) })
}
#[derive(Debug, Eq, PartialEq)]
pub enum ObjType {
COMMIT,
DIRTREE,
DIRMETA,
FILE,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash, Ord, PartialOrd)]
pub enum ObjId {
Commit(CommitId),
DirTree(DirTreeId),
DirMeta(DirMetaId),
Content(ContentId),
}
impl From<CommitId> for ObjId {
fn from(x: CommitId) -> Self {
ObjId::Commit(x)
}
}
impl From<DirTreeId> for ObjId {
fn from(x: DirTreeId) -> Self {
ObjId::DirTree(x)
}
}
impl From<DirMetaId> for ObjId {
fn from(x: DirMetaId) -> Self {
ObjId::DirMeta(x)
}
}
impl From<ContentId> for ObjId {
fn from(x: ContentId) -> Self {
ObjId::Content(x)
}
}
pub struct Repo {
repo: Dir,
}
impl Repo {
pub fn open(path: impl AsRef<std::path::Path>) -> Result<Self, Box<dyn Error>> {
let repo = Dir::open(
path.as_ref(),
OFlag::O_DIRECTORY | OFlag::O_CLOEXEC | OFlag::O_RDONLY,
Mode::empty(),
)?;
Ok(Self { repo })
}
pub fn open_object(&self, oid: &ObjId) -> Result<File, std::io::Error> {
let (extension, sha) = match oid {
ObjId::Commit(oid) => ("commit", oid.0),
ObjId::DirTree(oid) => ("dirtree", oid.0),
ObjId::DirMeta(oid) => ("dirmeta", oid.0),
ObjId::Content(oid) => ("file", oid.0),
};
// TODO: Avoid this allocation
let path = format!(
"objects/{:02x}/{}.{}",
sha.0[0],
hex::encode(&sha.0[1..]),
extension
);
Ok(open_file_at(&self.repo, &path).map_err(|x| x.as_errno().unwrap())?)
}
pub fn read_meta(&self, oid: &ContentId) -> Result<Meta, Box<dyn Error>> {
let file = self.open_object(&ObjId::Content(*oid))?;
let meta = file
.get_xattr("user.ostreemeta")?
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?;
let meta = copy_to_align(&meta);
let m = file.metadata()?;
Ok(Meta::from_data(meta.as_ref(), m.len()))
}
fn read_object<A: Alignment>(
&self,
oid: &ObjId,
) -> Result<Box<AlignedSlice<A>>, std::io::Error> {
let f = self.open_object(oid)?;
Ok(read_to_slice(f, None)?)
}
pub fn read_content(&self, oid: &ContentId) -> Result<Vec<u8>, std::io::Error> {
let mut f = self.open_object(&(*oid).into())?;
let mut out = vec![];
f.read_to_end(&mut out)?;
Ok(out)
}
pub fn read_dirtree(&self, oid: &DirTreeId) -> Result<OwnedDirTree, std::io::Error> {
Ok(OwnedDirTree(self.read_object(&(*oid).into())?))
}
pub fn read_commit(&self, oid: &CommitId) -> Result<OwnedCommit, std::io::Error> {
Ok(OwnedCommit(self.read_object(&(*oid).into())?))
}
pub fn read_dirmeta(&self, oid: &DirMetaId) -> Result<Meta, std::io::Error> {
let data = self.read_object(&(*oid).into())?;
Ok(Meta::from_data(&*data, 0))
}
pub fn read_content_xattrs(&self, oid: &ContentId) -> Result<Xattrs, std::io::Error> {
let file = self.open_object(&ObjId::Content(*oid))?;
let meta = file
.get_xattr("user.ostreemeta")?
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?;
let meta = copy_to_align(&meta).into_owned();
Ok(Xattrs::from_data(meta))
}
pub fn read_dirmeta_xattrs(&self, oid: &DirMetaId) -> Result<Xattrs, Box<dyn Error>> {
let data = self.read_object(&(*oid).into())?;
Ok(Xattrs::from_data(data))
}
pub fn iter_objects(&self) -> impl Iterator<Item = Result<ObjId, std::io::Error>> + '_ {
(0..=255)
.into_iter()
.map(move |prefix| self.iter_objects_with_prefix(prefix))
.flatten()
}
fn iter_objects_with_prefix(
&self,
prefix: u8,
) -> impl Iterator<Item = Result<ObjId, std::io::Error>> {
let path: PathBuf = ["objects", &format!("{:02x}", prefix)].iter().collect();
let d = Dir::openat(
self.repo.as_raw_fd(),
&path,
OFlag::O_CLOEXEC | OFlag::O_DIRECTORY | OFlag::O_RDONLY,
Mode::empty(),
);
let d = match d {
Ok(d) => d,
Err(nix::Error::Sys(nix::errno::Errno::ENOENT)) => {
return Either::Right(Either::Left(empty()))
}
Err(x) => return Either::Right(Either::Right(std::iter::once(Err(nix_to_std(x))))),
};
Either::Left(d.into_iter().filter_map(move |entry| match entry {
Ok(entry) => dirent_to_objid(prefix, entry).map(Ok),
Err(x) => Some(Err(nix_to_std(x))),
}))
}
}
fn nix_to_std(e: nix::Error) -> std::io::Error {
if let nix::Error::Sys(errno) = e {
errno.into()
} else {
std::io::Error::new(ErrorKind::Other, e)
}
}
fn dirent_to_objid(prefix: u8, entry: nix::dir::Entry) -> Option<ObjId> {
let filename = entry.file_name().to_bytes();
match filename {
b"." | b".." => return None,
_ => {}
}
if filename.len() < 62 {
eprintln!(
"Not a valid object filename: {:?}. Filename too short",
String::from_utf8_lossy(filename)
);
return None;
}
let (str_sha, ext) = filename.split_at(62);
let oid_suffix = match <[u8; 31]>::from_hex(str_sha) {
Ok(x) => x,
Err(err) => {
eprintln!(
"Error converting {:?} from hex: {:?}",
String::from_utf8_lossy(&str_sha),
err
);
return None;
}
};
let oid = Oid::from_prefix_suffix(prefix, &oid_suffix);
Some(match ext {
b".commit" => ObjId::Commit(CommitId(oid)),
b".dirmeta" => ObjId::DirMeta(DirMetaId(oid)),
b".dirtree" => ObjId::DirTree(DirTreeId(oid)),
b".file" => ObjId::Content(ContentId(oid)),
_ => {
eprintln!(
"Incorrect extension {:?} for file: {:?}",
ext,
String::from_utf8_lossy(filename)
);
return None;
}
})
}
fn buf_as_commit(buf: &AlignedSlice<A8>) -> Commit<'_> {
let c = gv!("(a{sv}aya(say)sstayay)").cast(&buf);
let (_, parent, _, _, _, _, dirtree, dirmeta) = c.to_tuple();
Commit {
parent: CommitId::ref_cast(parent.as_ref()),
dirtree: DirTreeId::ref_cast(dirtree.as_ref()),
dirmeta: DirMetaId::ref_cast(dirmeta.as_ref()),
}
}
pub struct Commit<'a> {
pub parent: &'a CommitId,
pub dirtree: &'a DirTreeId,
pub dirmeta: &'a DirMetaId,
}
pub struct OwnedCommit(Box<AlignedSlice<A8>>);
impl OwnedCommit {
pub fn as_commit(&self) -> Commit<'_> {
self.into()
}
}
impl<'a> From<&'a OwnedCommit> for Commit<'a> {
fn from(x: &'a OwnedCommit) -> Self {
buf_as_commit(&x.0)
}
}
// (a(say)a(sayay))
#[derive(Debug, RefCast)]
#[repr(transparent)]
pub struct DirTree<'a>(&'a AlignedSlice<A1>);
pub struct OwnedDirTree(Box<AlignedSlice<A1>>);
impl OwnedDirTree {
pub fn as_dirtree(&self) -> DirTree<'_> {
self.into()
}
}
impl<'a> From<&'a OwnedDirTree> for DirTree<'a> {
fn from(x: &'a OwnedDirTree) -> Self {
DirTree(&x.0)
}
}
impl<'a> DirTree<'a> {
pub fn from_bytes(b: &'a [u8]) -> Self {
DirTree(b.as_aligned())
}
pub fn iter_files(&'a self) -> impl Iterator<Item = FileEntry<'a>> + ExactSizeIterator {
let files = gv!("(a(say)a(sayay))").cast(&self.0).to_tuple().0;
files.into_iter().map(|x| x.to_tuple().into())
}
pub fn iter_dirs(&'a self) -> impl Iterator<Item = DirEntry<'a>> + ExactSizeIterator {
let files = gv!("(a(say)a(sayay))").cast(&self.0).to_tuple().1;
files.into_iter().map(|x| x.to_tuple().into())
}
}
pub struct DirEntry<'a> {
pub name: &'a str,
pub dirtree_id: &'a DirTreeId,
pub dirmeta_id: &'a DirMetaId,
}
impl<'a> DirEntry<'a> {
pub fn from_tuple(t: (&'a gvariant::Str, &'a [u8], &'a [u8])) -> Option<Self> {
Some(Self {
name: t.0.to_str(),
dirtree_id: DirTreeId::ref_cast(Oid::try_from_slice(t.1)?),
dirmeta_id: DirMetaId::ref_cast(Oid::try_from_slice(t.2)?),
})
}
}
impl<'a> From<(&'a gvariant::Str, &'a [u8], &'a [u8])> for DirEntry<'a> {
fn from(t: (&'a gvariant::Str, &'a [u8], &'a [u8])) -> Self {
Self {
name: t.0.to_str(),
dirtree_id: DirTreeId::ref_cast(t.1.as_ref()),
dirmeta_id: DirMetaId::ref_cast(t.2.as_ref()),
}
}
}
pub struct FileEntry<'a> {
pub name: &'a str,
pub oid: &'a ContentId,
}
impl<'a> FileEntry<'a> {
pub fn from_tuple(t: (&'a gvariant::Str, &'a [u8])) -> Option<Self> {
Some(t.into())
}
}
impl<'a> From<(&'a gvariant::Str, &'a [u8])> for FileEntry<'a> {
fn from(x: (&'a gvariant::Str, &'a [u8])) -> Self {
FileEntry {
name: x.0.to_str(),
oid: ContentId::ref_cast(x.1.as_ref()),
}
}
}
// (uuua(ayay))
pub struct Meta {
pub uid: u32,
pub gid: u32,
pub mode: u32,
pub size: u64,
}
pub struct Xattrs(Box<AlignedSlice<A4>>);
impl Xattrs {
fn from_data(data: Box<AlignedSlice<A4>>) -> Xattrs {
Xattrs(data)
}
pub fn get(&self, key: &[u8]) -> Option<&[u8]> {
let (_, _, _, xattrs) = gv!("(uuua(ayay))").cast(&self.0).to_tuple();
for x in xattrs {
let (k, v) = x.to_tuple();
if let Ok(k) = CStr::from_bytes_with_nul(k) {
if k.to_bytes() == key {
return Some(v);
}
}
}
None
}
pub fn iter_keys(&self) -> impl Iterator<Item = &CStr> {
let (_, _, _, xattrs) = gv!("(uuua(ayay))").cast(&self.0).to_tuple();
xattrs
.iter()
.filter_map(|x| CStr::from_bytes_with_nul(&x.to_tuple().0).ok())
}
}
impl Meta {
pub fn from_data(data: &AlignedSlice<A4>, size: u64) -> Self {
let (uid, gid, mode, _xattrs) = gv!("(uuua(ayay))").cast(data).to_tuple();
Self {
uid: u32::from_be(*uid),
gid: u32::from_be(*gid),
mode: u32::from_be(*mode),
size,
}
}
}
#[cfg(test)]
mod tests {
use crate::{CommitId, ContentId, ObjId, Oid, Repo};
use hex::FromHex;
use std::{ffi::CStr, path::PathBuf};
use tempfile::tempdir;
#[test]
fn oid_from_hex() {
assert_eq!(
Oid::from_hex("750574081316f0c9078674bbe599bb79902a9d1b8020a92c56b81a69179452e5")
.unwrap(),
Oid([
0x75, 0x05, 0x74, 0x08, 0x13, 0x16, 0xf0, 0xc9, 0x07, 0x86, 0x74, 0xbb, 0xe5, 0x99,
0xbb, 0x79, 0x90, 0x2a, 0x9d, 0x1b, 0x80, 0x20, 0xa9, 0x2c, 0x56, 0xb8, 0x1a, 0x69,
0x17, 0x94, 0x52, 0xe5
])
);
}
#[test]
fn test_open_object() {
todo!("Open object of all different types, make sure there's no error");
todo!("Open object that doesn't exist, check for ENOENT");
}
const BARE_USER_REPO_TAR: &[u8] = include_bytes!("../../ostree-repo/testdata/bare-user.tar");
fn with_repo() -> (tempfile::TempDir, Repo) {
// Setup
let tmp = tempdir().unwrap();
let mountpoint = tmp.path().join("repo");
let repo = tmp.path().join("mnt");
std::fs::create_dir(&mountpoint).unwrap();
std::fs::create_dir(&repo).unwrap();
let mut bare_user_repo = tar::Archive::new(BARE_USER_REPO_TAR);
bare_user_repo.set_unpack_xattrs(true);
bare_user_repo.set_preserve_permissions(true);
bare_user_repo.unpack(&repo).unwrap();
let repo = Repo::open(&repo).unwrap();
(tmp, repo)
}
#[test]
fn test_read_xattrs() {
let (_tmpdir, repo) = with_repo();
let xattrs = repo
.read_content_xattrs(&ContentId(
Oid::from_hex("aaf192101c4250090c9c442189abc29f34959fa1f1288d3d58755b4897cb6c53")
.unwrap(),
))
.unwrap();
assert_eq!(
xattrs.iter_keys().collect::<Vec<_>>(),
[
CStr::from_bytes_with_nul(b"user.cow\0").unwrap(),
CStr::from_bytes_with_nul(b"user.no-value\0").unwrap(),
]
);
assert_eq!(xattrs.get(b"user.no-value").unwrap(), b"");
assert_eq!(xattrs.get(b"user.cow").unwrap(), b"goes moo");
}
#[test]
fn test_for_each_object() {
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("testdata/repo");
let r = Repo::open(d.as_path()).unwrap();
let v: Result<Vec<_>, _> = r.iter_objects().collect();
let v = v.unwrap();
let oid = Oid([
0x00u8, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13,
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x30, 0x31,
]);
assert_eq!(v[0], ObjId::Commit(CommitId(oid)));
}
}