soyokaze 0.6.3

HTTP/1/2/3 Library Crate
Documentation
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
//! Dialling an origin and issuing requests, from C.
//!
//! [`soyokaze_client_fetch`] and its shorthands each dial, exchange one
//! message, and close. [`soyokaze_client_open`] hands back the connection
//! instead, so several messages may go over one.

use crate::api::client::Client;
use crate::ffi::models::Limits;
use crate::ffi::errors::{ErrorHandle, Status};
use crate::ffi::models::Port;
use crate::ffi::tls::{ECHEntry, TLSConfig};
use crate::ffi::websocket::WebSocket;
use crate::ffi::{Buffer, Runtime, Slice};
use crate::models::{Message, Method, Role, URL, Version};
use crate::protocol::base::{AnyConnection, Connection};

/// The limits a client applies on top of the per-message [`Limits`].
///
/// The C half of [`ClientLimits`], field for field.
///
/// [`ClientLimits`]: crate::api::client::ClientLimits
#[repr(C)]
#[derive(Clone, Copy)]
pub struct ClientLimits {
    /// The limits each connection holds itself to.
    pub message: Limits,
    /// In seconds, how long establishing one connection may take, TLS
    /// handshake included. Zero waits forever.
    pub connection_timeout: f64,
}

impl ClientLimits {
    /// The [`ClientLimits`] this stands for.
    ///
    /// [`ClientLimits`]: crate::api::client::ClientLimits
    pub fn parse(&self) -> crate::api::client::ClientLimits {
        crate::api::client::ClientLimits { message: self.message.parse(), connection_timeout: self.connection_timeout }
    }

    /// The C half of `limits`, field for field.
    pub fn build(limits: &crate::api::client::ClientLimits) -> Self {
        Self { message: Limits::build(&limits.message), connection_timeout: limits.connection_timeout }
    }
}

/// The default [`ClientLimits`], to be adjusted and passed back.
///
/// [`ClientLimits`]: crate::api::client::ClientLimits
#[unsafe(no_mangle)]
pub extern "C" fn soyokaze_client_limits_default() -> ClientLimits {
    ClientLimits::build(&crate::api::client::ClientLimits::default())
}

/// How a [`Client`] is configured.
///
/// Passing null wherever one of these is asked for takes every default:
/// negotiate the version, default limits, TLS on, the platform trust store,
/// no ECH, cookies kept, HSTS remembered. A null pointer inside the struct
/// takes that field's default the same way.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct ClientConfig {
    /// The versions to offer, most preferred first, as `soyokaze_version_t`
    /// numbers. Null offers every supported version; exactly one entry pins
    /// the version instead of negotiating one.
    pub versions: *const i32,
    /// How many entries `versions` holds.
    pub version_count: usize,

    /// The limits every connection this client makes will hold itself to.
    pub limits: *const ClientLimits,

    /// Whether a stream transport is wrapped in TLS.
    pub secure: bool,
    /// Whether a cookie jar is kept across requests.
    pub cookies: bool,
    /// Whether an HSTS store is kept across requests.
    pub hsts: bool,

    /// The certificates to trust instead of the platform store, each DER or
    /// PEM. Null keeps the platform store.
    pub roots: *const Slice,
    /// How many entries `roots` holds.
    pub root_count: usize,

    /// The TLS details every context is built with. Null takes every default,
    /// as `soyokaze_tls_config_default` hands them out.
    pub tls: *const TLSConfig,

    /// The ECH configuration lists to use when dialling each host.
    pub ech: *const ECHEntry,
    /// How many entries `ech` holds.
    pub ech_count: usize,
}

impl ClientConfig {
    /// The configuration a null pointer stands for.
    pub const DEFAULT: Self = Self {
        versions: std::ptr::null(),
        version_count: 0,
        limits: std::ptr::null(),
        secure: true,
        cookies: true,
        hsts: true,
        roots: std::ptr::null(),
        root_count: 0,
        tls: std::ptr::null(),
        ech: std::ptr::null(),
        ech_count: 0,
    };

