libcronet_sys/lib.rs
1//! Raw FFI bindings for the Chromium Cronet C API (`libcronet`).
2//!
3//! `dynamic` takes precedence over `static-link` on every target, so one feature
4//! combination always selects the same backend. Desktop and Android targets load
5//! Cronet at runtime by default and link the archive only with `static-link`.
6//! Apple targets link the archive by default; enabling `dynamic` there switches to
7//! runtime loading, which requires a user-supplied shared library (no shared
8//! Cronet build is released for macOS, and iOS/tvOS support none at all).
9//!
10//! ## Obtaining the native library
11//!
12//! The native library is not vendored. Provide it one of three ways:
13//! - point `CRONET_LIB_DIR` at a directory containing it (static mode), or
14//! - place a loadable `libcronet.{so,dll,dylib}` on the system search path (dynamic
15//! mode), or
16//! - enable **`static-link,download-static`** for automatic static downloads, or
17//! the legacy **`download`** feature for either backend, to fetch and checksum a
18//! prebuilt from <https://github.com/rust-proxy/cronet-binaries> into `OUT_DIR`.
19//! Then load it via [`load_downloaded_library`] (dynamic) — the path is also
20//! available via [`downloaded_library_path`].
21
22// The upstream header declares bidirectional_stream_is_done, but the native
23// library does not implement it. Observe the terminal callbacks instead; binding
24// the missing symbol prevents Windows static consumers from linking.
25
26#![allow(clippy::missing_safety_doc)]
27
28// ---------------------------------------------------------------------------
29// Common opaque pointer types — always compiled
30// ---------------------------------------------------------------------------
31
32/// Opaque handle to a `Cronet_Engine` object.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34#[repr(transparent)]
35pub struct RawEngine(pub usize);
36
37/// Opaque handle to a `Cronet_EngineParams` object.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[repr(transparent)]
40pub struct RawEngineParams(pub usize);
41
42/// Opaque handle to a `stream_engine` (bidirectional stream engine).
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44#[repr(transparent)]
45pub struct RawStreamEngine(pub usize);
46
47/// Opaque handle to a `bidirectional_stream`.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49#[repr(transparent)]
50pub struct RawBidirectionalStream(pub usize);
51
52/// Opaque handle to a `CertVerifier`.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54#[repr(transparent)]
55pub struct RawCertVerifier(pub usize);
56
57// ---------------------------------------------------------------------------
58// C callback types — always compiled
59// ---------------------------------------------------------------------------
60
61/// TCP dialer callback: returns fd (or negative net_error).
62pub type RawDialer = extern "C" fn(
63 context: *mut std::ffi::c_void,
64 address: *const std::os::raw::c_char,
65 port: u16,
66) -> isize;
67
68/// UDP dialer callback returning a native socket or negative net error.
69/// On success, write the local endpoint and an ID (zero disables close notification).
70pub type RawUdpDialer = extern "C" fn(
71 context: *mut std::ffi::c_void,
72 address: *const std::os::raw::c_char,
73 port: u16,
74 out_local_address: *mut std::os::raw::c_char,
75 out_local_port: *mut u16,
76 out_socket_id: *mut u64,
77) -> isize;
78
79/// Optional notification for a nonzero ID returned by the UDP dialer.
80pub type RawUdpSocketClose = extern "C" fn(socket_id: u64);
81
82/// Raw callback struct for `bidirectional_stream`.
83///
84/// Field order and signatures mirror `bidirectional_stream_callback` in
85/// `bidirectional_stream_c.h` exactly. The C API does **not** pass a user-data
86/// argument — application state is associated through the stream's `annotation`
87/// (passed to `bidirectional_stream_create`). `on_read_completed` and
88/// `on_write_completed` carry the data buffer pointer the C API was operating on.
89#[repr(C)]
90pub struct RawBidirectionalStreamCallback {
91 /// `void (*on_stream_ready)(bidirectional_stream* stream)`
92 pub on_stream_ready: Option<extern "C" fn(stream: RawBidirectionalStream)>,
93 /// `void (*on_response_headers_received)(bidirectional_stream*, const header_array*, const char*)`
94 pub on_response_headers_received: Option<
95 extern "C" fn(
96 stream: RawBidirectionalStream,
97 headers: *const RawBidirectionalStreamHeaderArray,
98 negotiated_protocol: *const std::os::raw::c_char,
99 ),
100 >,
101 /// `void (*on_read_completed)(bidirectional_stream*, char* data, int bytes_read)`
102 pub on_read_completed: Option<
103 extern "C" fn(
104 stream: RawBidirectionalStream,
105 data: *mut std::os::raw::c_char,
106 bytes_read: i32,
107 ),
108 >,
109 /// `void (*on_write_completed)(bidirectional_stream*, const char* data)`
110 pub on_write_completed: Option<
111 extern "C" fn(stream: RawBidirectionalStream, data: *const std::os::raw::c_char),
112 >,
113 /// `void (*on_response_trailers_received)(bidirectional_stream*, const header_array*)`
114 pub on_response_trailers_received: Option<
115 extern "C" fn(
116 stream: RawBidirectionalStream,
117 trailers: *const RawBidirectionalStreamHeaderArray,
118 ),
119 >,
120 /// `void (*on_succeded)(bidirectional_stream* stream)` (note: C header spelling)
121 pub on_succeeded: Option<extern "C" fn(stream: RawBidirectionalStream)>,
122 /// `void (*on_failed)(bidirectional_stream* stream, int net_error)`
123 pub on_failed: Option<extern "C" fn(stream: RawBidirectionalStream, net_error: i32)>,
124 /// `void (*on_canceled)(bidirectional_stream* stream)`
125 pub on_canceled: Option<extern "C" fn(stream: RawBidirectionalStream)>,
126}
127
128/// Header struct for `bidirectional_stream`.
129#[repr(C)]
130#[derive(Clone, Copy)]
131pub struct RawBidirectionalStreamHeader {
132 pub key: *const std::os::raw::c_char,
133 pub value: *const std::os::raw::c_char,
134}
135
136/// Header array struct.
137#[repr(C)]
138#[derive(Clone, Copy)]
139pub struct RawBidirectionalStreamHeaderArray {
140 pub count: usize,
141 pub capacity: usize,
142 pub headers: *const RawBidirectionalStreamHeader,
143}
144
145// ---------------------------------------------------------------------------
146// Prebuilt-library discovery (the `download` feature)
147// ---------------------------------------------------------------------------
148
149/// Whether this build links Cronet into the executable.
150pub const STATIC_LINKED: bool = cfg!(cronet_static_link);
151
152/// Path to the verified archive or shared library selected by the downloader,
153/// or `None` when the build used no downloaded asset.
154///
155/// In dynamic mode this is a loadable `.so`/`.dll`; pass it to
156/// [`load_library`] (or just call [`load_downloaded_library`]).
157pub fn downloaded_library_path() -> Option<&'static str> {
158 option_env!("CRONET_DOWNLOADED_LIB_PATH")
159}
160
161/// Load the prebuilt library that `build.rs` downloaded (dynamic mode).
162///
163/// Returns an error in dynamic mode without `download`. In static mode this
164/// is a no-op: the library is already linked.
165///
166/// # Safety
167/// Same contract as [`load_library`] — must be called before any other FFI
168/// function, and only once.
169pub unsafe fn load_downloaded_library() -> Result<(), Box<dyn std::error::Error>> {
170 #[cfg(cronet_static_link)]
171 {
172 Ok(())
173 }
174 #[cfg(not(cronet_static_link))]
175 match downloaded_library_path() {
176 Some(path) => unsafe { load_library(path) },
177 None => Err("libcronet-sys was built without the `download` feature; \
178 no prebuilt library path is available"
179 .into()),
180 }
181}
182
183// ---------------------------------------------------------------------------
184// Pull in the correct backend
185// ---------------------------------------------------------------------------
186
187#[cfg(not(cronet_static_link))]
188mod dynamic;
189#[cfg(not(cronet_static_link))]
190pub use dynamic::*;
191
192#[cfg(cronet_static_link)]
193mod static_link;
194#[cfg(cronet_static_link)]
195pub use static_link::*;
196
197#[cfg(all(
198 test,
199 any(
200 feature = "download",
201 all(feature = "download-static", cronet_static_link)
202 )
203))]
204mod download_tests {
205 /// With the `download` feature on, build.rs must have fetched a prebuilt
206 /// and exposed a real, existing path.
207 #[test]
208 fn downloaded_path_points_at_a_real_file() {
209 if std::env::var_os("CRONET_LIB_DIR").is_some() && super::STATIC_LINKED {
210 return;
211 }
212 let path = super::downloaded_library_path()
213 .expect("`download` feature should set CRONET_DOWNLOADED_LIB_PATH");
214 assert!(
215 std::path::Path::new(path).exists(),
216 "downloaded library should exist on disk: {path}"
217 );
218 }
219}
220
221#[cfg(all(test, cronet_static_link))]
222mod static_tests {
223 #[test]
224 fn static_backend_does_not_load_a_runtime_library() {
225 assert!(unsafe { super::load_library("/nonexistent/cronet-library") }.is_ok());
226 assert!(unsafe { super::load_downloaded_library() }.is_ok());
227 }
228}
229
230#[cfg(all(test, not(cronet_static_link), not(feature = "download")))]
231mod dynamic_tests {
232 #[test]
233 fn dynamic_backend_uses_runtime_library_without_static_download() {
234 assert!(super::downloaded_library_path().is_none());
235 assert!(unsafe { super::load_library("/nonexistent/cronet-library") }.is_err());
236 }
237}