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
use std::{
cell::{Cell, RefCell},
fmt,
fs::{self, OpenOptions},
io::{self, Read},
os::unix::{self, fs::PermissionsExt},
path::{self, Path, PathBuf},
};
use crate::{error::NarError, parser};
pub struct Decoder<R: Read> {
inner: DecoderInner<R>,
}
pub struct DecoderInner<R> {
pos: Cell<u64>,
reader: RefCell<R>,
}
pub struct Entries<'a, R: Read> {
decoder: &'a Decoder<R>,
current_activity: CurrentActivity,
}
#[derive(Debug)]
pub struct Entry<'a, R> {
pub path: Option<PathBuf>,
pub content: Content<'a, R>,
}
pub enum Content<'a, R> {
Directory,
Symlink { target: PathBuf },
File {
executable: bool,
size: u64,
offset: u64,
data: io::Take<&'a DecoderInner<R>>,
},
}
impl<'a, R> Content<'a, R> {
pub fn is_directory(&self) -> bool {
matches!(self, Self::Directory)
}
pub fn is_symlink(&self) -> bool {
matches!(self, Self::Symlink { .. })
}
pub fn is_file(&self) -> bool {
matches!(self, Self::File { .. })
}
}
#[derive(Debug)]
enum CurrentActivity {
Finished,
ParsingTopLevel,
ParsingContent { next: u64, path: PathBuf },
ParsingDirectoryEntries { path: PathBuf },
}
impl<R: Read> Decoder<R> {
pub fn new(reader: R) -> Result<Self, NarError> {
let inner = DecoderInner {
pos: Cell::new(0),
reader: RefCell::new(reader),
};
parser::expect_str(&inner, "nix-archive-1")?;
Ok(Self { inner })
}
pub fn entries(&self) -> Result<Entries<R>, NarError> {
Entries::new(self)
}
pub fn unpack<P: AsRef<Path>>(&self, dst: P) -> Result<(), NarError> {
let dst = dst.as_ref();
if fs::symlink_metadata(dst).is_ok() {
return Err(NarError::UnpackError(format!(
"Unpack destination already exists: {}. Delete it first.",
dst.display()
)));
}
for entry in self.entries()? {
let entry = entry?;
match &entry.path {
None => {}
Some(path) => {
if path
.components()
.any(|c| !matches!(c, path::Component::Normal(_)))
{
continue;
}
}
}
let dst_path = entry
.path
.map(|path| dst.join(path))
.unwrap_or_else(|| dst.to_path_buf());
macro_rules! assert_parent_is_dir {
($dst_path:ident) => {
if let Some(parent) = dst_path.parent() {
if !parent.is_dir() {
return Err(NarError::UnpackError(format!(
"Entry {} has a parent which is not a directory",
dst_path.display()
)));
}
}
};
}
match entry.content {
Content::Directory => {
fs::create_dir(dst_path)?;
}
Content::Symlink { target } => {
assert_parent_is_dir!(dst_path);
unix::fs::symlink(target, dst_path)?;
}
Content::File {
executable,
size: _,
offset: _,
mut data,
} => {
assert_parent_is_dir!(dst_path);
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(dst_path)?;
io::copy(&mut data, &mut file)?;
let mut perms = file.metadata()?.permissions();
perms.set_mode(if executable { 0o555 } else { 0o444 });
file.set_permissions(perms)?;
}
}
}
Ok(())
}
}
impl<'a, R: Read> Read for &'a DecoderInner<R> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
let i = self.reader.borrow_mut().read(into)?;
self.pos.set(self.pos.get() + i as u64);
Ok(i)
}
}
impl<'a, R: Read> Entries<'a, R> {
fn new(decoder: &'a Decoder<R>) -> Result<Self, NarError> {
let decoder_pos = decoder.inner.pos.get();
if decoder_pos != 24 {
return Err(NarError::ApiError(format!(
"Can only call `entries` on a new `Decoder`. This one is at position {decoder_pos}."
)));
}
Ok(Self {
decoder,
current_activity: CurrentActivity::ParsingTopLevel,
})
}
fn handle_parse_regular(
&mut self,
path: Option<PathBuf>,
executable: bool,
size: u64,
) -> Entry<'a, R> {
let size_rounded_up = (size + 7) & !7;
self.current_activity = CurrentActivity::ParsingContent {
next: self.decoder.inner.pos.get() + size_rounded_up,
path: path.clone().unwrap_or_else(PathBuf::new),
};
Entry {
path,
content: Content::File {
executable,
size,
offset: self.decoder.inner.pos.get(),
data: self.decoder.inner.take(size),
},
}
}
fn next_or_err(&mut self) -> Result<Option<Entry<'a, R>>, NarError> {
use parser::{Node as N, ParseResult as PR};
use CurrentActivity as CA;
match self.current_activity {
CA::Finished => Ok(None),
CA::ParsingTopLevel => match parser::parse_next(&self.decoder.inner)? {
PR::Node(N::Regular { executable, size }) => {
Ok(Some(self.handle_parse_regular(None, executable, size)))
}
PR::Node(N::Symlink { target }) => {
self.current_activity = CA::Finished;
Ok(Some(Entry {
path: None,
content: Content::Symlink {
target: target.into(),
},
}))
}
PR::Node(N::Directory) => {
self.current_activity = CA::ParsingDirectoryEntries {
path: PathBuf::new(),
};
Ok(Some(Entry {
path: None,
content: Content::Directory,
}))
}
PR::DirectoryEntry(path, _) => Err(NarError::ParseError(format!(
"got unexpected directory entry at top-level: '{}'",
path.display()
))),
PR::ParenClose => {
self.current_activity = CA::Finished;
Ok(None)
}
},
CA::ParsingDirectoryEntries { path: ref dir_path } => {
let dir_path = dir_path.to_path_buf();
match parser::parse_next(&self.decoder.inner)? {
PR::Node(
node @ (N::Regular { .. } | N::Symlink { .. } | N::Directory),
) => Err(NarError::ParseError(format!(
"got unexpected {} node at while parsing directory '{}'",
node.variant_name(),
dir_path.display()
))),
PR::DirectoryEntry(path, node) => {
let path = dir_path.join(path);
match node {
N::Regular { executable, size } => Ok(Some(
self.handle_parse_regular(Some(path), executable, size),
)),
N::Symlink { target } => {
parser::parse_paren_close(&self.decoder.inner)?;
Ok(Some(Entry {
path: Some(path),
content: Content::Symlink {
target: target.into(),
},
}))
}
N::Directory => {
self.current_activity =
CA::ParsingDirectoryEntries { path: path.clone() };
Ok(Some(Entry {
path: Some(path),
content: Content::Directory,
}))
}
}
}
PR::ParenClose => {
if let Some(parent) = dir_path.parent() {
parser::parse_paren_close(&self.decoder.inner)?;
self.current_activity = CA::ParsingDirectoryEntries {
path: parent.to_path_buf(),
};
self.next_or_err()
} else {
self.current_activity = CA::Finished;
Ok(None)
}
}
}
}
CA::ParsingContent { next, ref path } => {
skip_bytes(&self.decoder.inner, next - self.decoder.inner.pos.get())?;
parser::parse_paren_close(&self.decoder.inner)?;
if let Some(parent) = path.parent() {
parser::parse_paren_close(&self.decoder.inner)?;
self.current_activity = CA::ParsingDirectoryEntries {
path: parent.to_path_buf(),
};
self.next_or_err()
} else {
self.current_activity = CA::Finished;
Ok(None)
}
}
}
}
}
impl<'a, R: Read> Iterator for Entries<'a, R> {
type Item = Result<Entry<'a, R>, NarError>;
fn next(&mut self) -> Option<Self::Item> {
match self.next_or_err() {
Err(err) => {
self.current_activity = CurrentActivity::Finished;
Some(Err(err))
}
Ok(None) => None,
Ok(Some(res)) => Some(Ok(res)),
}
}
}
impl<R> fmt::Debug for Content<'_, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Content::Directory => f.write_str("Directory"),
Content::Symlink { target } => {
f.debug_struct("Symlink").field("target", target).finish()
}
Content::File {
executable,
size,
offset,
data: _,
} => f
.debug_struct("File")
.field("executable", executable)
.field("size", size)
.field("offset", offset)
.finish(),
}
}
}
fn skip_bytes<R: Read>(
mut decoder_inner: &DecoderInner<R>,
mut bytes_to_skip: u64,
) -> Result<(), NarError> {
if bytes_to_skip > 0 {
use std::cmp;
while bytes_to_skip > 0 {
let mut buf = [0u8; 4096 * 8];
let n = cmp::min(bytes_to_skip, buf.len() as u64);
match decoder_inner
.read(&mut buf[..n as usize])
.map_err(Into::<NarError>::into)?
{
0 => {
return Err(NarError::ParseError(
"unexpected EOF during skip".to_string(),
));
}
n => {
bytes_to_skip -= n as u64;
}
}
}
}
Ok(())
}
impl<'a, R> Entry<'a, R> {
pub fn abs_path(&self) -> PathBuf {
let mut p = Path::new("/").to_path_buf();
if let Some(ref path) = self.path {
p.push(path);
}
p
}
}