1#![allow(non_snake_case, dead_code, unsafe_op_in_unsafe_fn)]
7
8use std::path::{Path, PathBuf};
9use std::sync::{Mutex, OnceLock};
10
11pub use libloading::Library;
12
13struct LoadedLibrary {
14 handle: Library,
15 path: PathBuf,
16}
17
18static LIB: OnceLock<LoadedLibrary> = OnceLock::new();
19static LOAD_LOCK: Mutex<()> = Mutex::new(());
21
22pub fn loaded_library_path() -> Option<&'static Path> {
24 LIB.get().map(|lib| lib.path.as_path())
25}
26
27fn candidate(path: &Path) -> Option<PathBuf> {
28 if path.is_dir() {
29 find_platform_library(path)
30 } else {
31 Some(path.to_owned())
32 }
33}
34
35pub fn conflicting_library(requested: &Path) -> Option<&'static Path> {
38 let loaded = LIB.get()?;
39 let matches = candidate(requested).is_some_and(|path| {
40 if path.file_name() == Some(path.as_os_str()) {
41 return matches_search_name(&path, loaded);
42 }
43 path == loaded.path || same_file::is_same_file(&path, &loaded.path).unwrap_or(false)
44 });
45 (!matches).then_some(loaded.path.as_path())
46}
47
48#[cfg(windows)]
49fn matches_search_name(name: &Path, loaded: &LoadedLibrary) -> bool {
50 libloading::os::windows::Library::open_already_loaded(name)
51 .is_ok_and(|module| same_module(&module.into(), &loaded.handle))
52}
53
54#[cfg(any(
55 target_os = "linux",
56 target_os = "android",
57 target_vendor = "apple",
58 target_os = "freebsd"
59))]
60fn matches_search_name(name: &Path, loaded: &LoadedLibrary) -> bool {
61 unsafe { libloading::os::unix::Library::open(Some(name), libc::RTLD_NOLOAD | libc::RTLD_LAZY) }
63 .is_ok_and(|module| same_module(&module.into(), &loaded.handle))
64}
65
66#[cfg(not(any(
67 windows,
68 target_os = "linux",
69 target_os = "android",
70 target_vendor = "apple",
71 target_os = "freebsd"
72)))]
73fn matches_search_name(name: &Path, loaded: &LoadedLibrary) -> bool {
74 loaded.path.file_name() == Some(name.as_os_str())
75}
76
77fn same_module(a: &Library, b: &Library) -> bool {
78 unsafe {
80 let (Ok(a), Ok(b)) = (
81 a.get::<*const ()>(b"Cronet_Engine_Create"),
82 b.get::<*const ()>(b"Cronet_Engine_Create"),
83 ) else {
84 return false;
85 };
86 *a == *b
87 }
88}
89
90#[cfg(unix)]
91fn module_path(symbol: *const ()) -> std::io::Result<PathBuf> {
92 use std::os::unix::ffi::OsStrExt;
93 let mut info = std::mem::MaybeUninit::<libc::Dl_info>::uninit();
94 unsafe {
96 if libc::dladdr(symbol.cast(), info.as_mut_ptr()) == 0 {
97 return Err(std::io::Error::other(
98 "dladdr could not locate the Cronet module",
99 ));
100 }
101 let name = info.assume_init().dli_fname;
102 if name.is_null() {
103 return Err(std::io::Error::other(
104 "dladdr returned no Cronet module path",
105 ));
106 }
107 Ok(PathBuf::from(std::ffi::OsStr::from_bytes(
108 std::ffi::CStr::from_ptr(name).to_bytes(),
109 )))
110 }
111}
112
113#[cfg(windows)]
114fn module_path(symbol: *const ()) -> std::io::Result<PathBuf> {
115 use std::os::windows::ffi::OsStringExt;
116 use windows_sys::Win32::System::LibraryLoader::{
117 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
118 GetModuleFileNameW, GetModuleHandleExW,
119 };
120 let mut module = 0;
121 let mut name = vec![0u16; 32768];
122 unsafe {
124 if GetModuleHandleExW(
125 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
126 symbol.cast(),
127 &mut module,
128 ) == 0
129 {
130 return Err(std::io::Error::last_os_error());
131 }
132 let len = GetModuleFileNameW(module, name.as_mut_ptr(), name.len() as u32) as usize;
133 if len == 0 || len == name.len() {
134 return Err(std::io::Error::last_os_error());
135 }
136 Ok(std::ffi::OsString::from_wide(&name[..len]).into())
137 }
138}
139
140pub unsafe fn load_library(path: &str) -> Result<(), Box<dyn std::error::Error>> {
158 let _guard = LOAD_LOCK.lock().unwrap_or_else(|err| err.into_inner());
159 if LIB.get().is_some() {
160 return Err("library already loaded".into());
161 }
162 let resolved = candidate(Path::new(path)).ok_or_else(|| {
163 format!("no loadable cronet library for this platform found in directory {path:?}")
164 })?;
165 let lib = Library::new(&resolved)?;
166 let create = lib.get::<unsafe extern "C" fn() -> super::RawEngine>(b"Cronet_Engine_Create")?;
168 let destroy = lib.get::<unsafe extern "C" fn(super::RawEngine)>(b"Cronet_Engine_Destroy")?;
169 let version = lib.get::<unsafe extern "C" fn(super::RawEngine) -> *const std::ffi::c_char>(
170 b"Cronet_Engine_GetVersionString",
171 )?;
172 let engine = create();
173 if engine.0 == 0 {
174 return Err("Cronet version probe could not create an engine".into());
175 }
176 let ptr = version(engine);
177 let actual = if ptr.is_null() {
178 String::from("<unknown>")
179 } else {
180 std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned()
181 };
182 destroy(engine);
183 if actual != "154.0.8037.49" {
184 return Err(
185 format!("incompatible Cronet {actual}, expected SagerNet 154.0.8037.49").into(),
186 );
187 }
188 let path = module_path(*create as *const ())?;
189 let path = path.canonicalize().unwrap_or(path);
190 LIB.set(LoadedLibrary { handle: lib, path })
191 .map_err(|_| "library already loaded".into())
192}
193
194pub fn find_platform_library(dir: &Path) -> Option<PathBuf> {
206 let mut candidates: Vec<(i32, PathBuf)> = Vec::new();
207 collect_candidates(dir, MAX_SEARCH_DEPTH, &mut candidates);
208 candidates.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
210 candidates.into_iter().next().map(|(_, path)| path)
211}
212
213const MAX_SEARCH_DEPTH: usize = 8;
215
216fn collect_candidates(dir: &Path, depth: usize, out: &mut Vec<(i32, PathBuf)>) {
221 let entries = match std::fs::read_dir(dir) {
222 Ok(entries) => entries,
223 Err(_) => return,
224 };
225 for entry in entries.flatten() {
226 let Ok(file_type) = entry.file_type() else {
227 continue;
228 };
229 let path = entry.path();
230 if file_type.is_dir() {
234 if depth > 0 {
235 collect_candidates(&path, depth - 1, out);
236 }
237 } else {
238 let name = entry.file_name();
239 if let Some(score) = rank_library(&name.to_string_lossy()) {
240 out.push((score, path));
241 }
242 }
243 }
244}
245
246fn choose_library<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<String> {
249 let mut scored: Vec<(i32, String)> = names
250 .into_iter()
251 .filter_map(|n| rank_library(n).map(|s| (s, n.to_string())))
252 .collect();
253 scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
255 scored.into_iter().next().map(|(_, name)| name)
256}
257
258fn rank_library(name: &str) -> Option<i32> {
261 let lower = name.to_ascii_lowercase();
262 if !is_loadable_lib(&lower) {
263 return None;
264 }
265
266 let mut score = 0;
267 if lower.contains("cronet") {
268 score += 8;
269 }
270 score += arch_bonus(&lower);
271 score += os_bonus(&lower);
272 if lower.contains("simulator") {
274 score -= 4;
275 }
276 let canonical = format!(
278 "{}cronet{}",
279 std::env::consts::DLL_PREFIX,
280 std::env::consts::DLL_SUFFIX
281 )
282 .to_ascii_lowercase();
283 if lower == canonical {
284 score += 2;
285 }
286 Some(score)
287}
288
289fn is_loadable_lib(name: &str) -> bool {
292 let suffix = std::env::consts::DLL_SUFFIX; name.ends_with(suffix) || name.contains(&format!("{suffix}."))
294}
295
296fn arch_bonus(lower: &str) -> i32 {
298 let positives: &[&str] = match std::env::consts::ARCH {
299 "x86_64" => &["amd64", "x86_64", "x64"],
300 "x86" => &["386", "i686", "i386", "x86"],
301 "aarch64" => &["arm64", "aarch64"],
302 "arm" => &["armv7", "armhf", "armeabi", "arm"],
303 "loongarch64" => &["loong64", "loongarch64"],
304 "riscv64" => &["riscv64"],
305 _ => &[],
306 };
307 let mut bonus = 0;
308 if positives.iter().any(|t| lower.contains(t)) {
309 bonus += 4;
310 }
311 match std::env::consts::ARCH {
313 "x86" if lower.contains("x86_64") || lower.contains("amd64") || lower.contains("x64") => {
314 bonus -= 6;
315 }
316 "arm" if lower.contains("arm64") || lower.contains("aarch64") => {
317 bonus -= 6;
318 }
319 _ => {}
320 }
321 bonus
322}
323
324fn os_bonus(lower: &str) -> i32 {
326 let (mine, others): (&[&str], &[&str]) = match std::env::consts::OS {
327 "windows" => (&["windows", "win"], &["linux", "android", "darwin", "macos", "ios"]),
328 "linux" => (&["linux"], &["windows", "android", "darwin", "macos", "ios"]),
329 "android" => (&["android"], &["windows", "darwin", "macos", "ios"]),
330 "macos" => (&["darwin", "macos", "osx"], &["windows", "android", "ios"]),
331 "ios" => (&["ios"], &["windows", "android", "linux"]),
332 _ => (&[], &[]),
333 };
334 let mut bonus = 0;
335 if mine.iter().any(|t| lower.contains(t)) {
336 bonus += 2;
337 }
338 if others.iter().any(|t| lower.contains(t)) {
339 bonus -= 3;
340 }
341 bonus
342}
343
344macro_rules! ffi_call {
349 ($name:literal, $sig:ty, $($arg:expr),* $(,)?) => {{
350 let lib = LIB.get().expect("libcronet not loaded; call load_library() first");
351 let func: libloading::Symbol<$sig> = lib.handle.get($name).unwrap_or_else(|e| {
352 panic!("symbol {} not found: {}", String::from_utf8_lossy($name), e)
353 });
354 func($($arg),*)
355 }};
356}
357
358pub unsafe fn Cronet_Engine_Create() -> super::RawEngine {
363 ffi_call!(b"Cronet_Engine_Create", unsafe extern "C" fn() -> super::RawEngine,)
364}
365
366pub unsafe fn Cronet_Engine_Destroy(engine: super::RawEngine) {
367 ffi_call!(b"Cronet_Engine_Destroy", unsafe extern "C" fn(super::RawEngine), engine)
368}
369
370pub unsafe fn Cronet_Engine_StartWithParams(
371 engine: super::RawEngine, params: super::RawEngineParams,
372) -> i32 {
373 ffi_call!(b"Cronet_Engine_StartWithParams", unsafe extern "C" fn(super::RawEngine, super::RawEngineParams) -> i32, engine, params)
374}
375
376pub unsafe fn Cronet_Engine_Shutdown(engine: super::RawEngine) -> i32 {
377 ffi_call!(b"Cronet_Engine_Shutdown", unsafe extern "C" fn(super::RawEngine) -> i32, engine)
378}
379
380pub unsafe fn Cronet_Engine_GetVersionString(engine: super::RawEngine) -> *const std::os::raw::c_char {
381 ffi_call!(b"Cronet_Engine_GetVersionString", unsafe extern "C" fn(super::RawEngine) -> *const std::os::raw::c_char, engine)
382}
383
384pub unsafe fn Cronet_Engine_GetDefaultUserAgent(engine: super::RawEngine) -> *const std::os::raw::c_char {
385 ffi_call!(b"Cronet_Engine_GetDefaultUserAgent", unsafe extern "C" fn(super::RawEngine) -> *const std::os::raw::c_char, engine)
386}
387
388pub unsafe fn Cronet_Engine_GetStreamEngine(engine: super::RawEngine) -> super::RawStreamEngine {
389 ffi_call!(b"Cronet_Engine_GetStreamEngine", unsafe extern "C" fn(super::RawEngine) -> super::RawStreamEngine, engine)
390}
391
392pub unsafe fn Cronet_Engine_CloseAllConnections(engine: super::RawEngine) {
393 ffi_call!(b"Cronet_Engine_CloseAllConnections", unsafe extern "C" fn(super::RawEngine), engine)
394}
395
396pub unsafe fn Cronet_CreateCertVerifierWithRootCerts(
397 pem: *const std::os::raw::c_char,
398) -> super::RawCertVerifier {
399 ffi_call!(b"Cronet_CreateCertVerifierWithRootCerts", unsafe extern "C" fn(*const std::os::raw::c_char) -> super::RawCertVerifier, pem)
400}
401
402pub unsafe fn Cronet_Engine_SetMockCertVerifierForTesting(
403 engine: super::RawEngine, verifier: super::RawCertVerifier,
404) {
405 ffi_call!(b"Cronet_Engine_SetMockCertVerifierForTesting", unsafe extern "C" fn(super::RawEngine, super::RawCertVerifier), engine, verifier)
406}
407
408pub unsafe fn Cronet_Engine_SetDialer(
409 engine: super::RawEngine,
410 callback: Option<super::RawDialer>,
411 context: *mut std::ffi::c_void,
412) {
413 ffi_call!(b"Cronet_Engine_SetDialer", unsafe extern "C" fn(super::RawEngine, Option<super::RawDialer>, *mut std::ffi::c_void), engine, callback, context)
414}
415
416pub unsafe fn Cronet_Engine_SetUdpDialer(
417 engine: super::RawEngine,
418 callback: Option<super::RawUdpDialer>,
419 context: *mut std::ffi::c_void,
420 on_close: Option<super::RawUdpSocketClose>,
421) {
422 ffi_call!(
423 b"Cronet_Engine_SetUdpDialer",
424 unsafe extern "C" fn(
425 super::RawEngine,
426 Option<super::RawUdpDialer>,
427 *mut std::ffi::c_void,
428 Option<super::RawUdpSocketClose>,
429 ),
430 engine,
431 callback,
432 context,
433 on_close
434 )
435}
436
437pub unsafe fn Cronet_EngineParams_Create() -> super::RawEngineParams {
442 ffi_call!(b"Cronet_EngineParams_Create", unsafe extern "C" fn() -> super::RawEngineParams,)
443}
444
445pub unsafe fn Cronet_EngineParams_Destroy(params: super::RawEngineParams) {
446 ffi_call!(b"Cronet_EngineParams_Destroy", unsafe extern "C" fn(super::RawEngineParams), params)
447}
448
449pub unsafe fn Cronet_EngineParams_enable_quic_set(params: super::RawEngineParams, enable: bool) {
450 ffi_call!(b"Cronet_EngineParams_enable_quic_set", unsafe extern "C" fn(super::RawEngineParams, bool), params, enable)
451}
452
453pub unsafe fn Cronet_EngineParams_enable_http2_set(params: super::RawEngineParams, enable: bool) {
454 ffi_call!(b"Cronet_EngineParams_enable_http2_set", unsafe extern "C" fn(super::RawEngineParams, bool), params, enable)
455}
456
457pub unsafe fn Cronet_EngineParams_enable_brotli_set(params: super::RawEngineParams, enable: bool) {
458 ffi_call!(b"Cronet_EngineParams_enable_brotli_set", unsafe extern "C" fn(super::RawEngineParams, bool), params, enable)
459}
460
461pub unsafe fn Cronet_EngineParams_user_agent_set(
462 params: super::RawEngineParams, ua: *const std::os::raw::c_char,
463) {
464 ffi_call!(b"Cronet_EngineParams_user_agent_set", unsafe extern "C" fn(super::RawEngineParams, *const std::os::raw::c_char), params, ua)
465}
466
467pub unsafe fn Cronet_EngineParams_experimental_options_set(
468 params: super::RawEngineParams, opts: *const std::os::raw::c_char,
469) {
470 ffi_call!(b"Cronet_EngineParams_experimental_options_set", unsafe extern "C" fn(super::RawEngineParams, *const std::os::raw::c_char), params, opts)
471}
472
473pub unsafe fn Cronet_EngineParams_http_cache_mode_set(params: super::RawEngineParams, mode: i32) {
474 ffi_call!(b"Cronet_EngineParams_http_cache_mode_set", unsafe extern "C" fn(super::RawEngineParams, i32), params, mode)
475}
476
477pub unsafe fn Cronet_EngineParams_http_cache_max_size_set(params: super::RawEngineParams, size: i64) {
478 ffi_call!(b"Cronet_EngineParams_http_cache_max_size_set", unsafe extern "C" fn(super::RawEngineParams, i64), params, size)
479}
480
481pub unsafe fn bidirectional_stream_create(
486 engine: super::RawStreamEngine,
487 annotation: usize,
488 callback: *const super::RawBidirectionalStreamCallback,
489) -> super::RawBidirectionalStream {
490 ffi_call!(b"bidirectional_stream_create", unsafe extern "C" fn(super::RawStreamEngine, usize, *const super::RawBidirectionalStreamCallback) -> super::RawBidirectionalStream, engine, annotation, callback)
491}
492
493pub unsafe fn bidirectional_stream_destroy(stream: super::RawBidirectionalStream) -> i32 {
494 ffi_call!(b"bidirectional_stream_destroy", unsafe extern "C" fn(super::RawBidirectionalStream) -> i32, stream)
495}
496
497pub unsafe fn bidirectional_stream_start(
498 stream: super::RawBidirectionalStream,
499 url: *const std::os::raw::c_char,
500 priority: i32,
501 method: *const std::os::raw::c_char,
502 headers: *const super::RawBidirectionalStreamHeaderArray,
503 end_of_stream: bool,
504) -> i32 {
505 ffi_call!(b"bidirectional_stream_start", unsafe extern "C" fn(super::RawBidirectionalStream, *const std::os::raw::c_char, i32, *const std::os::raw::c_char, *const super::RawBidirectionalStreamHeaderArray, bool) -> i32, stream, url, priority, method, headers, end_of_stream)
506}
507
508pub unsafe fn bidirectional_stream_read(
509 stream: super::RawBidirectionalStream,
510 buffer: *mut u8,
511 size: i32,
512) -> i32 {
513 ffi_call!(b"bidirectional_stream_read", unsafe extern "C" fn(super::RawBidirectionalStream, *mut u8, i32) -> i32, stream, buffer, size)
514}
515
516pub unsafe fn bidirectional_stream_write(
517 stream: super::RawBidirectionalStream,
518 buffer: *const u8,
519 size: i32,
520 end_of_stream: bool,
521) -> i32 {
522 ffi_call!(b"bidirectional_stream_write", unsafe extern "C" fn(super::RawBidirectionalStream, *const u8, i32, bool) -> i32, stream, buffer, size, end_of_stream)
523}
524
525pub unsafe fn bidirectional_stream_flush(stream: super::RawBidirectionalStream) {
526 ffi_call!(b"bidirectional_stream_flush", unsafe extern "C" fn(super::RawBidirectionalStream), stream)
527}
528
529pub unsafe fn bidirectional_stream_cancel(stream: super::RawBidirectionalStream) {
530 ffi_call!(b"bidirectional_stream_cancel", unsafe extern "C" fn(super::RawBidirectionalStream), stream)
531}
532
533pub unsafe fn bidirectional_stream_disable_auto_flush(stream: super::RawBidirectionalStream, disable: bool) {
534 ffi_call!(b"bidirectional_stream_disable_auto_flush", unsafe extern "C" fn(super::RawBidirectionalStream, bool), stream, disable)
535}
536
537pub unsafe fn bidirectional_stream_delay_request_headers_until_flush(
538 stream: super::RawBidirectionalStream,
539 delay: bool,
540) {
541 ffi_call!(b"bidirectional_stream_delay_request_headers_until_flush", unsafe extern "C" fn(super::RawBidirectionalStream, bool), stream, delay)
542}
543
544
545#[cfg(test)]
546mod tests {
547 use super::*;
548
549 fn suf() -> &'static str {
551 std::env::consts::DLL_SUFFIX
552 }
553
554 #[test]
555 fn rejects_non_loadable_extensions() {
556 assert!(choose_library(["libcronet.a", "cronet.lib", "cronet_c.h", "notes.txt"]).is_none());
558 }
559
560 #[test]
561 fn prefers_cronet_named_file() {
562 let s = suf();
563 let other = format!("libfoo{s}");
564 let cronet = format!("libcronet{s}");
565 let chosen = choose_library([other.as_str(), cronet.as_str()]).unwrap();
566 assert_eq!(chosen, cronet);
567 }
568
569 #[test]
570 fn single_canonical_file_in_dir_is_picked() {
571 let s = suf();
572 let only = format!("libcronet{s}");
573 assert_eq!(choose_library([only.as_str()]).unwrap(), only);
574 }
575
576 #[test]
577 fn ties_break_deterministically() {
578 let s = suf();
579 let a = format!("libaaa{s}");
581 let b = format!("libbbb{s}");
582 assert_eq!(choose_library([b.as_str(), a.as_str()]).unwrap(), a);
583 }
584
585 #[test]
586 fn matches_release_asset_naming_for_this_target() {
587 let s = suf();
590 let os = std::env::consts::OS;
591 let (mine, foreign): (&str, &str) = match std::env::consts::ARCH {
592 "x86_64" => ("amd64", "arm64"),
593 "aarch64" => ("arm64", "amd64"),
594 "x86" => ("386", "amd64"),
595 _ => return, };
597 let mine_file = format!("libcronet-{os}-{mine}{s}");
598 let foreign_file = format!("libcronet-{os}-{foreign}{s}");
599 let chosen = choose_library([foreign_file.as_str(), mine_file.as_str()]).unwrap();
600 assert_eq!(chosen, mine_file);
601 }
602
603 #[test]
604 fn find_in_directory_resolves_full_path() {
605 let s = suf();
607 let dir = std::env::temp_dir().join(format!("cronet_sys_find_test_{}", std::process::id()));
608 let _ = std::fs::create_dir_all(&dir);
609 let lib = dir.join(format!("libcronet{s}"));
610 std::fs::write(&lib, b"not a real lib").unwrap();
611 std::fs::write(dir.join("readme.txt"), b"ignore me").unwrap();
612
613 let found = find_platform_library(&dir).expect("should find the cronet lib");
614 assert_eq!(found, lib);
615
616 let _ = std::fs::remove_dir_all(&dir);
617 }
618
619 #[test]
620 fn find_recurses_into_subdirectories() {
621 let s = suf();
623 let os = std::env::consts::OS;
624 let root =
625 std::env::temp_dir().join(format!("cronet_sys_recurse_test_{}", std::process::id()));
626 let sub = root.join(format!("{os}-host")).join("nested");
627 std::fs::create_dir_all(&sub).unwrap();
628 std::fs::write(root.join("notes.txt"), b"ignore").unwrap();
629 let lib = sub.join(format!("libcronet{s}"));
630 std::fs::write(&lib, b"not a real lib").unwrap();
631
632 let found = find_platform_library(&root).expect("should find nested cronet lib");
634 assert_eq!(found, lib);
635
636 let _ = std::fs::remove_dir_all(&root);
637 }
638}