Debian Codegraph @

third_party/rust/breakpad-symbols/src/http.rs

raw
1 //! Contains HTTP symbol retrieval specific functionality
2
3 use crate::*;
4 use reqwest::{redirect, Client, Url};
5 use std::io::{self, Write};
6 use std::path::Path;
7 use std::str::FromStr;
8 use std::time::Duration;
9 use tempfile::NamedTempFile;
10 use tracing::{debug, trace, warn};
11
12 /// A key that uniquely identifies a File associated with a module
13 type FileKey = (ModuleKey, FileKind);
14
15 /// An implementation of `SymbolSupplier` that loads Breakpad text-format
16 /// symbols from HTTP URLs.
17 ///
18 /// See [`crate::breakpad_sym_lookup`] for details on how paths are searched.
19 pub struct HttpSymbolSupplier {
20 /// File paths that are known to be in the cache
21 #[allow(clippy::type_complexity)]
22 cached_file_paths: CacheMap<FileKey, CachedAsyncResult<(PathBuf, Option<Url>), FileError>>,
23 /// HTTP Client to use for fetching symbols.
24 client: Client,
25 /// URLs to search for symbols.
26 urls: Vec<Url>,
27 /// A `SimpleSymbolSupplier` to use for local symbol paths.
28 local: SimpleSymbolSupplier,
29 /// A path at which to cache downloaded symbols.
30 ///
31 /// We recommend using a subdirectory of `std::env::temp_dir()`, as this
32 /// will be your OS's intended location for tempory files. This should
33 /// give you free garbage collection of the cache while still allowing it
34 /// to function between runs.
35 cache: PathBuf,
36 /// A path to a temporary location where downloaded symbols can be written
37 /// before being atomically swapped into the cache.
38 ///
39 /// We recommend using `std::env::temp_dir()`, as this will be your OS's
40 /// intended location for temporary files.
41 tmp: PathBuf,
42 }
43
44 impl HttpSymbolSupplier {
45 /// Create a new `HttpSymbolSupplier`.
46 ///
47 /// Symbols will be searched for in each of `local_paths` and `cache` first,
48 /// then via HTTP at each of `urls`. If a symbol file is found via HTTP it
49 /// will be saved under `cache`.
50 pub fn new(
51 urls: Vec<String>,
52 cache: PathBuf,
53 tmp: PathBuf,
54 mut local_paths: Vec<PathBuf>,
55 timeout: Duration,
56 ) -> HttpSymbolSupplier {
57 let client = Client::builder().timeout(timeout).build().unwrap();
58 let urls = urls
59 .into_iter()
60 .filter_map(|mut u| {
61 if !u.ends_with('/') {
62 u.push('/');
63 }
64 Url::parse(&u).ok()
65 })
66 .collect();
67 local_paths.push(cache.clone());
68 let local = SimpleSymbolSupplier::new(local_paths);
69 let cached_file_paths = Default::default();
70 HttpSymbolSupplier {
71 client,
72 cached_file_paths,
73 urls,
74 local,
75 cache,
76 tmp,
77 }
78 }
79
80 #[tracing::instrument(level = "trace", skip(self, module), fields(module = crate::basename(&module.code_file())))]
81 pub async fn locate_file_internal(
82 &self,
83 module: &(dyn Module + Sync),
84 file_kind: FileKind,
85 ) -> Result<(PathBuf, Option<Url>), FileError> {
86 self.cached_file_paths
87 .cache_default(file_key(module, file_kind))
88 .get(|| async {
89 // First look for the file in the cache
90 if let Ok(path) = self.local.locate_file(module, file_kind).await {
91 return Ok((path, None));
92 }
93
94 // Then try to download the file
95 // FIXME: if we try to parallelize this with `join` then if we have multiple hits
96 // we'll end up downloading all of them at once and having them race to write into
97 // the cache... is that ok? Maybe? Since only one will ever win the swap, and it's
98 // unlikely to get multiple hits... this might actually be ok!
99 if let Some(lookup) = lookup(module, file_kind) {
100 for url in &self.urls {
101 let fetch =
102 fetch_lookup(&self.client, url, &lookup, &self.cache, &self.tmp).await;
103
104 if let Ok((path, url)) = fetch {
105 return Ok((path, url));
106 }
107 }
108
109 // If we're allowed to look for mozilla's special CAB paths, do that
110 if cfg!(feature = "mozilla_cab_symbols") {
111 for url in &self.urls {
112 let fetch = fetch_cab_lookup(
113 &self.client,
114 url,
115 &lookup,
116 &self.cache,
117 &self.tmp,
118 )
119 .await;
120
121 if let Ok((path, url)) = fetch {
122 return Ok((path, url));
123 }
124 }
125 }
126 }
127 Err(FileError::NotFound)
128 })
129 .await
130 .as_ref()
131 .clone()
132 }
133 }
134
135 fn file_key(module: &(dyn Module + Sync), file_kind: FileKind) -> FileKey {
136 (module_key(module), file_kind)
137 }
138
139 fn create_cache_file(tmp_path: &Path, final_path: &Path) -> io::Result<NamedTempFile> {
140 // Use tempfile to save things to our cache to ensure proper
141 // atomicity of writes. We may want multiple instances of rust-minidump
142 // to be sharing a cache, and we don't want one instance to see another
143 // instance's partially written results.
144 //
145 // tempfile is designed explicitly for this purpose, and will handle all
146 // the platform-specific details and do its best to cleanup if things
147 // crash.
148
149 // First ensure that the target directory in the cache exists
150 let base = final_path.parent().ok_or_else(|| {
151 io::Error::new(
152 io::ErrorKind::Other,
153 format!("Bad cache path: {final_path:?}"),
154 )
155 })?;
156 fs::create_dir_all(base)?;
157
158 NamedTempFile::new_in(tmp_path)
159 }
160
161 fn commit_cache_file(mut temp: NamedTempFile, final_path: &Path, url: &Url) -> io::Result<()> {
162 // Append any extra metadata we also want to be cached as "INFO" lines,
163 // because this is an established format that parsers will ignore the
164 // contents of by default.
165
166 // INFO URL allows us to properly report the url we retrieved a symbol file
167 // from, even when the file is loaded from our on-disk cache.
168 let cache_metadata = format!("INFO URL {url}\n");
169 temp.write_all(cache_metadata.as_bytes())?;
170
171 // TODO: don't do this
172 if final_path.exists() {
173 fs::remove_file(final_path)?;
174 }
175
176 // If another process already wrote this entry, prefer their value to
177 // avoid needless file system churn.
178 temp.persist_noclobber(final_path)?;
179
180 Ok(())
181 }
182
183 /// Perform a code_file/code_identifier lookup for a specific symbol server.
184 async fn individual_lookup_debug_info_by_code_info(
185 base_url: &Url,
186 lookup_path: &str,
187 ) -> Option<DebugInfoResult> {
188 let url = base_url.join(lookup_path).ok()?;
189
190 debug!("Trying code file / code identifier lookup: {}", url);
191
192 // This should not follow redirects--we want the next url if there is one
193 let no_redirects_client = Client::builder()
194 .redirect(redirect::Policy::none())
195 .build()
196 .ok()?;
197
198 let response = no_redirects_client.get(url.clone()).send().await;
199 if let Ok(res) = response {
200 let res_status = res.status();
201 if res_status == reqwest::StatusCode::FOUND
202 || res_status == reqwest::StatusCode::MOVED_PERMANENTLY
203 {
204 let location_header = res.headers().get("Location")?;
205 let mut new_url = location_header.to_str().ok()?;
206 if new_url.starts_with('/') {
207 new_url = new_url.strip_prefix('/').unwrap_or(new_url);
208 }
209
210 // new_url looks like some/path/stuff/xul.pdb/somedebugid/xul.sym and we want the debug
211 // file and debug id portions which are at fixed indexes from the end
212 let mut parts = new_url.rsplit('/');
213 let debug_identifier_part = parts.nth(1)?;
214 let debug_identifier = DebugId::from_str(debug_identifier_part).ok()?;
215 let debug_file_part = parts.next()?;
216 let debug_file = String::from(debug_file_part);
217
218 debug!("Found debug info {} {}", debug_file, debug_identifier);
219 return Some(DebugInfoResult {
220 debug_file,
221 debug_identifier,
222 });
223 }
224 }
225
226 None
227 }
228
229 /// Given a vector of symbol urls and a module with a code_file and code_identifier,
230 /// this tries to request a symbol file using the code file and code identifier.
231 ///
232 /// `<code file>/<code identifier>/<code file>.sym`
233 ///
234 /// If the symbol server returns an HTTP 302 redirect, the Location header will
235 /// have the correct download API url with the debug file and debug identifier.
236 ///
237 /// This is supported by tecken
238 ///
239 /// This returns a DebugInfoResult with the new debug file and debug identifier
240 /// or None.
241 async fn lookup_debug_info_by_code_info(
242 symbol_urls: &Vec<Url>,
243 module: &(dyn Module + Sync),
244 ) -> Option<DebugInfoResult> {
245 let lookup_path = code_info_breakpad_sym_lookup(module)?;
246
247 for base_url in symbol_urls {
248 if let Some(result) =
249 individual_lookup_debug_info_by_code_info(base_url, &lookup_path).await
250 {
251 return Some(result);
252 }
253 }
254
255 debug!(
256 "No debug file / debug id found with lookup path {}.",
257 lookup_path
258 );
259
260 None
261 }
262
263 /// Fetch a symbol file from the URL made by combining `base_url` and `rel_path` using `client`,
264 /// save the file contents under `cache` + `rel_path` and also return them.
265 async fn fetch_symbol_file(
266 client: &Client,
267 base_url: &Url,
268 module: &(dyn Module + Sync),
269 cache: &Path,
270 tmp: &Path,
271 ) -> Result<SymbolFile, SymbolError> {
272 trace!("HttpSymbolSupplier trying symbol server {}", base_url);
273 // This function is a bit of a complicated mess because we want to write
274 // the input to our symbol cache, but we're a streaming parser. So we
275 // use the bare SymbolFile::parse to get access to the contents of
276 // the input stream as it's downloaded+parsed to write it to disk.
277 //
278 // Note that caching is strictly "optional" because it's more important
279 // to parse the symbols. So if at any point the caching i/o fails, we just
280 // give up on caching but let the parse+download continue.
281
282 // First try to GET the file from a server
283 let sym_lookup = breakpad_sym_lookup(module).ok_or(SymbolError::MissingDebugFileOrId)?;
284 let mut url = base_url
285 .join(&sym_lookup.server_rel)
286 .map_err(|_| SymbolError::NotFound)?;
287 let code_id = module.code_identifier().unwrap_or_default();
288 url.query_pairs_mut()
289 .append_pair("code_file", crate::basename(&module.code_file()))
290 .append_pair("code_id", code_id.as_str());
291 debug!("Trying {}", url);
292 let res = client
293 .get(url.clone())
294 .send()
295 .await
296 .and_then(|res| res.error_for_status())
297 .map_err(|_| SymbolError::NotFound)?;
298
299 // Now try to create the temp cache file (not yet in the cache)
300 let final_cache_path = cache.join(sym_lookup.cache_rel);
301 let mut temp = create_cache_file(tmp, &final_cache_path)
302 .map_err(|e| {
303 warn!("Failed to save symbol file in local disk cache: {}", e);
304 })
305 .ok();
306
307 // Now stream parse the file as it downloads.
308 let mut symbol_file = SymbolFile::parse_async(res, |data| {
309 // While we're downloading+parsing, save this data to the the disk cache too
310 if let Some(file) = temp.as_mut() {
311 if let Err(e) = file.write_all(data) {
312 // Give up on caching this.
313 warn!("Failed to save symbol file in local disk cache: {}", e);
314 temp = None;
315 }
316 }
317 })
318 .await?;
319 // Make note of what URL this symbol file was downloaded from.
320 symbol_file.url = Some(url.to_string());
321
322 // Try to finish the cache file and atomically swap it into the cache.
323 if let Some(temp) = temp {
324 let _ = commit_cache_file(temp, &final_cache_path, &url).map_err(|e| {
325 warn!("Failed to save symbol file in local disk cache: {}", e);
326 });
327 }
328
329 Ok(symbol_file)
330 }
331
332 /// Like fetch_symbol_file but instead of parsing the file live, we just download it opaquely based
333 /// on the given Lookup.
334 ///
335 /// The returned value is the path to the downloaded file and the url it was downloaded from.
336 async fn fetch_lookup(
337 client: &Client,
338 base_url: &Url,
339 lookup: &FileLookup,
340 cache: &Path,
341 tmp: &Path,
342 ) -> Result<(PathBuf, Option<Url>), SymbolError> {
343 // First try to GET the file from a server
344 let url = base_url
345 .join(&lookup.server_rel)
346 .map_err(|_| SymbolError::NotFound)?;
347 debug!("Trying {}", url);
348 let mut res = client
349 .get(url.clone())
350 .send()
351 .await
352 .and_then(|res| res.error_for_status())
353 .map_err(|_| SymbolError::NotFound)?;
354
355 // Now try to create the temp cache file (not yet in the cache)
356 let final_cache_path = cache.join(&lookup.cache_rel);
357 let mut temp = create_cache_file(tmp, &final_cache_path)?;
358
359 // Now stream the contents to our file
360 while let Some(chunk) = res
361 .chunk()
362 .await
363 .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?
364 {
365 temp.write_all(&chunk[..])?;
366 }
367
368 // And swap it into the cache
369 temp.persist_noclobber(&final_cache_path)
370 .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
371
372 trace!("symbols: fetched native binary: {}", lookup.cache_rel);
373
374 Ok((final_cache_path, Some(url)))
375 }
376
377 #[cfg(feature = "mozilla_cab_symbols")]
378 async fn fetch_cab_lookup(
379 client: &Client,
380 base_url: &Url,
381 lookup: &FileLookup,
382 cache: &Path,
383 tmp: &Path,
384 ) -> Result<(PathBuf, Option<Url>), FileError> {
385 let cab_lookup = moz_lookup(lookup.clone());
386 // First try to GET the file from a server
387 let url = base_url
388 .join(&cab_lookup.server_rel)
389 .map_err(|_| FileError::NotFound)?;
390 debug!("Trying {}", url);
391 let res = client
392 .get(url.clone())
393 .send()
394 .await
395 .and_then(|res| res.error_for_status())
396 .map_err(|_| FileError::NotFound)?;
397
398 let cab_bytes = res.bytes().await.map_err(|_| FileError::NotFound)?;
399 let final_cache_path =
400 unpack_cabinet_file(&cab_bytes, lookup, cache, tmp).map_err(|_| FileError::NotFound)?;
401
402 trace!("symbols: fetched native binary: {}", lookup.cache_rel);
403
404 Ok((final_cache_path, Some(url)))
405 }
406
407 #[cfg(not(feature = "mozilla_cab_symbols"))]
408 async fn fetch_cab_lookup(
409 _client: &Client,
410 _base_url: &Url,
411 _lookup: &FileLookup,
412 _cache: &Path,
413 _tmp: &Path,
414 ) -> Result<(PathBuf, Option<Url>), FileError> {
415 Err(FileError::NotFound)
416 }
417
418 #[cfg(feature = "mozilla_cab_symbols")]
419 pub fn unpack_cabinet_file(
420 buf: &[u8],
421 lookup: &FileLookup,
422 cache: &Path,
423 tmp: &Path,
424 ) -> Result<PathBuf, std::io::Error> {
425 trace!("symbols: unpacking CAB file: {}", lookup.cache_rel);
426 // try to find a file in a cabinet archive and unpack it to the destination
427 use cab::Cabinet;
428 use std::io::Cursor;
429 fn get_cabinet_file(
430 cab: &Cabinet<Cursor<&[u8]>>,
431 file_name: &str,
432 ) -> Result<String, std::io::Error> {
433 for folder in cab.folder_entries() {
434 for file in folder.file_entries() {
435 let cab_file_name = file.name();
436 if cab_file_name.ends_with(file_name) {
437 return Ok(cab_file_name.to_string());
438 }
439 }
440 }
441 Err(std::io::Error::from(std::io::ErrorKind::NotFound))
442 }
443 let final_cache_path = cache.join(&lookup.cache_rel);
444
445 let cursor = Cursor::new(buf);
446 let mut cab = Cabinet::new(cursor)?;
447 let file_name = final_cache_path.file_name().unwrap().to_string_lossy();
448 let cab_file = get_cabinet_file(&cab, &file_name)?;
449 let mut reader = cab.read_file(&cab_file)?;
450
451 // Now try to create the temp cache file (not yet in the cache)
452 let mut temp = create_cache_file(tmp, &final_cache_path)?;
453 std::io::copy(&mut reader, &mut temp)?;
454
455 // And swap it into the cache
456 temp.persist_noclobber(&final_cache_path)
457 .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
458
459 Ok(final_cache_path)
460 }
461
462 /// Try to lookup native binaries in the cache and by querying the symbol server
463
464 #[async_trait]
465 impl SymbolSupplier for HttpSymbolSupplier {
466 #[tracing::instrument(name = "symbols", level = "trace", skip_all, fields(file = crate::basename(&module.code_file())))]
467 async fn locate_symbols(
468 &self,
469 module: &(dyn Module + Sync),
470 ) -> Result<LocateSymbolsResult, SymbolError> {
471 // If we don't have a debug_file or debug_identifier, then try to get it
472 // from a symbol server.
473 let mut debug_file = module.debug_file().map(|name| name.into_owned());
474 let mut debug_id = module.debug_identifier();
475 let missing_debug_info = debug_file.is_none() || debug_id.is_none();
476
477 let extra_debug_info;
478
479 if missing_debug_info {
480 debug!("Missing debug file or debug identifier--trying lookup with code info");
481 extra_debug_info = lookup_debug_info_by_code_info(&self.urls, module).await;
482 if let Some(debug_info_result) = &extra_debug_info {
483 debug_file = Some(debug_info_result.debug_file.clone());
484 debug_id = Some(debug_info_result.debug_identifier);
485 }
486 } else {
487 extra_debug_info = None;
488 }
489
490 // Build a minimal module for lookups with the debug file and debug
491 // identifier we need to use
492 let lookup_module = SimpleModule::from_basic_info(
493 debug_file,
494 debug_id,
495 Some(module.code_file().into_owned()),
496 module.code_identifier(),
497 );
498
499 // First: try local paths for sym files
500 let local_result = self.local.locate_symbols(&lookup_module).await;
501 if !matches!(local_result, Err(SymbolError::NotFound)) {
502 // Everything but NotFound prevents cascading
503 return local_result.map(|r| LocateSymbolsResult {
504 symbols: r.symbols,
505 extra_debug_info: r.extra_debug_info.or(extra_debug_info),
506 });
507 }
508 trace!("HttpSymbolSupplier search (SimpleSymbolSupplier found nothing)");
509
510 // Second: try to directly download sym files
511 for url in &self.urls {
512 // First, try to get a breakpad .sym file from the symbol server
513 let sym =
514 fetch_symbol_file(&self.client, url, &lookup_module, &self.cache, &self.tmp).await;
515 match sym {
516 Ok(symbols) => {
517 trace!("HttpSymbolSupplier parsed file!");
518 return Ok(LocateSymbolsResult {
519 symbols,
520 extra_debug_info,
521 });
522 }
523 Err(e) => {
524 trace!("HttpSymbolSupplier failed: {}", e);
525 }
526 }
527 }
528
529 // If we get this far, we have failed to find anything
530 Err(SymbolError::NotFound)
531 }
532
533 async fn locate_file(
534 &self,
535 module: &(dyn Module + Sync),
536 file_kind: FileKind,
537 ) -> Result<PathBuf, FileError> {
538 self.locate_file_internal(module, file_kind)
539 .await
540 .map(|(path, _url)| path)
541 }
542 }