    /// The [`Client`] this configures.
    ///
    /// `None` when an entry is unusable: a number that names no version, a
    /// null root, a TLS list that is not UTF-8, or an ECH host that is null
    /// or not UTF-8.
    ///
    /// # Safety
    ///
    /// Every pointer in the struct must either be null or point to its stated
    /// number of readable elements, themselves valid.
    pub unsafe fn build(&self) -> Option<Client> {
        let mut config = crate::api::client::ClientConfig {
            secure: self.secure,
            cookies: self.cookies,
            hsts: self.hsts,
            ..crate::api::client::ClientConfig::default()
        };

        let versions = unsafe { Version::parse_all(self.versions, self.version_count) }?;
        if !versions.is_empty() {
            config.versions = versions;
        }

        if let Some(limits) = unsafe { self.limits.as_ref() } {
            config.limits = limits.parse();
        }

        if !self.roots.is_null() {
            let mut roots = Vec::with_capacity(self.root_count);
            for index in 0..self.root_count {
                let slice = unsafe { *self.roots.add(index) };
                roots.push(unsafe { Slice::borrow(slice.data, slice.len) }?.to_vec());
            }
            config.roots = Some(roots);
        }

        if let Some(tls) = unsafe { self.tls.as_ref() } {
            config.tls = unsafe { tls.parse() }?;
        }

        if !self.ech.is_null() {
            for index in 0..self.ech_count {
                let entry = unsafe { *self.ech.add(index) };
                let host = unsafe { Slice::borrow_text(entry.host.data, entry.host.len) }?;
                let list = unsafe { Slice::borrow(entry.config_list.data, entry.config_list.len) }?;
                config.ech.insert(host.to_owned(), list.to_vec());
            }
        }

        Some(Client::new(config))
    }
}

/// Builds a [`Client`].
///
/// A null `config` takes [`ClientConfig::DEFAULT`]. Returns null when the
/// configuration holds an unusable entry.
///
/// # Safety
///
/// `config` must either be null or point to a readable [`ClientConfig`] whose
/// own pointers are valid.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_new(config: *const ClientConfig) -> *mut Client {
    let config = unsafe { config.as_ref() }.copied().unwrap_or(ClientConfig::DEFAULT);

    match unsafe { config.build() } {
        Some(client) => Box::into_raw(Box::new(client)),
        None => std::ptr::null_mut(),
    }
}

/// Releases a [`Client`].
///
/// # Safety
///
/// `client` must come from [`soyokaze_client_new`] and not have been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_free(client: *mut Client) {
    if !client.is_null() {
        drop(unsafe { Box::from_raw(client) });
    }
}

/// Makes one request and hands back the response.
///
/// Dials, exchanges, and closes. HSTS is applied to the URL first; `Host` and
/// `Cookie` are filled in unless `request` already carries them; and any
/// `Set-Cookie` and `Strict-Transport-Security` on the response are taken into
/// the client's state. Redirects are not followed.
///
/// `request` may be null. When it is not, its field section and body are used
/// for the request and the handle is consumed — the caller must not free it.
///
/// # Safety
///
/// `runtime` and `client` must be handles that have not been freed, `url` must
/// point to `url_len` readable octets, `request` must either be null or be a
/// message handle the caller owns, and `out` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_fetch(runtime: *mut Runtime, client: *const Client, method: i32, url: *const u8, url_len: usize, request: *mut Message, out: *mut *mut Message, error: *mut *mut ErrorHandle) -> Status {
    let request = (!request.is_null()).then(|| *unsafe { Box::from_raw(request) });

    let Some(method) = Method::from_code(method) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    let (Some(runtime), Some(client), Some(url)) = (unsafe { runtime.as_ref() }, unsafe { client.as_ref() }, unsafe { Slice::borrow_text(url, url_len) })
    else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    let (headers, body) = match request {
        Some(request) => (request.headers, request.body),
        None => (None, None),
    };

    match runtime.0.block_on(client.fetch(method, url, headers, body)) {
        Ok(response) => {
            unsafe { *out = Box::into_raw(Box::new(response)) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// A `GET`; see [`soyokaze_client_fetch`].
///
/// # Safety
///
/// As [`soyokaze_client_fetch`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_get(runtime: *mut Runtime, client: *const Client, url: *const u8, url_len: usize, out: *mut *mut Message, error: *mut *mut ErrorHandle) -> Status {
    unsafe { soyokaze_client_fetch(runtime, client, Method::GET as i32, url, url_len, std::ptr::null_mut(), out, error) }
}

/// A `HEAD`; see [`soyokaze_client_fetch`].
///
/// # Safety
///
/// As [`soyokaze_client_fetch`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_head(runtime: *mut Runtime, client: *const Client, url: *const u8, url_len: usize, out: *mut *mut Message, error: *mut *mut ErrorHandle) -> Status {
    unsafe { soyokaze_client_fetch(runtime, client, Method::HEAD as i32, url, url_len, std::ptr::null_mut(), out, error) }
}

/// A `POST`; see [`soyokaze_client_fetch`].
///
/// # Safety
///
/// As [`soyokaze_client_fetch`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_post(runtime: *mut Runtime, client: *const Client, url: *const u8, url_len: usize, request: *mut Message, out: *mut *mut Message, error: *mut *mut ErrorHandle) -> Status {
    unsafe { soyokaze_client_fetch(runtime, client, Method::POST as i32, url, url_len, request, out, error) }
}

