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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use crate::core::{PackageId, SourceId};
use crate::ops;
use crate::sources::registry::download;
use crate::sources::registry::MaybeLock;
use crate::sources::registry::{LoadResponse, RegistryConfig, RegistryData};
use crate::util::errors::CargoResult;
use crate::util::{Config, Filesystem, IntoUrl, Progress, ProgressStyle};
use anyhow::Context;
use cargo_util::paths;
use curl::easy::{HttpVersion, List};
use curl::multi::{EasyHandle, Multi};
use log::{debug, trace};
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::str;
use std::task::Poll;
use std::time::Duration;
use url::Url;
const ETAG: &'static str = "ETag";
const LAST_MODIFIED: &'static str = "Last-Modified";
const UNKNOWN: &'static str = "Unknown";
pub struct HttpRegistry<'cfg> {
index_path: Filesystem,
cache_path: Filesystem,
source_id: SourceId,
config: &'cfg Config,
url: Url,
multi: Multi,
requested_update: bool,
downloads: Downloads<'cfg>,
multiplexing: bool,
fresh: HashSet<PathBuf>,
fetch_started: bool,
registry_config: Option<RegistryConfig>,
}
pub struct Downloads<'cfg> {
pending: HashMap<usize, (Download, EasyHandle)>,
pending_ids: HashMap<PathBuf, usize>,
results: HashMap<PathBuf, Result<CompletedDownload, curl::Error>>,
next: usize,
progress: RefCell<Option<Progress<'cfg>>>,
downloads_finished: usize,
}
struct Download {
token: usize,
path: PathBuf,
data: RefCell<Vec<u8>>,
index_version: RefCell<Option<String>>,
total: Cell<u64>,
current: Cell<u64>,
}
struct CompletedDownload {
response_code: u32,
data: Vec<u8>,
index_version: String,
}
impl<'cfg> HttpRegistry<'cfg> {
pub fn new(source_id: SourceId, config: &'cfg Config, name: &str) -> HttpRegistry<'cfg> {
let url = source_id
.url()
.to_string()
.trim_start_matches("sparse+")
.trim_end_matches('/')
.into_url()
.expect("a url with the protocol stripped should still be valid");
HttpRegistry {
index_path: config.registry_index_path().join(name),
cache_path: config.registry_cache_path().join(name),
source_id,
config,
url,
multi: Multi::new(),
multiplexing: false,
downloads: Downloads {
next: 0,
pending: HashMap::new(),
pending_ids: HashMap::new(),
results: HashMap::new(),
progress: RefCell::new(Some(Progress::with_style(
"Fetching",
ProgressStyle::Ratio,
config,
))),
downloads_finished: 0,
},
fresh: HashSet::new(),
requested_update: false,
fetch_started: false,
registry_config: None,
}
}
fn handle_http_header(buf: &[u8]) -> Option<(&str, &str)> {
if buf.is_empty() {
return None;
}
let buf = std::str::from_utf8(buf).ok()?.trim_end();
if buf.contains('\n') {
return None;
}
let (tag, value) = buf.split_once(':')?;
let value = value.trim();
Some((tag, value))
}
fn start_fetch(&mut self) -> CargoResult<()> {
if self.fetch_started {
return Ok(());
}
self.fetch_started = true;
self.multiplexing = self.config.http_config()?.multiplexing.unwrap_or(true);
self.multi
.pipelining(false, self.multiplexing)
.with_context(|| "failed to enable multiplexing/pipelining in curl")?;
self.multi.set_max_host_connections(2)?;
self.config
.shell()
.status("Updating", self.source_id.display_index())?;
Ok(())
}
fn handle_completed_downloads(&mut self) -> CargoResult<()> {
assert_eq!(
self.downloads.pending.len(),
self.downloads.pending_ids.len()
);
let pending = &mut self.downloads.pending;
self.multi.messages(|msg| {
let token = msg.token().expect("failed to read token");
let (_, handle) = &pending[&token];
let result = match msg.result_for(handle) {
Some(result) => result,
None => return,
};
let (download, mut handle) = pending.remove(&token).unwrap();
self.downloads.pending_ids.remove(&download.path).unwrap();
let result = match result {
Ok(()) => {
self.downloads.downloads_finished += 1;
match handle.response_code() {
Ok(code) => Ok(CompletedDownload {
response_code: code,
data: download.data.take(),
index_version: download
.index_version
.take()
.unwrap_or_else(|| UNKNOWN.to_string()),
}),
Err(e) => Err(e),
}
}
Err(e) => Err(e),
};
self.downloads.results.insert(download.path, result);
});
self.downloads.tick()?;
Ok(())
}
fn full_url(&self, path: &Path) -> String {
format!("{}/{}", self.url, path.display())
}
fn is_fresh(&self, path: &Path) -> bool {
if !self.requested_update {
trace!(
"using local {} as user did not request update",
path.display()
);
true
} else if self.config.cli_unstable().no_index_update {
trace!("using local {} in no_index_update mode", path.display());
true
} else if self.config.offline() {
trace!("using local {} in offline mode", path.display());
true
} else if self.fresh.contains(path) {
trace!("using local {} as it was already fetched", path.display());
true
} else {
debug!("checking freshness of {}", path.display());
false
}
}
}
impl<'cfg> RegistryData for HttpRegistry<'cfg> {
fn prepare(&self) -> CargoResult<()> {
Ok(())
}
fn index_path(&self) -> &Filesystem {
&self.index_path
}
fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path {
self.config.assert_package_cache_locked(path)
}
fn is_updated(&self) -> bool {
self.requested_update
}
fn load(
&mut self,
_root: &Path,
path: &Path,
index_version: Option<&str>,
) -> Poll<CargoResult<LoadResponse>> {
trace!("load: {}", path.display());
if let Some(_token) = self.downloads.pending_ids.get(path) {
debug!("dependency is still pending: {}", path.display());
return Poll::Pending;
}
if let Some(index_version) = index_version {
trace!(
"local cache of {} is available at version `{}`",
path.display(),
index_version
);
if self.is_fresh(path) {
return Poll::Ready(Ok(LoadResponse::CacheValid));
}
} else if self.fresh.contains(path) {
debug!(
"cache did not contain previously downloaded file {}",
path.display()
);
}
if let Some(result) = self.downloads.results.remove(path) {
let result =
result.with_context(|| format!("download of {} failed", path.display()))?;
debug!(
"index file downloaded with status code {}",
result.response_code
);
trace!("index file version: {}", result.index_version);
if !self.fresh.insert(path.to_path_buf()) {
debug!("downloaded the index file `{}` twice", path.display())
}
match result.response_code {
200 => {}
304 => {
if index_version.is_none() {
return Poll::Ready(Err(anyhow::anyhow!(
"server said not modified (HTTP 304) when no local cache exists"
)));
}
return Poll::Ready(Ok(LoadResponse::CacheValid));
}
404 | 410 | 451 => {
return Poll::Ready(Ok(LoadResponse::NotFound));
}
code => {
return Err(anyhow::anyhow!(
"server returned unexpected HTTP status code {} for {}\nbody: {}",
code,
self.full_url(path),
str::from_utf8(&result.data).unwrap_or("<invalid utf8>"),
))
.into();
}
}
return Poll::Ready(Ok(LoadResponse::Data {
raw_data: result.data,
index_version: Some(result.index_version),
}));
}
if self.config.offline() {
return Poll::Ready(Err(anyhow::anyhow!(
"can't download index file from '{}': you are in offline mode (--offline)",
self.url
)));
}
self.start_fetch()?;
if self.registry_config.is_none() && path != Path::new("config.json") {
match self.config()? {
Poll::Ready(_) => {}
Poll::Pending => return Poll::Pending,
}
}
let mut handle = ops::http_handle(self.config)?;
let full_url = self.full_url(path);
debug!("fetch {}", full_url);
handle.get(true)?;
handle.url(&full_url)?;
handle.follow_location(true)?;
if self.multiplexing {
handle.http_version(HttpVersion::V2)?;
} else {
handle.http_version(HttpVersion::V11)?;
}
handle.pipewait(true)?;
let mut headers = List::new();
if let Some(index_version) = index_version {
if let Some((key, value)) = index_version.split_once(':') {
match key {
ETAG => headers.append(&format!("If-None-Match: {}", value.trim()))?,
LAST_MODIFIED => {
headers.append(&format!("If-Modified-Since: {}", value.trim()))?
}
_ => debug!("unexpected index version: {}", index_version),
}
}
}
handle.http_headers(headers)?;
let token = self.downloads.next;
self.downloads.next += 1;
debug!("downloading {} as {}", path.display(), token);
assert_eq!(
self.downloads.pending_ids.insert(path.to_path_buf(), token),
None,
"path queued for download more than once"
);
handle.write_function(move |buf| {
trace!("{} - {} bytes of data", token, buf.len());
tls::with(|downloads| {
if let Some(downloads) = downloads {
downloads.pending[&token]
.0
.data
.borrow_mut()
.extend_from_slice(buf);
}
});
Ok(buf.len())
})?;
handle.progress(true)?;
handle.progress_function(move |dl_total, dl_cur, _, _| {
tls::with(|downloads| match downloads {
Some(d) => d.progress(token, dl_total as u64, dl_cur as u64),
None => false,
})
})?;
handle.header_function(move |buf| {
if let Some((tag, value)) = Self::handle_http_header(buf) {
let is_etag = tag.eq_ignore_ascii_case(ETAG);
let is_lm = tag.eq_ignore_ascii_case(LAST_MODIFIED);
if is_etag || is_lm {
tls::with(|downloads| {
if let Some(downloads) = downloads {
let mut index_version =
downloads.pending[&token].0.index_version.borrow_mut();
if is_etag {
*index_version = Some(format!("{}: {}", ETAG, value));
} else if index_version.is_none() && is_lm {
*index_version = Some(format!("{}: {}", LAST_MODIFIED, value));
};
}
})
}
}
true
})?;
let dl = Download {
token,
data: RefCell::new(Vec::new()),
path: path.to_path_buf(),
index_version: RefCell::new(None),
total: Cell::new(0),
current: Cell::new(0),
};
let mut handle = self.multi.add(handle)?;
handle.set_token(token)?;
self.downloads.pending.insert(dl.token, (dl, handle));
Poll::Pending
}
fn config(&mut self) -> Poll<CargoResult<Option<RegistryConfig>>> {
if self.registry_config.is_some() {
return Poll::Ready(Ok(self.registry_config.clone()));
}
debug!("loading config");
let index_path = self.config.assert_package_cache_locked(&self.index_path);
let config_json_path = index_path.join("config.json");
if self.is_fresh(Path::new("config.json")) {
match fs::read(&config_json_path) {
Ok(raw_data) => match serde_json::from_slice(&raw_data) {
Ok(json) => {
self.registry_config = Some(json);
return Poll::Ready(Ok(self.registry_config.clone()));
}
Err(e) => log::debug!("failed to decode cached config.json: {}", e),
},
Err(e) => log::debug!("failed to read config.json cache: {}", e),
}
}
match self.load(Path::new(""), Path::new("config.json"), None)? {
Poll::Ready(LoadResponse::Data {
raw_data,
index_version: _,
}) => {
trace!("config loaded");
self.registry_config = Some(serde_json::from_slice(&raw_data)?);
if paths::create_dir_all(&config_json_path.parent().unwrap()).is_ok() {
if let Err(e) = fs::write(&config_json_path, &raw_data) {
log::debug!("failed to write config.json cache: {}", e);
}
}
Poll::Ready(Ok(self.registry_config.clone()))
}
Poll::Ready(LoadResponse::NotFound) => {
Poll::Ready(Err(anyhow::anyhow!("config.json not found in registry")))
}
Poll::Ready(LoadResponse::CacheValid) => {
panic!("config.json is not stored in the index cache")
}
Poll::Pending => Poll::Pending,
}
}
fn invalidate_cache(&mut self) {
debug!("invalidated index cache");
self.requested_update = true;
}
fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> {
let registry_config = loop {
match self.config()? {
Poll::Pending => self.block_until_ready()?,
Poll::Ready(cfg) => break cfg.unwrap(),
}
};
download::download(
&self.cache_path,
&self.config,
pkg,
checksum,
registry_config,
)
}
fn finish_download(
&mut self,
pkg: PackageId,
checksum: &str,
data: &[u8],
) -> CargoResult<File> {
download::finish_download(&self.cache_path, &self.config, pkg, checksum, data)
}
fn is_crate_downloaded(&self, pkg: PackageId) -> bool {
download::is_crate_downloaded(&self.cache_path, &self.config, pkg)
}
fn block_until_ready(&mut self) -> CargoResult<()> {
let initial_pending_count = self.downloads.pending.len();
trace!(
"block_until_ready: {} transfers pending",
initial_pending_count
);
loop {
self.handle_completed_downloads()?;
let remaining_in_multi = tls::set(&self.downloads, || {
self.multi
.perform()
.with_context(|| "failed to perform http requests")
})?;
trace!("{} transfers remaining", remaining_in_multi);
if remaining_in_multi == 0 {
return Ok(());
}
let timeout = self
.multi
.get_timeout()?
.unwrap_or_else(|| Duration::new(5, 0));
self.multi
.wait(&mut [], timeout)
.with_context(|| "failed to wait on curl `Multi`")?;
}
}
}
impl<'cfg> Downloads<'cfg> {
fn progress(&self, token: usize, total: u64, cur: u64) -> bool {
let dl = &self.pending[&token].0;
dl.total.set(total);
dl.current.set(cur);
true
}
fn tick(&self) -> CargoResult<()> {
let mut progress = self.progress.borrow_mut();
let progress = progress.as_mut().unwrap();
progress.tick(
self.downloads_finished,
self.downloads_finished + self.pending.len(),
"",
)
}
}
mod tls {
use super::Downloads;
use std::cell::Cell;
thread_local!(static PTR: Cell<usize> = Cell::new(0));
pub(crate) fn with<R>(f: impl FnOnce(Option<&Downloads<'_>>) -> R) -> R {
let ptr = PTR.with(|p| p.get());
if ptr == 0 {
f(None)
} else {
let ptr = unsafe { &*(ptr as *const Downloads<'_>) };
f(Some(ptr))
}
}
pub(crate) fn set<R>(dl: &Downloads<'_>, f: impl FnOnce() -> R) -> R {
struct Reset<'a, T: Copy>(&'a Cell<T>, T);
impl<'a, T: Copy> Drop for Reset<'a, T> {
fn drop(&mut self) {
self.0.set(self.1);
}
}
PTR.with(|p| {
let _reset = Reset(p, p.get());
p.set(dl as *const Downloads<'_> as usize);
f()
})
}
}