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
//! Local content-addressed store: each (package, version, dist reference) is
//! extracted ONCE into `<cache>/store/<vendor>/<pkg>/<key>/`, then cloned
//! into the projects' vendor/ (see clone.rs). Atomic write: extraction into a
//! sibling temporary directory then `rename`; the final directory only exists
//! complete, and two concurrent processes converge (the loser of the rename
//! discards its temporary directory).
use crate::error::{Error, Result};
use crate::extract::{extract_tar, extract_zip};
/// The archive format of a dist in the store.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DistKind {
Zip,
Tar,
}
use std::path::PathBuf;
pub struct Store {
root: PathBuf,
}
/// Segment naming the extraction semantics an entry was written with. A store
/// entry is a *tree*, not an archive, so it carries whatever rule the build
/// that wrote it applied — and when that rule changes (`v2`: the modes come
/// from the archive instead of "executable → 0755, default otherwise"), an old
/// entry keeps serving the old tree forever, silently. Bumping this segment is
/// what makes the change take effect; the previous trees stay on disk, unused,
/// until the cache is cleared.
const LAYOUT: &str = "v2";
impl Store {
pub fn at(root: PathBuf) -> Store {
Store { root }
}
pub fn default_location() -> Store {
Store::at(crate::platform::cache_dir().join("store"))
}
/// Entry key: version + first 12 hex chars of the dist reference,
/// sanitised for the file system.
pub fn entry_path(&self, name: &str, version: &str, dist_ref: Option<&str>) -> PathBuf {
let sane = |s: &str| -> String {
s.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
c
} else {
'-'
}
})
.collect()
};
let short_ref = dist_ref.unwrap_or("noref");
let short_ref = &short_ref[..short_ref.len().min(12)];
self.root
.join(LAYOUT)
.join(name) // vendor/pkg: two safe segments (validated by the lock)
.join(format!("{}-{}", sane(version), sane(short_ref)))
}
/// Ensures the entry is present, extracting it if needed.
/// Returns the path of the extracted tree.
pub fn ensure(
&self,
name: &str,
version: &str,
dist_ref: Option<&str>,
dist_bytes: &[u8],
kind: DistKind,
) -> Result<PathBuf> {
let final_path = self.entry_path(name, version, dist_ref);
if final_path.is_dir() {
return Ok(final_path);
}
let parent = final_path.parent().unwrap_or(&self.root).to_path_buf();
std::fs::create_dir_all(&parent).map_err(Error::io(&parent))?;
let tmp = tempfile::Builder::new()
.prefix(".tmp-")
.tempdir_in(&parent)
.map_err(Error::io(&parent))?;
let extracted = match kind {
DistKind::Zip => extract_zip(dist_bytes, tmp.path()),
DistKind::Tar => extract_tar(dist_bytes, tmp.path()),
};
// A refusal names the package, not `.tmp-EX4VNV` under the store.
extracted.map_err(|e| match e {
Error::HostileArchive { reason, .. } => Error::HostileDist {
name: name.to_owned(),
version: version.to_owned(),
reason,
},
other => other,
})?;
let tmp_path = tmp.keep();
match std::fs::rename(&tmp_path, &final_path) {
Ok(()) => Ok(final_path),
Err(_) if final_path.is_dir() => {
// A concurrent process won the rename: its entry is complete.
let _ = std::fs::remove_dir_all(&tmp_path);
Ok(final_path)
}
Err(source) => {
let _ = std::fs::remove_dir_all(&tmp_path);
Err(Error::Io {
path: final_path,
source,
})
}
}
}
pub fn contains(&self, name: &str, version: &str, dist_ref: Option<&str>) -> bool {
self.entry_path(name, version, dist_ref).is_dir()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write as _;
use zip::write::SimpleFileOptions;
fn sample_zip() -> Vec<u8> {
let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
w.add_directory("root-x", SimpleFileOptions::default())
.expect("dir");
w.start_file("root-x/composer.json", SimpleFileOptions::default())
.expect("f");
w.write_all(b"{}").expect("w");
w.finish().expect("finish").into_inner()
}
#[test]
fn ensure_is_idempotent_and_atomic() {
let dir = tempfile::tempdir().expect("tmp");
let store = Store::at(dir.path().join("store"));
let zip = sample_zip();
let p1 = store
.ensure(
"a/b",
"1.0.0",
Some("deadbeefcafe1234"),
&zip,
DistKind::Zip,
)
.expect("ensure");
assert!(p1.join("composer.json").is_file());
assert!(store.contains("a/b", "1.0.0", Some("deadbeefcafe1234")));
// Second call: same bytes or not, the existing entry wins.
let p2 = store
.ensure(
"a/b",
"1.0.0",
Some("deadbeefcafe1234"),
b"garbage",
DistKind::Zip,
)
.expect("hit");
assert_eq!(p1, p2);
// Different key -> other entry.
assert!(!store.contains("a/b", "1.0.0", Some("feedfacefeed5678")));
// Hostile version sanitised (no traversal).
let p3 = store
.ensure("a/b", "../../evil", None, &zip, DistKind::Zip)
.expect("sane");
assert!(p3.starts_with(dir.path().join("store").join(LAYOUT).join("a/b")));
// The layout segment is part of the key: a tree written by another
// extraction rule is never served under this one.
assert!(store
.entry_path("a/b", "1.0.0", Some("deadbeefcafe1234"))
.components()
.any(|c| c.as_os_str() == LAYOUT));
}
}