/// A `PUT`; see [`soyokaze_client_fetch`].
///
/// # Safety
///
/// As [`soyokaze_client_fetch`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_put(runtime: *mut Runtime, client: *const Client, url: *const u8, url_len: usize, request: *mut Message, out: *mut *mut Message, error: *mut *mut ErrorHandle) -> Status {
    unsafe { soyokaze_client_fetch(runtime, client, Method::PUT as i32, url, url_len, request, out, error) }
}

/// A `DELETE`; see [`soyokaze_client_fetch`].
///
/// # Safety
///
/// As [`soyokaze_client_fetch`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_delete(runtime: *mut Runtime, client: *const Client, url: *const u8, url_len: usize, out: *mut *mut Message, error: *mut *mut ErrorHandle) -> Status {
    unsafe { soyokaze_client_fetch(runtime, client, Method::DELETE as i32, url, url_len, std::ptr::null_mut(), out, error) }
}

/// Opens a connection for a URL, taking the transport from its scheme.
///
/// # Safety
///
/// `runtime`, `client` and `url` must be handles that have not been freed, and
/// `out` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_open(runtime: *mut Runtime, client: *const Client, url: *const URL, out: *mut *mut AnyConnection, error: *mut *mut ErrorHandle) -> Status {
    let (Some(runtime), Some(client), Some(url)) = (unsafe { runtime.as_ref() }, unsafe { client.as_ref() }, unsafe { url.as_ref() })
    else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    match runtime.0.block_on(client.open(url)) {
        Ok(connection) => {
            unsafe { *out = Box::into_raw(Box::new(connection)) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Opens a connection to a host on a given port.
///
/// The port decides the transport, and so which versions are available.
///
/// # Safety
///
/// `runtime` and `client` must be handles that have not been freed, `host` must
/// point to `host_len` readable octets, `port` must point to a readable [`Port`]
/// whose own pointers are valid, and `out` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_connect(runtime: *mut Runtime, client: *const Client, host: *const u8, host_len: usize, port: *const Port, out: *mut *mut AnyConnection, error: *mut *mut ErrorHandle) -> Status {
    let (Some(runtime), Some(client), Some(host), Some(port)) = (
        unsafe { runtime.as_ref() },
        unsafe { client.as_ref() },
        unsafe { Slice::borrow_text(host, host_len) },
        unsafe { port.as_ref() },
    ) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    let Some(port) = (unsafe { port.parse() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    match runtime.0.block_on(client.connect(host, port)) {
        Ok(connection) => {
            unsafe { *out = Box::into_raw(Box::new(connection)) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Sends a request over an open connection and waits for the response.
///
/// Informational (1xx) responses are read past. `request` is consumed — the
/// caller must not free it.
///
/// # Safety
///
/// `runtime`, `client`, `connection` and `request` must be handles that have not
/// been freed, and `out` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_request(runtime: *mut Runtime, client: *const Client, connection: *mut AnyConnection, request: *mut Message, out: *mut *mut Message, error: *mut *mut ErrorHandle) -> Status {
    if request.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    let request = *unsafe { Box::from_raw(request) };

    let (Some(runtime), Some(client), Some(connection)) = (unsafe { runtime.as_ref() }, unsafe { client.as_ref() }, unsafe { connection.as_mut() })
    else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    match runtime.0.block_on(client.request(connection, request)) {
        Ok(response) => {
            unsafe { *out = Box::into_raw(Box::new(response)) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Opens a WebSocket connection.
///
/// The handshake follows whichever version is negotiated: an HTTP/1.1
/// upgrade, or extended CONNECT over HTTP/2 and HTTP/3. The socket carries
/// its runtime with it, so the WebSocket calls take none — but `runtime`
/// must outlive the socket.
///
/// # Safety
///
/// `runtime` and `client` must be handles that have not been freed, `url`
/// must point to `url_len` readable octets, and `out` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_websocket(runtime: *mut Runtime, client: *const Client, url: *const u8, url_len: usize, out: *mut *mut WebSocket, error: *mut *mut ErrorHandle) -> Status {
    let (Some(runtime), Some(client), Some(url)) = (unsafe { runtime.as_ref() }, unsafe { client.as_ref() }, unsafe { Slice::borrow_text(url, url_len) })
    else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    match runtime.0.block_on(client.websocket(url)) {
        Ok(connection) => {
            unsafe { *out = Box::into_raw(Box::new(WebSocket { connection, handle: runtime.0.handle().clone() })) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// The version the connection settled on.
///
/// A null `connection` reads as [`Version::V1_1`].
///
/// # Safety
///
/// `connection` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_version(connection: *const AnyConnection) -> Version {
    unsafe { connection.as_ref() }.map_or(Version::V1_1, |connection| connection.version())
}

/// What this end of the connection is doing on it.
///
/// One of the `soyokaze_role_t` numbers; a null `connection` reads as
/// [`Role::UserAgent`], which is what a connection this library hands a C
/// caller from the client side is.
///
/// # Safety
///
/// As [`soyokaze_connection_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_role(connection: *const AnyConnection) -> u32 {
    match unsafe { connection.as_ref() } {
        Some(connection) => Role::build(connection.role()),
        None => Role::build(Role::UserAgent),
    }
}

/// The connection's identifier, owned by the caller.
///
/// # Safety
///
/// As [`soyokaze_connection_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_id(connection: *const AnyConnection) -> Buffer {
    match unsafe { connection.as_ref() } {
        Some(connection) => Buffer::new(connection.id().0.to_vec()),
        None => Buffer::EMPTY,
    }
}

/// The address the peer connected from, and its port, as text.
///
/// Empty on a client connection, and on one over a Unix socket, whose accepted
/// address names nothing. This is what every request the connection receives is
/// stamped with. Free the result with [`soyokaze_buffer_free`].
///
/// [`soyokaze_buffer_free`]: crate::ffi::soyokaze_buffer_free
///
/// # Safety
///
/// As [`soyokaze_connection_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_client(connection: *const AnyConnection) -> Buffer {
    match unsafe { connection.as_ref() }.and_then(Connection::client) {
        Some(client) => Buffer::new(client.to_string().into_bytes()),
        None => Buffer::EMPTY,
    }
}

/// Sends one message over an open connection, without waiting for anything
/// back.
///
/// This is the raw half of [`soyokaze_client_request`], for pipelining
/// requests or streaming responses by hand. On HTTP/2 and HTTP/3 a response
/// must carry the stream identifier of the request it answers, set with
/// `soyokaze_message_set_stream_id`. `message` is consumed — the caller must
/// not free it.
///
/// # Safety
///
/// `runtime` and `connection` must be handles that have not been freed, and
/// `message` must be a message handle the caller owns.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_send(runtime: *mut Runtime, connection: *mut AnyConnection, message: *mut Message, error: *mut *mut ErrorHandle) -> Status {
    if message.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    let message = *unsafe { Box::from_raw(message) };

    let (Some(runtime), Some(connection)) = (unsafe { runtime.as_ref() }, unsafe { connection.as_mut() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    match runtime.0.block_on(connection.send(message)) {
        Ok(()) => Status::Ok,
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Receives the next message from an open connection.
///
/// Unlike [`soyokaze_client_request`], informational (1xx) responses are
/// handed over rather than read past.
///
/// # Safety
///
/// `runtime` and `connection` must be handles that have not been freed, and
/// `out` must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_receive(runtime: *mut Runtime, connection: *mut AnyConnection, out: *mut *mut Message, error: *mut *mut ErrorHandle) -> Status {
    let (Some(runtime), Some(connection)) = (unsafe { runtime.as_ref() }, unsafe { connection.as_mut() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    match runtime.0.block_on(connection.receive()) {
        Ok(message) => {
            unsafe { *out = Box::into_raw(Box::new(message)) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Opens a WebSocket over an already-open connection and takes it over.
///
/// The client-side counterpart of a server accepting one. The connection is
/// consumed whether the handshake succeeds or not — the caller must not free
/// or use it again. The socket carries its runtime with it, but `runtime`
/// must outlive the socket.
///
/// # Safety
///
/// `runtime` must be a handle that has not been freed, `connection` must be
/// one the caller owns, `authority` and `target` must point to their stated
/// number of readable octets, `limits` must be null or readable, and `out`
/// must be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_open_websocket(runtime: *mut Runtime, connection: *mut AnyConnection, authority: *const u8, authority_len: usize, target: *const u8, target_len: usize, limits: *const crate::ffi::models::Limits, out: *mut *mut WebSocket, error: *mut *mut ErrorHandle) -> Status {
    if connection.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    let connection = *unsafe { Box::from_raw(connection) };

    let (Some(runtime), Some(authority), Some(target)) = (
        unsafe { runtime.as_ref() },
        unsafe { Slice::borrow_text(authority, authority_len) },
        unsafe { Slice::borrow_text(target, target_len) },
    ) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    if out.is_null() {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    }

    let limits = unsafe { crate::ffi::models::Limits::or_default(limits) };

    match runtime.0.block_on(connection.open_websocket(authority, target, limits)) {
        Ok(socket) => {
            unsafe { *out = Box::into_raw(Box::new(WebSocket { connection: socket, handle: runtime.0.handle().clone() })) };
            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Whether another message may go over the connection.
///
/// # Safety
///
/// As [`soyokaze_connection_version`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_reusable(connection: *const AnyConnection) -> bool {
    unsafe { connection.as_ref() }.is_some_and(|connection| connection.reusable())
}

/// Closes the connection, leaving the handle to be freed.
///
/// # Safety
///
/// `runtime` and `connection` must be handles that have not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_close(runtime: *mut Runtime, connection: *mut AnyConnection) {
    if let (Some(runtime), Some(connection)) = (unsafe { runtime.as_ref() }, unsafe { connection.as_mut() }) {
        runtime.0.block_on(connection.close());
    }
}

/// Releases a connection.
///
/// Does not close it; call [`soyokaze_connection_close`] first to shut it down
/// in an orderly way.
///
/// # Safety
///
/// `connection` must be a handle the caller owns and has not freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_connection_free(connection: *mut AnyConnection) {
    if !connection.is_null() {
        drop(unsafe { Box::from_raw(connection) });
    }
}

/// The connection identifier a client would give a connection to `host` on
/// `target`, owned by the caller.
///
/// The same identifier every message on that connection carries, so a caller
/// can key its own bookkeeping on what the library will use.
///
/// # Safety
///
/// `client` must either be null or be a handle that has not been freed, `host`
/// must point to `host_len` readable octets, and `target` must point to a
/// readable [`Port`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_id(client: *const Client, host: *const u8, host_len: usize, target: *const Port) -> Buffer {
    let (Some(client), Some(host), Some(target)) = (unsafe { client.as_ref() }, unsafe { Slice::borrow_text(host, host_len) }, unsafe { target.as_ref() }.and_then(|target| unsafe { target.parse() })) else {
        return Buffer::EMPTY;
    };

    Buffer::new(client.id(host, &target).0.to_vec())
}

/// The authority a client would send for `host` on `target`, owned by the
/// caller.
///
/// The port is left off when it is the scheme's default, which is what an
/// origin expects to see in `Host` or `:authority`.
///
/// # Safety
///
/// As [`soyokaze_client_id`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_authority(client: *const Client, host: *const u8, host_len: usize, target: *const Port) -> Buffer {
    let (Some(client), Some(host), Some(target)) = (unsafe { client.as_ref() }, unsafe { Slice::borrow_text(host, host_len) }, unsafe { target.as_ref() }.and_then(|target| unsafe { target.parse() })) else {
        return Buffer::EMPTY;
    };

    Buffer::new(client.authority(host, &target).into_bytes())
}

/// The ECH configuration list a client would use for `host`, borrowed from the
/// client.
///
/// Absent when the client has none for that host, either exactly or through
/// the `*` fallback.
///
/// # Safety
///
/// `client` must either be null or be a handle that has not been freed, and
/// `host` must point to `host_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_ech(client: *const Client, host: *const u8, host_len: usize) -> Slice {
    let (Some(client), Some(host)) = (unsafe { client.as_ref() }, unsafe { Slice::borrow_text(host, host_len) }) else {
        return Slice::ABSENT;
    };

    match client.ech(host) {
        Some(config) => Slice::new(config),
        None => Slice::ABSENT,
    }
}

/// The version a client would use without negotiating one.
///
/// A plain connection has no ALPN to settle a version with, so the client must
/// have been given exactly one version to offer. Fails when it was given
/// several, since nothing could then choose between them.
///
/// # Safety
///
/// `client` must either be null or be a handle that has not been freed, and
/// `out` must either be null or be writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_prior_version(client: *const Client, out: *mut Version, error: *mut *mut ErrorHandle) -> Status {
    let Some(client) = (unsafe { client.as_ref() }) else {
        return unsafe { ErrorHandle::raise(error, Status::Invalid) };
    };

    match client.prior_version() {
        Ok(version) => {
            if !out.is_null() {
                unsafe { *out = version };
            }

            Status::Ok
        }
        Err(failure) => unsafe { ErrorHandle::report(error, &failure) },
    }
}

/// Whether every version the client offers runs over QUIC.
///
/// A client like that dials UDP and nothing else, which is what decides how a
/// URL with no port is reached.
///
/// # Safety
///
/// `client` must either be null or be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_only_quic(client: *const Client) -> bool {
    unsafe { client.as_ref() }.is_some_and(|client| client.only_quic())
}

/// How many versions the client offers.
///
/// # Safety
///
/// As [`soyokaze_client_only_quic`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_version_count(client: *const Client) -> usize {
    unsafe { client.as_ref() }.map_or(0, |client| client.config.versions.len())
}

/// The version at `index` among those the client offers, or `-1` past the end.
///
/// # Safety
///
/// As [`soyokaze_client_only_quic`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_version_at(client: *const Client, index: usize) -> i32 {
    match unsafe { client.as_ref() }.and_then(|client| client.config.versions.get(index)) {
        Some(&version) => version as i32,
        None => -1,
    }
}

/// The client's cookie jar, as a handle of its own, or null when it keeps
/// none.
///
/// Borrowed from the client and valid until it is freed; it must not be freed
/// with `soyokaze_cookiejar_free`, which would take the client's jar with it.
///
/// # Safety
///
/// As [`soyokaze_client_only_quic`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_jar(client: *const Client) -> *const crate::cookies::CookieJar {
    match unsafe { client.as_ref() }.and_then(|client| client.jar.as_ref()) {
        Some(jar) => std::sync::Arc::as_ptr(jar),
        None => std::ptr::null(),
    }
}

/// The client's HSTS store, as a handle of its own, or null when it keeps
/// none.
///
/// As [`soyokaze_client_jar`], for the store.
///
/// # Safety
///
/// As [`soyokaze_client_only_quic`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_store(client: *const Client) -> *const crate::hsts::HSTSStore {
    match unsafe { client.as_ref() }.and_then(|client| client.store.as_ref()) {
        Some(store) => std::sync::Arc::as_ptr(store),
        None => std::ptr::null(),
    }
}

/// Rewrites a URL to `https` when the client's HSTS store insists on it.
///
/// Does nothing when the client keeps no store, or when the host has no policy
/// on file. Returns whether the URL was rewritten.
///
/// # Safety
///
/// `client` must either be null or be a handle that has not been freed, and
/// `url` must be a handle that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_apply_hsts(client: *const Client, url: *mut URL) -> bool {
    let (Some(client), Some(url)) = (unsafe { client.as_ref() }, unsafe { url.as_mut() }) else {
        return false;
    };

    let before = url.scheme.clone();
    client.apply_hsts(url, std::time::Instant::now());
    before != url.scheme
}

/// Builds the request finalizer a client would use for `authority`.
///
/// Freed with `soyokaze_request_finalizer_free`.
///
/// # Safety
///
/// `client` must either be null or be a handle that has not been freed, and
/// `authority` must point to `authority_len` readable octets.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn soyokaze_client_request_finalizer(client: *const Client, authority: *const u8, authority_len: usize) -> *mut crate::finalizer::RequestFinalizer {
    let (Some(client), Some(authority)) = (unsafe { client.as_ref() }, unsafe { Slice::borrow_text(authority, authority_len) }) else {
        return std::ptr::null_mut();
    };

    Box::into_raw(Box::new(client.request_finalizer(authority)))
}