lsquic.h revision 0a4f8953
1/* Copyright (c) 2017 - 2022 LiteSpeed Technologies Inc.  See LICENSE. */
2#ifndef __LSQUIC_H__
3#define __LSQUIC_H__
4
5/**
6 * @file
7 * public API for using liblsquic is defined in this file.
8 *
9 */
10
11#include <stdarg.h>
12#include <lsquic_types.h>
13#ifndef WIN32
14#include <sys/uio.h>
15#include <time.h>
16#else
17#include <vc_compat.h>
18#endif
19
20struct sockaddr;
21
22#ifdef __cplusplus
23extern "C" {
24#endif
25
26#define LSQUIC_MAJOR_VERSION 3
27#define LSQUIC_MINOR_VERSION 1
28#define LSQUIC_PATCH_VERSION 1
29
30/**
31 * Engine flags:
32 */
33
34/** Server mode */
35#define LSENG_SERVER (1 << 0)
36
37/** Use HTTP behavior */
38#define LSENG_HTTP  (1 << 1)
39
40#define LSENG_HTTP_SERVER (LSENG_SERVER|LSENG_HTTP)
41
42/**
43 * This is a list of QUIC versions that we know of.  List of supported
44 * versions is in LSQUIC_SUPPORTED_VERSIONS.
45 */
46enum lsquic_version
47{
48    /**
49     * Q043.  Support for processing PRIORITY frames.  Since this library
50     * has supported PRIORITY frames from the beginning, this version is
51     * exactly the same as LSQVER_042.
52     */
53    LSQVER_043,
54
55    /**
56     * Q046.  Use IETF Draft-17 compatible packet headers.
57     */
58    LSQVER_046,
59
60    /**
61     * Q050.  Variable-length QUIC server connection IDs.  Use CRYPTO frames
62     * for handshake.  IETF header format matching invariants-06.  Packet
63     * number encryption.  Initial packets are obfuscated.
64     */
65    LSQVER_050,
66
67    /**
68     * IETF QUIC Draft-27
69     */
70    LSQVER_ID27,
71
72    /**
73     * IETF QUIC Draft-29
74     */
75    LSQVER_ID29,
76
77    /**
78     * IETF QUIC v1.
79     */
80    LSQVER_I001,
81
82    /**
83     * Special version to trigger version negotiation.
84     * [draft-ietf-quic-transport-11], Section 3.
85     */
86    LSQVER_VERNEG,
87
88    N_LSQVER
89};
90
91/**
92 * We currently support versions 43, 46, 50, Draft-27, Draft-29,
93 * and IETF QUIC v1.
94 * @see lsquic_version
95 */
96#define LSQUIC_SUPPORTED_VERSIONS ((1 << N_LSQVER) - 1)
97
98/**
99 * List of versions in which the server never includes CID in short packets.
100 */
101#define LSQUIC_FORCED_TCID0_VERSIONS ((1 << LSQVER_046)|(1 << LSQVER_050))
102
103#define LSQUIC_EXPERIMENTAL_VERSIONS ( \
104                            (1 << LSQVER_VERNEG))
105
106#define LSQUIC_DEPRECATED_VERSIONS ((1 << LSQVER_ID27))
107
108#define LSQUIC_GQUIC_HEADER_VERSIONS (1 << LSQVER_043)
109
110#define LSQUIC_IETF_VERSIONS ((1 << LSQVER_ID27) \
111                          | (1 << LSQVER_ID29) \
112                          | (1 << LSQVER_I001) | (1 << LSQVER_VERNEG))
113
114#define LSQUIC_IETF_DRAFT_VERSIONS ((1 << LSQVER_ID27) \
115                                  | (1 << LSQVER_ID29) \
116                                  | (1 << LSQVER_VERNEG))
117
118enum lsquic_hsk_status
119{
120    /**
121     * The handshake failed.
122     */
123    LSQ_HSK_FAIL,
124    /**
125     * The handshake succeeded without session resumption.
126     */
127    LSQ_HSK_OK,
128    /**
129     * The handshake succeeded with session resumption.
130     */
131    LSQ_HSK_RESUMED_OK,
132    /**
133     * Session resumption failed.  Retry the connection without session
134     * resumption.
135     */
136    LSQ_HSK_RESUMED_FAIL,
137};
138
139/**
140 * @struct lsquic_stream_if
141 * @brief The definitions of callback functions called by lsquic_stream to
142 * process events.
143 *
144 */
145struct lsquic_stream_if {
146
147    /**
148     * Use @ref lsquic_conn_get_ctx to get back the context.  It is
149     * OK for this function to return NULL.
150     */
151    lsquic_conn_ctx_t *(*on_new_conn)(void *stream_if_ctx,
152                                                        lsquic_conn_t *c);
153
154    /** This is called when our side received GOAWAY frame.  After this,
155     *  new streams should not be created.  The callback is optional.
156     */
157    void (*on_goaway_received)(lsquic_conn_t *c);
158    void (*on_conn_closed)(lsquic_conn_t *c);
159
160    /** If you need to initiate a connection, call lsquic_conn_make_stream().
161     *  This will cause `on_new_stream' callback to be called when appropriate
162     *  (this operation is delayed when maximum number of outgoing streams is
163     *  reached).
164     *
165     *  After `on_close' is called, the stream is no longer accessible.
166     */
167    lsquic_stream_ctx_t *
168         (*on_new_stream)(void *stream_if_ctx, lsquic_stream_t *s);
169
170    void (*on_read)     (lsquic_stream_t *s, lsquic_stream_ctx_t *h);
171    void (*on_write)    (lsquic_stream_t *s, lsquic_stream_ctx_t *h);
172    void (*on_close)    (lsquic_stream_t *s, lsquic_stream_ctx_t *h);
173    /* Called when datagram is ready to be written */
174    ssize_t (*on_dg_write)(lsquic_conn_t *c, void *, size_t);
175    /* Called when datagram is read from a packet.  This callback is required
176     * when es_datagrams is true.  Take care to process it quickly, as this
177     * is called during lsquic_engine_packet_in().
178     */
179    void (*on_datagram)(lsquic_conn_t *, const void *buf, size_t);
180    /* This callback in only called in client mode */
181    /**
182     * When handshake is completed, this optional callback is called.
183     */
184    void (*on_hsk_done)(lsquic_conn_t *c, enum lsquic_hsk_status s);
185    /**
186     * When client receives a token in NEW_TOKEN frame, this callback is called.
187     * The callback is optional.
188     */
189    void (*on_new_token)(lsquic_conn_t *c, const unsigned char *token,
190                                                        size_t token_size);
191    /**
192     * This optional callback lets client record information needed to
193     * perform a session resumption next time around.
194     *
195     * For IETF QUIC, this is called only if ea_get_ssl_ctx() is *not* set,
196     * in which case the library creates its own SSL_CTX.
197     *
198     * Note: this callback will be deprecated when gQUIC support is removed.
199     */
200    void (*on_sess_resume_info)(lsquic_conn_t *c, const unsigned char *, size_t);
201    /**
202     * Optional callback is called as soon as the peer resets a stream.
203     * The argument `how' is either 0, 1, or 2, meaning "read", "write", and
204     * "read and write", respectively (just like in shutdown(2)).  This
205     * signals the user to stop reading, writing, or both.
206     *
207     * Note that resets differ in gQUIC and IETF QUIC.  In gQUIC, `how' is
208     * always 2; in IETF QUIC, `how' is either 0 or 1 because one can reset
209     * just one direction in IETF QUIC.
210     */
211    void (*on_reset)    (lsquic_stream_t *s, lsquic_stream_ctx_t *h, int how);
212    /**
213     * Optional callback is called when a CONNECTION_CLOSE frame is received.
214     * This allows the application to log low-level diagnostic information about
215     * errors received with the CONNECTION_CLOSE frame. If app_error is -1 then
216     * it is considered unknown if this is an app_error or not.
217     */
218    void (*on_conncloseframe_received)(lsquic_conn_t *c,
219                                       int app_error, uint64_t error_code,
220                                       const char *reason, int reason_len);
221};
222
223struct ssl_ctx_st;
224struct ssl_st;
225struct ssl_session_st;
226struct lsxpack_header;
227
228/**
229 * QUIC engine in server mode needs access to certificates.  This is
230 * accomplished by providing a callback and a context to the engine
231 * constructor.
232 */
233
234/* `sni' may be NULL if engine is not HTTP mode and client TLS transport
235 * parameters did not include the SNI.
236 */
237typedef struct ssl_ctx_st * (*lsquic_lookup_cert_f)(
238    void *lsquic_cert_lookup_ctx, const struct sockaddr *local, const char *sni);
239
240/**
241 * Minimum flow control window is set to 16 KB for both client and server.
242 * This means we can send up to this amount of data before handshake gets
243 * completed.
244 */
245#define      LSQUIC_MIN_FCW             (16 * 1024)
246
247/* Each LSQUIC_DF_* value corresponds to es_* entry in
248 * lsquic_engine_settings below.
249 */
250
251/**
252 * By default, deprecated and experimental versions are not included.
253 */
254#define LSQUIC_DF_VERSIONS         (LSQUIC_SUPPORTED_VERSIONS & \
255                                            ~LSQUIC_DEPRECATED_VERSIONS & \
256                                            ~LSQUIC_EXPERIMENTAL_VERSIONS)
257
258#define LSQUIC_DF_CFCW_SERVER      (3 * 1024 * 1024 / 2)
259#define LSQUIC_DF_CFCW_CLIENT      (15 * 1024 * 1024)
260#define LSQUIC_DF_SFCW_SERVER      (1 * 1024 * 1024)
261#define LSQUIC_DF_SFCW_CLIENT      (6 * 1024 * 1024)
262#define LSQUIC_DF_MAX_STREAMS_IN   100
263
264/* IQUIC uses different names for these: */
265#define LSQUIC_DF_INIT_MAX_DATA_SERVER LSQUIC_DF_CFCW_SERVER
266#define LSQUIC_DF_INIT_MAX_DATA_CLIENT LSQUIC_DF_CFCW_CLIENT
267#define LSQUIC_DF_INIT_MAX_STREAM_DATA_BIDI_REMOTE_SERVER LSQUIC_DF_SFCW_SERVER
268#define LSQUIC_DF_INIT_MAX_STREAM_DATA_BIDI_LOCAL_SERVER 0
269#define LSQUIC_DF_INIT_MAX_STREAM_DATA_BIDI_REMOTE_CLIENT 0
270#define LSQUIC_DF_INIT_MAX_STREAM_DATA_BIDI_LOCAL_CLIENT LSQUIC_DF_SFCW_CLIENT
271#define LSQUIC_DF_INIT_MAX_STREAMS_BIDI LSQUIC_DF_MAX_STREAMS_IN
272#define LSQUIC_DF_INIT_MAX_STREAMS_UNI_CLIENT 100
273#define LSQUIC_DF_INIT_MAX_STREAMS_UNI_SERVER 3
274/* XXX What's a good value here? */
275#define LSQUIC_DF_INIT_MAX_STREAM_DATA_UNI_CLIENT   (32 * 1024)
276#define LSQUIC_DF_INIT_MAX_STREAM_DATA_UNI_SERVER   (12 * 1024)
277
278/**
279 * Default idle connection time in seconds.
280 */
281#define LSQUIC_DF_IDLE_TIMEOUT 30
282
283/**
284 * Default ping period in seconds.
285 */
286#define LSQUIC_DF_PING_PERIOD 15
287
288/**
289 * Default handshake timeout in microseconds.
290 */
291#define LSQUIC_DF_HANDSHAKE_TO     (10 * 1000 * 1000)
292
293#define LSQUIC_DF_IDLE_CONN_TO     (LSQUIC_DF_IDLE_TIMEOUT * 1000 * 1000)
294#define LSQUIC_DF_SILENT_CLOSE     1
295
296/** Default value of maximum header list size.  If set to non-zero value,
297 *  SETTINGS_MAX_HEADER_LIST_SIZE will be sent to peer after handshake is
298 *  completed (assuming the peer supports this setting frame type).
299 */
300#define LSQUIC_DF_MAX_HEADER_LIST_SIZE 0
301
302/** Default value of UAID (user-agent ID). */
303#define LSQUIC_DF_UA               "LSQUIC"
304
305#define LSQUIC_DF_STTL               86400
306#define LSQUIC_DF_MAX_INCHOATE     (1 * 1000 * 1000)
307/** Do not use NSTP by default */
308#define LSQUIC_DF_SUPPORT_NSTP     0
309/** TODO: IETF QUIC clients do not support push */
310#define LSQUIC_DF_SUPPORT_PUSH         1
311#define LSQUIC_DF_SUPPORT_TCID0    1
312/** By default, LSQUIC ignores Public Reset packets. */
313#define LSQUIC_DF_HONOR_PRST       0
314
315/**
316 * By default, LSQUIC will not send Public Reset packets in response to
317 * packets that specify unknown connections.
318 */
319#define LSQUIC_DF_SEND_PRST        0
320
321/** By default, infinite loop checks are turned on */
322#define LSQUIC_DF_PROGRESS_CHECK    1000
323
324/** By default, read/write events are dispatched in a loop */
325#define LSQUIC_DF_RW_ONCE           0
326
327/** By default, the threshold is not enabled */
328#define LSQUIC_DF_PROC_TIME_THRESH  0
329
330/** By default, packets are paced */
331#define LSQUIC_DF_PACE_PACKETS      1
332
333/** Default clock granularity is 1000 microseconds */
334#define LSQUIC_DF_CLOCK_GRANULARITY      1000
335
336/** The default value is 8 for simplicity */
337#define LSQUIC_DF_SCID_LEN 8
338
339/** The default value is 60 CIDs per minute */
340#define LSQUIC_DF_SCID_ISS_RATE   60
341
342#define LSQUIC_DF_QPACK_DEC_MAX_BLOCKED 100
343#define LSQUIC_DF_QPACK_DEC_MAX_SIZE 4096
344#define LSQUIC_DF_QPACK_ENC_MAX_BLOCKED 100
345#define LSQUIC_DF_QPACK_ENC_MAX_SIZE 4096
346
347/* By default, QPACK experiments are turned off */
348#define LSQUIC_DF_QPACK_EXPERIMENT 0
349
350/** ECN is disabled by default */
351#define LSQUIC_DF_ECN 0
352
353/** Allow migration by default */
354#define LSQUIC_DF_ALLOW_MIGRATION 1
355
356/** Use QL loss bits by default */
357#define LSQUIC_DF_QL_BITS 2
358
359/** Turn spin bit on by default */
360#define LSQUIC_DF_SPIN 1
361
362/** Turn on delayed ACKs extension by default */
363#define LSQUIC_DF_DELAYED_ACKS 1
364
365/**
366 * Defaults for the Packet Tolerance PID Controller (PTPC) used by the
367 * Delayed ACKs extension:
368 */
369#define LSQUIC_DF_PTPC_PERIODICITY 3
370#define LSQUIC_DF_PTPC_MAX_PACKTOL 150
371#define LSQUIC_DF_PTPC_DYN_TARGET 1
372#define LSQUIC_DF_PTPC_TARGET 1.0
373#define LSQUIC_DF_PTPC_PROP_GAIN 0.8
374#define LSQUIC_DF_PTPC_INT_GAIN 0.35
375#define LSQUIC_DF_PTPC_ERR_THRESH 0.05
376#define LSQUIC_DF_PTPC_ERR_DIVISOR 0.05
377
378/** Turn on timestamp extension by default */
379#define LSQUIC_DF_TIMESTAMPS 1
380
381/* Use Adaptive CC by default */
382#define LSQUIC_DF_CC_ALGO 3
383
384/* Default value of the CC RTT threshold is 1.5 ms */
385#define LSQUIC_DF_CC_RTT_THRESH 1500
386
387/** Turn off datagram extension by default */
388#define LSQUIC_DF_DATAGRAMS 0
389
390/** Assume optimistic NAT by default. */
391#define LSQUIC_DF_OPTIMISTIC_NAT 1
392
393/** Turn on Extensible HTTP Priorities by default. */
394#define LSQUIC_DF_EXT_HTTP_PRIO 1
395
396/** By default, incoming packet size is not limited. */
397#define LSQUIC_DF_MAX_UDP_PAYLOAD_SIZE_RX 0
398
399/**
400 * By default, greasing the QUIC bit is enabled (if peer sent
401 * the "grease_quic_bit" transport parameter).
402 */
403#define LSQUIC_DF_GREASE_QUIC_BIT 1
404
405/** By default, DPLPMTUD is enabled */
406#define LSQUIC_DF_DPLPMTUD 1
407
408/** By default, this value is left up to the engine. */
409#define LSQUIC_DF_BASE_PLPMTU 0
410
411/** By default, this value is left up to the engine. */
412#define LSQUIC_DF_MAX_PLPMTU 0
413
414/** By default, drop no-progress connections after 60 seconds on the server */
415#define LSQUIC_DF_NOPROGRESS_TIMEOUT_SERVER 60
416
417/** By default, do not use no-progress timeout on the client */
418#define LSQUIC_DF_NOPROGRESS_TIMEOUT_CLIENT 0
419
420/** By default, we use the minimum timer of 1000 milliseconds */
421#define LSQUIC_DF_MTU_PROBE_TIMER 1000
422
423/** By default, calling on_close() is not delayed */
424#define LSQUIC_DF_DELAY_ONCLOSE 0
425
426/**
427 * By default, maximum batch size is not specified, leaving it up to the
428 * library.
429 */
430#define LSQUIC_DF_MAX_BATCH_SIZE 0
431
432/** Transport parameter sanity checks are performed by default. */
433#define LSQUIC_DF_CHECK_TP_SANITY 1
434
435struct lsquic_engine_settings {
436    /**
437     * This is a bit mask wherein each bit corresponds to a value in
438     * enum lsquic_version.  Client starts negotiating with the highest
439     * version and goes down.  Server supports either of the versions
440     * specified here.
441     *
442     * This setting applies to both Google and IETF QUIC.
443     *
444     * @see lsquic_version
445     */
446    unsigned        es_versions;
447
448    /**
449     * Initial default CFCW.
450     *
451     * In server mode, per-connection values may be set lower than
452     * this if resources are scarce.
453     *
454     * Do not set es_cfcw and es_sfcw lower than @ref LSQUIC_MIN_FCW.
455     *
456     * @see es_max_cfcw
457     */
458    unsigned        es_cfcw;
459
460    /**
461     * Initial default SFCW.
462     *
463     * In server mode, per-connection values may be set lower than
464     * this if resources are scarce.
465     *
466     * Do not set es_cfcw and es_sfcw lower than @ref LSQUIC_MIN_FCW.
467     *
468     * @see es_max_sfcw
469     */
470    unsigned        es_sfcw;
471
472    /**
473     * This value is used to specify maximum allowed value CFCW is allowed
474     * to reach due to window auto-tuning.  By default, this value is zero,
475     * which means that CFCW is not allowed to increase from its initial
476     * value.
477     *
478     * This setting is applicable to both gQUIC and IETF QUIC.
479     *
480     * @see es_cfcw, @see es_init_max_data.
481     */
482    unsigned        es_max_cfcw;
483
484    /**
485     * This value is used to specify the maximum value stream flow control
486     * window is allowed to reach due to auto-tuning.  By default, this
487     * value is zero, meaning that auto-tuning is turned off.
488     *
489     * This setting is applicable to both gQUIC and IETF QUIC.
490     *
491     * @see es_sfcw, @see es_init_max_stream_data_bidi_remote,
492     * @see es_init_max_stream_data_bidi_local.
493     */
494    unsigned        es_max_sfcw;
495
496    /** MIDS */
497    unsigned        es_max_streams_in;
498
499    /**
500     * Handshake timeout in microseconds.
501     *
502     * For client, this can be set to an arbitrary value (zero turns the
503     * timeout off).
504     *
505     * For server, this value is limited to about 16 seconds.  Do not set
506     * it to zero.
507     */
508    unsigned long   es_handshake_to;
509
510    /** ICSL in microseconds; GQUIC only */
511    unsigned long   es_idle_conn_to;
512
513    /**
514     * When true, CONNECTION_CLOSE is not sent when connection times out.
515     * The server will also not send a reply to client's CONNECTION_CLOSE.
516     *
517     * Corresponds to SCLS (silent close) gQUIC option.
518     */
519    int             es_silent_close;
520
521    /**
522     * This corresponds to SETTINGS_MAX_HEADER_LIST_SIZE
523     * (RFC 7540, Section 6.5.2).  0 means no limit.  Defaults
524     * to @ref LSQUIC_DF_MAX_HEADER_LIST_SIZE.
525     */
526    unsigned        es_max_header_list_size;
527
528    /** UAID -- User-Agent ID.  Defaults to @ref LSQUIC_DF_UA. */
529    const char     *es_ua;
530
531    /**
532     * More parameters for server
533     */
534    uint64_t        es_sttl; /* SCFG TTL in seconds */
535
536    uint32_t        es_pdmd; /* One fixed value X509 */
537    uint32_t        es_aead; /* One fixed value AESG */
538    uint32_t        es_kexs; /* One fixed value C255 */
539
540    /* Maximum number of incoming connections in inchoate state.  This is
541     * only applicable in server mode.
542     */
543    unsigned        es_max_inchoate;
544
545    /**
546     * Setting this value to 0 means that
547     *
548     * For client:
549     *  a) we send a SETTINGS frame to indicate that we do not support server
550     *     push; and
551     *  b) All incoming pushed streams get reset immediately.
552     * (For maximum effect, set es_max_streams_in to 0.)
553     *
554     * For server:
555     *  lsquic_conn_push_stream() will return -1.
556     */
557    int             es_support_push;
558
559    /**
560     * If set to true value, the server will not include connection ID in
561     * outgoing packets if client's CHLO specifies TCID=0.
562     *
563     * For client, this means including TCID=0 into CHLO message.  Note that
564     * in this case, the engine tracks connections by the
565     * (source-addr, dest-addr) tuple, thereby making it necessary to create
566     * a socket for each connection.
567     *
568     * This option has no effect in Q046 and Q050, as the server never includes
569     * CIDs in the short packets.
570     *
571     * This setting is applicable to gQUIC only.
572     *
573     * The default is @ref LSQUIC_DF_SUPPORT_TCID0.
574     */
575    int             es_support_tcid0;
576
577    /**
578     * Q037 and higher support "No STOP_WAITING frame" mode.  When set, the
579     * client will send NSTP option in its Client Hello message and will not
580     * sent STOP_WAITING frames, while ignoring incoming STOP_WAITING frames,
581     * if any.  Note that if the version negotiation happens to downgrade the
582     * client below Q037, this mode will *not* be used.
583     *
584     * This option does not affect the server, as it must support NSTP mode
585     * if it was specified by the client.
586     *
587     * This setting is applicable to gQUIC only.
588     */
589    int             es_support_nstp;
590
591    /**
592     * If set to true value, the library will drop connections when it
593     * receives corresponding Public Reset packet.  The default is to
594     * ignore these packets.
595     *
596     * The default is @ref LSQUIC_DF_HONOR_PRST.
597     */
598    int             es_honor_prst;
599
600    /**
601     * If set to true value, the library will send Public Reset packets
602     * in response to incoming packets with unknown Connection IDs.
603     * The default is @ref LSQUIC_DF_SEND_PRST.
604     */
605    int             es_send_prst;
606
607    /**
608     * A non-zero value enables internal checks that identify suspected
609     * infinite loops in user @ref on_read and @ref on_write callbacks
610     * and break them.  An infinite loop may occur if user code keeps
611     * on performing the same operation without checking status, e.g.
612     * reading from a closed stream etc.
613     *
614     * The value of this parameter is as follows: should a callback return
615     * this number of times in a row without making progress (that is,
616     * reading, writing, or changing stream state), loop break will occur.
617     *
618     * The defaut value is @ref LSQUIC_DF_PROGRESS_CHECK.
619     */
620    unsigned        es_progress_check;
621
622    /**
623     * A non-zero value make stream dispatch its read-write events once
624     * per call.
625     *
626     * When zero, read and write events are dispatched until the stream
627     * is no longer readable or writeable, respectively, or until the
628     * user signals unwillingness to read or write using
629     * @ref lsquic_stream_wantread() or @ref lsquic_stream_wantwrite()
630     * or shuts down the stream.
631     *
632     * This also applies to the on_dg_write() callback.
633     *
634     * The default value is @ref LSQUIC_DF_RW_ONCE.
635     */
636    int             es_rw_once;
637
638    /**
639     * If set, this value specifies the number of microseconds that
640     * @ref lsquic_engine_process_conns() and
641     * @ref lsquic_engine_send_unsent_packets() are allowed to spend
642     * before returning.
643     *
644     * This is not an exact science and the connections must make
645     * progress, so the deadline is checked after all connections get
646     * a chance to tick (in the case of @ref lsquic_engine_process_conns())
647     * and at least one batch of packets is sent out.
648     *
649     * When processing function runs out of its time slice, immediate
650     * calls to @ref lsquic_engine_has_unsent_packets() return false.
651     *
652     * The default value is @ref LSQUIC_DF_PROC_TIME_THRESH.
653     */
654    unsigned        es_proc_time_thresh;
655
656    /**
657     * If set to true, packet pacing is implemented per connection.
658     *
659     * The default value is @ref LSQUIC_DF_PACE_PACKETS.
660     */
661    int             es_pace_packets;
662
663    /**
664     * Clock granularity information is used by the pacer.  The value
665     * is in microseconds; default is @ref LSQUIC_DF_CLOCK_GRANULARITY.
666     */
667    unsigned        es_clock_granularity;
668
669    /**
670     * Congestion control algorithm to use.
671     *
672     *  0:  Use default (@ref LSQUIC_DF_CC_ALGO)
673     *  1:  Cubic
674     *  2:  BBRv1
675     *  3:  Adaptive (Cubic or BBRv1)
676     */
677    unsigned        es_cc_algo;
678
679    /**
680     * Congestion controller RTT threshold in microseconds.
681     *
682     * Adaptive congestion control uses BBRv1 until RTT is determined.  At
683     * that point a permanent choice of congestion controller is made. If
684     * RTT is smaller than or equal to es_cc_rtt_thresh, congestion
685     * controller is switched to Cubic; otherwise, BBRv1 is picked.
686     *
687     * The default value is @ref LSQUIC_DF_CC_RTT_THRESH.
688     */
689    unsigned        es_cc_rtt_thresh;
690
691    /**
692     * No progress timeout.
693     *
694     * If connection does not make progress for this number of seconds, the
695     * connection is dropped.  Here, progress is defined as user streams
696     * being written to or read from.
697     *
698     * If this value is zero, this timeout is disabled.
699     *
700     * Default value is @ref LSQUIC_DF_NOPROGRESS_TIMEOUT_SERVER in server
701     * mode and @ref LSQUIC_DF_NOPROGRESS_TIMEOUT_CLIENT in client mode.
702     */
703    unsigned        es_noprogress_timeout;
704
705    /* The following settings are specific to IETF QUIC. */
706    /* vvvvvvvvvvv */
707
708    /**
709     * Initial max data.
710     *
711     * This is a transport parameter.
712     *
713     * Depending on the engine mode, the default value is either
714     * @ref LSQUIC_DF_INIT_MAX_DATA_CLIENT or
715     * @ref LSQUIC_DF_INIT_MAX_DATA_SERVER.
716     */
717    unsigned        es_init_max_data;
718
719    /**
720     * Initial maximum amount of stream data allowed to be sent on streams
721     * created by remote end (peer).
722     *
723     * This is a transport parameter.
724     *
725     * Depending on the engine mode, the default value is either
726     * @ref LSQUIC_DF_INIT_MAX_STREAM_DATA_BIDI_REMOTE_CLIENT or
727     * @ref LSQUIC_DF_INIT_MAX_STREAM_DATA_BIDI_REMOTE_SERVER.
728     */
729    unsigned        es_init_max_stream_data_bidi_remote;
730
731    /**
732     * Initial maximum amount of stream data allowed to be sent on streams
733     * created by remote end (peer).
734     *
735     * This is a transport parameter.
736     *
737     * Depending on the engine mode, the default value is either
738     * @ref LSQUIC_DF_INIT_MAX_STREAM_DATA_BIDI_LOCAL_CLIENT or
739     * @ref LSQUIC_DF_INIT_MAX_STREAM_DATA_BIDI_LOCAL_SERVER.
740     */
741    unsigned        es_init_max_stream_data_bidi_local;
742
743    /**
744     * Initial max stream data for unidirectional streams initiated
745     * by remote endpoint.
746     *
747     * This is a transport parameter.
748     *
749     * Depending on the engine mode, the default value is either
750     * @ref LSQUIC_DF_INIT_MAX_STREAM_DATA_UNI_CLIENT or
751     * @ref LSQUIC_DF_INIT_MAX_STREAM_DATA_UNI_SERVER.
752     */
753    unsigned        es_init_max_stream_data_uni;
754
755    /**
756     * Maximum initial number of bidirectional stream.
757     *
758     * This is a transport parameter.
759     *
760     * Default value is @ref LSQUIC_DF_INIT_MAX_STREAMS_BIDI.
761     */
762    unsigned        es_init_max_streams_bidi;
763
764    /**
765     * Maximum initial number of unidirectional stream.
766     *
767     * This is a transport parameter.
768     *
769     * Default value is @ref LSQUIC_DF_INIT_MAX_STREAMS_UNI_CLIENT or
770     * @ref LSQUIC_DF_INIT_MAX_STREAM_DATA_UNI_SERVER.
771     */
772    unsigned        es_init_max_streams_uni;
773
774    /**
775     * Idle connection timeout.
776     *
777     * This is a transport parameter.
778     *
779     * (Note: es_idle_conn_to is not reused because it is in microseconds,
780     * which, I now realize, was not a good choice.  Since it will be
781     * obsoleted some time after the switchover to IETF QUIC, we do not
782     * have to keep on using strange units.)
783     *
784     * Default value is @ref LSQUIC_DF_IDLE_TIMEOUT.
785     *
786     * Maximum value is 600 seconds.
787     */
788    unsigned        es_idle_timeout;
789
790    /**
791     * Ping period.  If set to non-zero value, the connection will generate and
792     * send PING frames in the absence of other activity.
793     *
794     * By default, the server does not send PINGs and the period is set to zero.
795     * The client's defaut value is @ref LSQUIC_DF_PING_PERIOD.
796     */
797    unsigned        es_ping_period;
798
799    /**
800     * Source Connection ID length.  Only applicable to the IETF QUIC
801     * versions.  Valid values are 0 through 20, inclusive.
802     *
803     * Default value is @ref LSQUIC_DF_SCID_LEN.
804     */
805    unsigned        es_scid_len;
806
807    /**
808     * Source Connection ID issuance rate.  Only applicable to the IETF QUIC
809     * versions.  This field is measured in CIDs per minute.  Using value 0
810     * indicates that there is no rate limit for CID issuance.
811     *
812     * Default value is @ref LSQUIC_DF_SCID_ISS_RATE.
813     */
814    unsigned        es_scid_iss_rate;
815
816    /**
817     * Maximum size of the QPACK dynamic table that the QPACK decoder will
818     * use.
819     *
820     * The default is @ref LSQUIC_DF_QPACK_DEC_MAX_SIZE.
821     */
822    unsigned        es_qpack_dec_max_size;
823
824    /**
825     * Maximum number of blocked streams that the QPACK decoder is willing
826     * to tolerate.
827     *
828     * The default is @ref LSQUIC_DF_QPACK_DEC_MAX_BLOCKED.
829     */
830    unsigned        es_qpack_dec_max_blocked;
831
832    /**
833     * Maximum size of the dynamic table that the encoder is willing to use.
834     * The actual size of the dynamic table will not exceed the minimum of
835     * this value and the value advertized by peer.
836     *
837     * The default is @ref LSQUIC_DF_QPACK_ENC_MAX_SIZE.
838     */
839    unsigned        es_qpack_enc_max_size;
840
841    /**
842     * Maximum number of blocked streams that the QPACK encoder is willing
843     * to risk.  The actual number of blocked streams will not exceed the
844     * minimum of this value and the value advertized by peer.
845     *
846     * The default is @ref LSQUIC_DF_QPACK_ENC_MAX_BLOCKED.
847     */
848    unsigned        es_qpack_enc_max_blocked;
849
850    /**
851     * Enable ECN support.
852     *
853     * The default is @ref LSQUIC_DF_ECN
854     */
855    int             es_ecn;
856
857    /**
858     * Allow peer to migrate connection.
859     *
860     * The default is @ref LSQUIC_DF_ALLOW_MIGRATION
861     */
862    int             es_allow_migration;
863
864    /**
865     * Use QL loss bits.  Allowed values are:
866     *  0:  Do not use loss bits
867     *  1:  Allow loss bits
868     *  2:  Allow and send loss bits
869     *
870     * Default value is @ref LSQUIC_DF_QL_BITS
871     */
872    int             es_ql_bits;
873
874    /**
875     * Enable spin bit.  Allowed values are 0 and 1.
876     *
877     * Default value is @ref LSQUIC_DF_SPIN
878     */
879    int             es_spin;
880
881    /**
882     * Enable delayed ACKs extension.  Allowed values are 0 and 1.
883     *
884     * Default value is @ref LSQUIC_DF_DELAYED_ACKS
885     */
886    int             es_delayed_acks;
887
888    /**
889     * Enable timestamps extension.  Allowed values are 0 and 1.
890     *
891     * Default value is @ref LSQUIC_DF_TIMESTAMPS
892     */
893    int             es_timestamps;
894
895    /**
896     * Maximum packet size we are willing to receive.  This is sent to
897     * peer in transport parameters: the library does not enforce this
898     * limit for incoming packets.
899     *
900     * If set to zero, limit is not set.
901     *
902     * Default value is @ref LSQUIC_DF_MAX_UDP_PAYLOAD_SIZE_RX
903     */
904    unsigned short  es_max_udp_payload_size_rx;
905
906    /**
907     * Enable the "QUIC bit grease" extension.  When set to a true value,
908     * lsquic will grease the QUIC bit on the outgoing QUIC packets if
909     * the peer sent the "grease_quic_bit" transport parameter.
910     *
911     * Default value is @ref LSQUIC_DF_GREASE_QUIC_BIT
912     */
913    int             es_grease_quic_bit;
914
915    /**
916     * If set to true value, enable DPLPMTUD -- Datagram Packetization
917     * Layer Path MTU Discovery.
918     *
919     * Default value is @ref LSQUIC_DF_DPLPMTUD
920     */
921    int             es_dplpmtud;
922
923    /**
924     * PLPMTU size expected to work for most paths.
925     *
926     * If set to zero, this value is calculated based on QUIC and IP versions.
927     *
928     * Default value is @ref LSQUIC_DF_BASE_PLPMTU.
929     */
930    unsigned short  es_base_plpmtu;
931
932    /**
933     * Largest PLPMTU size the engine will try.
934     *
935     * If set to zero, picking this value is left to the engine.
936     *
937     * Default value is @ref LSQUIC_DF_MAX_PLPMTU.
938     */
939    unsigned short  es_max_plpmtu;
940
941    /**
942     * This value specifies how long the DPLPMTUD probe timer is, in
943     * milliseconds.  [draft-ietf-tsvwg-datagram-plpmtud-17] says:
944     *
945     " PROBE_TIMER:  The PROBE_TIMER is configured to expire after a period
946     "    longer than the maximum time to receive an acknowledgment to a
947     "    probe packet.  This value MUST NOT be smaller than 1 second, and
948     "    SHOULD be larger than 15 seconds.  Guidance on selection of the
949     "    timer value are provided in section 3.1.1 of the UDP Usage
950     "    Guidelines [RFC8085].
951     *
952     * If set to zero, the default is used.
953     *
954     * Default value is @ref LSQUIC_DF_MTU_PROBE_TIMER.
955     */
956    unsigned        es_mtu_probe_timer;
957
958    /**
959     * Enable datagram extension.  Allowed values are 0 and 1.
960     *
961     * Default value is @ref LSQUIC_DF_DATAGRAMS
962     */
963    int             es_datagrams;
964
965    /**
966     * If set to true, changes in peer port are assumed to be due to a
967     * benign NAT rebinding and path characteristics -- MTU, RTT, and
968     * CC state -- are not reset.
969     *
970     * Default value is @ref LSQUIC_DF_OPTIMISTIC_NAT.
971     */
972    int             es_optimistic_nat;
973
974    /**
975     * If set to true, Extensible HTTP Priorities are enabled.  This
976     * is HTTP/3-only setting.
977     *
978     * Default value is @ref LSQUIC_DF_EXT_HTTP_PRIO
979     */
980    int             es_ext_http_prio;
981
982    /**
983     * If set to 1, QPACK statistics are logged per connection.
984     *
985     * If set to 2, QPACK experiments are run.  In this mode, encoder
986     * and decoder setting values are randomly selected (from the range
987     * [0, whatever is specified in es_qpack_(enc|dec)_*]) and these
988     * values along with compression ratio and user agent are logged at
989     * NOTICE level when connection is destroyed.  The purpose of these
990     * experiments is to use compression performance statistics to figure
991     * out a good set of default values.
992     *
993     * Default value is @ref LSQUIC_DF_QPACK_EXPERIMENT.
994     */
995    int             es_qpack_experiment;
996
997    /**
998     * Settings for the Packet Tolerance PID Controller (PTPC) used for
999     * the Delayed ACKs logic.  Periodicity is how often the number of
1000     * incoming ACKs is sampled.  Periodicity's units is the number of
1001     * RTTs. Target is the average number of incoming ACKs per RTT we
1002     * want to achieve.  Error threshold defines the range of error values
1003     * within which no action is taken.  For example, error threshold of
1004     * 0.03 means that adjustment actions will be taken only when the
1005     * error is outside of the [-0.03, 0.03] range.  Proportional and
1006     * integral gains have their usual meanings described here:
1007     *      https://en.wikipedia.org/wiki/PID_controller#Controller_theory
1008     *
1009     * The average is normalized as follows:
1010     *    AvgNormalized = Avg * e / Target      # Where 'e' is 2.71828...
1011     *
1012     * The error is then calculated as ln(AvgNormalized) - 1.  This gives
1013     * us a logarithmic scale that is convenient to use for adjustment
1014     * calculations.  The error divisor is used to calculate the packet
1015     * tolerance adjustment:
1016     *    Adjustment = Error / ErrorDivisor
1017     *
1018     * WARNING.  The library comes with sane defaults.  Only fiddle with
1019     * these knobs if you know what you are doing.
1020     */
1021    unsigned es_ptpc_periodicity;   /* LSQUIC_DF_PTPC_PERIODICITY */
1022    unsigned es_ptpc_max_packtol;   /* LSQUIC_DF_PTPC_MAX_PACKTOL */
1023    int      es_ptpc_dyn_target;    /* LSQUIC_DF_PTPC_DYN_TARGET */
1024    float    es_ptpc_target,        /* LSQUIC_DF_PTPC_TARGET */
1025             es_ptpc_prop_gain,     /* LSQUIC_DF_PTPC_PROP_GAIN */
1026             es_ptpc_int_gain,      /* LSQUIC_DF_PTPC_INT_GAIN */
1027             es_ptpc_err_thresh,    /* LSQUIC_DF_PTPC_ERR_THRESH */
1028             es_ptpc_err_divisor;   /* LSQUIC_DF_PTPC_ERR_DIVISOR */
1029
1030    /**
1031     * When set to true, the on_close() callback will be delayed until the
1032     * peer acknowledges all data sent on the stream.  (Or until the connection
1033     * is destroyed in some manner -- either explicitly closed by the user or
1034     * as a result of an engine shutdown.)
1035     *
1036     * Default value is @ref LSQUIC_DF_DELAY_ONCLOSE
1037     */
1038    int             es_delay_onclose;
1039
1040    /**
1041     * If set to a non-zero value, specified maximum batch size.  (The
1042     * batch of packets passed to @ref ea_packets_out() callback).  Must
1043     * be no larger than 1024.
1044     *
1045     * Default value is @ref LSQUIC_DF_MAX_BATCH_SIZE
1046     */
1047    unsigned        es_max_batch_size;
1048
1049    /**
1050     * When true, sanity checks are performed on peer's transport parameter
1051     * values.  If some limits are set suspiciously low, the connection won't
1052     * be established.
1053     *
1054     * Default value is @ref LSQUIC_DF_CHECK_TP_SANITY
1055     */
1056    int             es_check_tp_sanity;
1057};
1058
1059/* Initialize `settings' to default values */
1060void
1061lsquic_engine_init_settings (struct lsquic_engine_settings *,
1062                             unsigned lsquic_engine_flags);
1063
1064/**
1065 * Check settings for errors.
1066 *
1067 * @param   settings    Settings struct.
1068 *
1069 * @param   flags       Engine flags.
1070 *
1071 * @param   err_buf     Optional pointer to buffer into which error string
1072 *                      is written.
1073
1074 * @param   err_buf_sz  Size of err_buf.  No more than this number of bytes
1075 *                      will be written to err_buf, including the NUL byte.
1076 *
1077 * @retval  0   Settings have no errors.
1078 * @retval -1   There are errors in settings.
1079 */
1080int
1081lsquic_engine_check_settings (const struct lsquic_engine_settings *settings,
1082                              unsigned lsquic_engine_flags,
1083                              char *err_buf, size_t err_buf_sz);
1084
1085struct lsquic_out_spec
1086{
1087    struct iovec          *iov;
1088    size_t                 iovlen;
1089    const struct sockaddr *local_sa;
1090    const struct sockaddr *dest_sa;
1091    void                  *peer_ctx;
1092    lsquic_conn_ctx_t     *conn_ctx;  /* will be NULL when sending out the first batch of handshake packets */
1093    int                    ecn;       /* Valid values are 0 - 3.  See RFC 3168 */
1094};
1095
1096/**
1097 * Returns number of packets successfully sent out or -1 on error.  -1 should
1098 * only be returned if no packets were sent out.  If -1 is returned or if the
1099 * return value is smaller than `n_packets_out', this indicates that sending
1100 * of packets is not possible.
1101 *
1102 * If not all packets could be sent out, errno is examined.  If it is not
1103 * EAGAIN or EWOULDBLOCK, the connection whose packet cause the error is
1104 * closed forthwith.
1105 *
1106 * No packets will be attempted to be sent out until
1107 * @ref lsquic_engine_send_unsent_packets() is called.
1108 */
1109typedef int (*lsquic_packets_out_f)(
1110    void                          *packets_out_ctx,
1111    const struct lsquic_out_spec  *out_spec,
1112    unsigned                       n_packets_out
1113);
1114
1115/**
1116 * The shared hash interface is used to share data between multiple LSQUIC
1117 * instances.
1118 */
1119struct lsquic_shared_hash_if
1120{
1121    /**
1122     * If you want your item to never expire, set `expiry' to zero.
1123     * Returns 0 on success, -1 on failure.
1124     *
1125     * If inserted successfully, `free()' will be called on `data' and 'key'
1126     * pointer when the element is deleted, whether due to expiration
1127     * or explicit deletion.
1128     */
1129    int (*shi_insert)(void *shi_ctx, void *key, unsigned key_sz,
1130                      void *data, unsigned data_sz, time_t expiry);
1131    /**
1132     * Returns 0 on success, -1 on failure.
1133     */
1134    int (*shi_delete)(void *shi_ctx, const void *key, unsigned key_sz);
1135
1136    /**
1137     * `data' is pointed to the result and `data_sz' is set to the
1138     * object size.  The implementation may choose to copy the object
1139     * into buffer pointed to by `data', so you should have it ready.
1140     *
1141     * @retval  1   found.
1142     * @retval  0   not found.
1143     * @retval -1   error (perhaps not enough room in `data' if copy was
1144     *                attempted).
1145     */
1146    int (*shi_lookup)(void *shi_ctx, const void *key, unsigned key_sz,
1147                                     void **data, unsigned *data_sz);
1148};
1149
1150/**
1151 * The packet out memory interface is used by LSQUIC to get buffers to
1152 * which outgoing packets will be written before they are passed to
1153 * ea_packets_out callback.
1154 *
1155 * If not specified, malloc() and free() are used.
1156 */
1157struct lsquic_packout_mem_if
1158{
1159    /**
1160     * Allocate buffer for sending.
1161     */
1162    void *  (*pmi_allocate) (void *pmi_ctx, void *peer_ctx, lsquic_conn_ctx_t *, unsigned short sz,
1163                                                                char is_ipv6);
1164    /**
1165     * This function is used to release the allocated buffer after it is
1166     * sent via @ref ea_packets_out.
1167     */
1168    void    (*pmi_release)  (void *pmi_ctx, void *peer_ctx, void *buf,
1169                                                                char is_ipv6);
1170    /**
1171     * If allocated buffer is not going to be sent, return it to the caller
1172     * using this function.
1173     */
1174    void    (*pmi_return)  (void *pmi_ctx, void *peer_ctx, void *buf,
1175                                                                char is_ipv6);
1176};
1177
1178typedef void (*lsquic_cids_update_f)(void *ctx, void **peer_ctx,
1179                                const lsquic_cid_t *cids, unsigned n_cids);
1180
1181struct stack_st_X509;
1182
1183enum lsquic_hsi_flag {
1184    /**
1185     * Turn HTTP/1.x mode on or off.  In this mode, decoded name and value
1186     * pair are separated by ": " and "\r\n" is appended to the end of the
1187     * string.  By default, this mode is off.
1188     */
1189    LSQUIC_HSI_HTTP1X          = 1 << 1,
1190    /** Include name hash into lsxpack_header */
1191    LSQUIC_HSI_HASH_NAME       = 1 << 2,
1192    /** Include nameval hash into lsxpack_header */
1193    LSQUIC_HSI_HASH_NAMEVAL    = 1 << 3,
1194};
1195
1196struct lsquic_hset_if
1197{
1198    /**
1199     * Create a new header set.  This object is (and must be) fetched from a
1200     * stream by calling @ref lsquic_stream_get_hset() before the stream can
1201     * be read.
1202     *
1203     * `stream' may be set to NULL in server mode.
1204     */
1205    void * (*hsi_create_header_set)(void *hsi_ctx, lsquic_stream_t *stream,
1206                                    int is_push_promise);
1207    /**
1208     * Return a header set prepared for decoding.  If `hdr' is NULL, this
1209     * means return a new structure with at least `space' bytes available
1210     * in the decoder buffer.  On success, a newly prepared header is
1211     * returned.
1212     *
1213     * If `hdr' is not NULL, it means there was not enough decoder buffer
1214     * and it must be increased to at least `space' bytes.  `buf', `val_len',
1215     * and `name_offset' member of the `hdr' structure may change.  On
1216     * success, the return value is the same as `hdr'.
1217     *
1218     * If NULL is returned, the space cannot be allocated.
1219     */
1220    struct lsxpack_header *
1221                        (*hsi_prepare_decode)(void *hdr_set,
1222                                              struct lsxpack_header *hdr,
1223                                              size_t space);
1224    /**
1225     * Process new header.  Return 0 on success, a positive value if a header
1226     * error occured, or a negative value on any other error.
1227     *
1228     * A positive return value will result in cancellation of associated
1229     * stream.
1230     *
1231     * A negative return value will result in connection being aborted.
1232     *
1233     * `hdr_set' is the header set object returned by
1234     * @ref hsi_create_header_set().
1235     *
1236     * `hdr' is the header returned by @ref `hsi_prepare_decode'.
1237     *
1238     * If `hdr' is NULL, this means that no more header are going to be
1239     * added to the set.
1240     */
1241    int (*hsi_process_header)(void *hdr_set, struct lsxpack_header *hdr);
1242    /**
1243     * Discard header set.  This is called for unclaimed header sets and
1244     * header sets that had an error.
1245     */
1246    void                (*hsi_discard_header_set)(void *hdr_set);
1247    /**
1248     * These flags specify properties of decoded headers passed to
1249     * hsi_process_header().  This is only applicable to QPACK headers;
1250     * HPACK library header properties are based on compilation, not
1251     * run-time, options.
1252     */
1253    enum lsquic_hsi_flag hsi_flags;
1254};
1255
1256/**
1257 * This struct contains a list of all callbacks that are used by the engine
1258 * to communicate with the user code.  Most of these are optional, while
1259 * the following are mandatory:
1260 *
1261 *  @ref ea_stream_if       The stream interface.
1262 *  @ref ea_packets_out     Function to send packets.
1263 *  @ref ea_lookup_cert     Function to look up certificates by SNI (used
1264 *                            in server mode).
1265 *
1266 * A pointer to this structure is passed to engine constructor
1267 * @ref lsquic_engine_new().
1268 */
1269struct lsquic_engine_api
1270{
1271    const struct lsquic_engine_settings *ea_settings;   /* Optional */
1272    /** Stream interface is required to manage connections and streams. */
1273    const struct lsquic_stream_if       *ea_stream_if;
1274    void                                *ea_stream_if_ctx;
1275    /** Function to send packets out is required. */
1276    lsquic_packets_out_f                 ea_packets_out;
1277    void                                *ea_packets_out_ctx;
1278    /** Function to look up certificates by SNI is used in server mode. */
1279    lsquic_lookup_cert_f                 ea_lookup_cert;
1280    void                                *ea_cert_lu_ctx;
1281    /** Mandatory callback for server, optional for client. */
1282    struct ssl_ctx_st *                (*ea_get_ssl_ctx)(void *peer_ctx,
1283                                                const struct sockaddr *local);
1284    /**
1285     * Shared hash interface is optional.  If set to zero, performance of
1286     * multiple LSQUIC instances will be degraded.
1287     */
1288    const struct lsquic_shared_hash_if  *ea_shi;
1289    void                                *ea_shi_ctx;
1290    /**
1291     * Memory interface is optional.
1292     */
1293    const struct lsquic_packout_mem_if  *ea_pmi;
1294    void                                *ea_pmi_ctx;
1295    /**
1296     * Optional interface to report new and old source connection IDs.
1297     */
1298    lsquic_cids_update_f                 ea_new_scids;
1299    lsquic_cids_update_f                 ea_live_scids;
1300    lsquic_cids_update_f                 ea_old_scids;
1301    void                                *ea_cids_update_ctx;
1302    /**
1303     * Function to verify server certificate.  The chain contains at least
1304     * one element.  The first element in the chain is the server
1305     * certificate.  The chain belongs to the library.  If you want to
1306     * retain it, call sk_X509_up_ref().
1307     *
1308     * 0 is returned on success, -1 on error.
1309     *
1310     * If the function pointer is not set, no verification is performed
1311     * (the connection is allowed to proceed).
1312     */
1313    int                                (*ea_verify_cert)(void *verify_ctx,
1314                                                struct stack_st_X509 *chain);
1315    void                                *ea_verify_ctx;
1316
1317    /**
1318     * Optional header set interface.  If not specified, the incoming headers
1319     * are converted to HTTP/1.x format and are read from stream and have to
1320     * be parsed again.
1321     */
1322    const struct lsquic_hset_if         *ea_hsi_if;
1323    void                                *ea_hsi_ctx;
1324
1325    /**
1326     * If set, engine will print cumulative connection statistics to this
1327     * file just before it is destroyed.  (Must be compiled with
1328     * -DLSQUIC_CONN_STATS=1).
1329     */
1330    void /* FILE, really */             *ea_stats_fh;
1331
1332    /**
1333     * The optional ALPN string is used by the client if @ref LSENG_HTTP
1334     * is not set.
1335     */
1336    const char                          *ea_alpn;
1337
1338    /**
1339     * Optional interface to control the creation of connection IDs
1340     */
1341    void                               (*ea_generate_scid)(void *ctx,
1342                                lsquic_conn_t *, lsquic_cid_t *, unsigned);
1343    /** Passed to ea_generate_scid() */
1344    void                                *ea_gen_scid_ctx;
1345};
1346
1347/**
1348 * Create new engine.
1349 *
1350 * @param   lsquic_engine_flags     A bitmask of @ref LSENG_SERVER and
1351 *                                  @ref LSENG_HTTP
1352 *
1353 * @param   api                     Required parameter that specifies
1354 *                                    various callbacks.
1355 *
1356 * The engine can be instantiated either in server mode (when LSENG_SERVER
1357 * is set) or client mode.  If you need both server and client in your
1358 * program, create two engines (or as many as you'd like).
1359 */
1360lsquic_engine_t *
1361lsquic_engine_new (unsigned lsquic_engine_flags,
1362                   const struct lsquic_engine_api *api);
1363
1364/**
1365 * Create a client connection to peer identified by `peer_ctx'.
1366 *
1367 * To let the engine specify QUIC version, use N_LSQVER.  If session resumption
1368 * information is supplied, version is picked from there instead.
1369 *
1370 * If `base_plpmtu' is set to zero, it is selected based on the
1371 * engine settings, QUIC version, and IP version.
1372 */
1373lsquic_conn_t *
1374lsquic_engine_connect (lsquic_engine_t *, enum lsquic_version,
1375                       const struct sockaddr *local_sa,
1376                       const struct sockaddr *peer_sa,
1377                       void *peer_ctx, lsquic_conn_ctx_t *conn_ctx,
1378                       const char *hostname, unsigned short base_plpmtu,
1379                       const unsigned char *sess_resume, size_t sess_resume_len,
1380                       /** Resumption token: optional */
1381                       const unsigned char *token, size_t token_sz);
1382
1383/**
1384 * Pass incoming packet to the QUIC engine.  This function can be called
1385 * more than once in a row.  After you add one or more packets, call
1386 * lsquic_engine_process_conns() to schedule output, if any.
1387 *
1388 * @retval  0   Packet was processed by a real connection.
1389 *
1390 * @retval  1   Packet was handled successfully, but not by a connection.
1391 *              This may happen with version negotiation and public reset
1392 *              packets as well as some packets that may be ignored.
1393 *
1394 * @retval -1   An error occurred.  Possible reasons are failure to allocate
1395 *              memory and invalid @param sa_local in client mode.
1396 */
1397int
1398lsquic_engine_packet_in (lsquic_engine_t *,
1399        const unsigned char *packet_in_data, size_t packet_in_size,
1400        const struct sockaddr *sa_local, const struct sockaddr *sa_peer,
1401        void *peer_ctx, int ecn);
1402
1403/**
1404 * Process tickable connections.  This function must be called often enough so
1405 * that packets and connections do not expire.
1406 */
1407void
1408lsquic_engine_process_conns (lsquic_engine_t *engine);
1409
1410/**
1411 * Returns true if engine has some unsent packets.  This happens if
1412 * @ref ea_packets_out() could not send everything out or if processing
1413 * deadline was exceeded (see @ref es_proc_time_thresh).
1414 */
1415int
1416lsquic_engine_has_unsent_packets (lsquic_engine_t *engine);
1417
1418/**
1419 * Send out as many unsent packets as possibe: until we are out of unsent
1420 * packets or until @ref ea_packets_out() fails.
1421 *
1422 * If @ref ea_packets_out() does fail cannot send all packets, this
1423 * function must be called to signify that sending of packets is possible
1424 * again.
1425 */
1426void
1427lsquic_engine_send_unsent_packets (lsquic_engine_t *engine);
1428
1429/**
1430 * Destroy engine and all connections and streams in it and free all
1431 * memory associated with this engine.
1432 */
1433void
1434lsquic_engine_destroy (lsquic_engine_t *);
1435
1436/** Return max allowed outbound streams less current outbound streams. */
1437unsigned
1438lsquic_conn_n_avail_streams (const lsquic_conn_t *);
1439
1440/**
1441 * Create a new request stream.  This causes @ref on_new_stream() callback
1442 * to be called.  If creating more requests is not permitted at the moment
1443 * (due to number of concurrent streams limit), stream creation is registered
1444 * as "pending" and the stream is created later when number of streams dips
1445 * under the limit again.  Any number of pending streams can be created.
1446 * Use @ref lsquic_conn_n_pending_streams() and
1447 * @ref lsquic_conn_cancel_pending_streams() to manage pending streams.
1448 *
1449 * If connection is going away, @ref on_new_stream() is called with the
1450 * stream parameter set to NULL.
1451 */
1452void
1453lsquic_conn_make_stream (lsquic_conn_t *);
1454
1455/** Return number of delayed streams currently pending */
1456unsigned
1457lsquic_conn_n_pending_streams (const lsquic_conn_t *);
1458
1459/** Cancel `n' pending streams.  Returns new number of pending streams. */
1460unsigned
1461lsquic_conn_cancel_pending_streams (lsquic_conn_t *, unsigned n);
1462
1463/**
1464 * Mark connection as going away: send GOAWAY frame and do not accept
1465 * any more incoming streams, nor generate streams of our own.
1466 *
1467 * Only applicable to HTTP/3 and GQUIC connections.  Otherwise a no-op.
1468 */
1469void
1470lsquic_conn_going_away (lsquic_conn_t *);
1471
1472/**
1473 * This forces connection close.  on_conn_closed and on_close callbacks
1474 * will be called.
1475 */
1476void
1477lsquic_conn_close (lsquic_conn_t *);
1478
1479/**
1480 * Set whether you want to read from stream.  If @param is_want is true,
1481 * @ref on_read() will be called when there is readable data in the
1482 * stream.  If @param is false, @ref on_read() will not be called.
1483 *
1484 * Returns previous value of this flag.
1485 */
1486int
1487lsquic_stream_wantread (lsquic_stream_t *s, int is_want);
1488
1489/**
1490 * Read up to @param len bytes from stream into @param buf.  Returns number
1491 * of bytes read or -1 on error, in which case errno is set.  Possible
1492 * errno values:
1493 *
1494 *  EBADF           The stream is closed.
1495 *  ECONNRESET      The stream has been reset.
1496 *  EWOULDBLOCK     There is no data to be read.
1497 *
1498 * Return value of zero indicates EOF.
1499 */
1500ssize_t
1501lsquic_stream_read (lsquic_stream_t *s, void *buf, size_t len);
1502
1503/**
1504 * Similar to @ref lsquic_stream_read(), but reads data into @param vec.
1505 */
1506ssize_t
1507lsquic_stream_readv (lsquic_stream_t *s, const struct iovec *vec, int iovcnt);
1508
1509/**
1510 * This function allows user-supplied callback to read the stream contents.
1511 * It is meant to be used for zero-copy stream processing.
1512 *
1513 * Return value and errors are same as in @ref lsquic_stream_read().
1514 */
1515ssize_t
1516lsquic_stream_readf (lsquic_stream_t *s,
1517    /**
1518     * The callback takes four parameters:
1519     *  - Pointer to user-supplied context;
1520     *  - Pointer to the data;
1521     *  - Data size (can be zero); and
1522     *  - Indicator whether the FIN follows the data.
1523     *
1524     * The callback returns number of bytes processed.  If this number is zero
1525     * or is smaller than `len', reading from stream stops.
1526     */
1527    size_t (*readf)(void *ctx, const unsigned char *buf, size_t len, int fin),
1528    void *ctx);
1529
1530/**
1531 * Set whether you want to write to stream.  If @param is_want is true,
1532 * @ref on_write() will be called when it is possible to write data to
1533 * the stream.  If @param is false, @ref on_write() will not be called.
1534 *
1535 * Returns previous value of this flag.
1536 */
1537int
1538lsquic_stream_wantwrite (lsquic_stream_t *s, int is_want);
1539
1540/**
1541 * Write `len' bytes to the stream.  Returns number of bytes written, which
1542 * may be smaller that `len'.
1543 *
1544 * A negative return value indicates a serious error (the library is likely
1545 * to have aborted the connection because of it).
1546 */
1547ssize_t
1548lsquic_stream_write (lsquic_stream_t *s, const void *buf, size_t len);
1549
1550/**
1551 * Like @ref lsquic_stream_write(), but read data from @param vec.
1552 */
1553ssize_t
1554lsquic_stream_writev (lsquic_stream_t *s, const struct iovec *vec, int count);
1555
1556/**
1557 * Write to streams using a single call to a preadv-like function.
1558 */
1559ssize_t
1560lsquic_stream_pwritev (lsquic_stream_t *s,
1561    ssize_t (*preadv)(void *user_data, const struct iovec *iov, int iovcnt),
1562    void *user_data, size_t n_to_write);
1563
1564/**
1565 * Used as argument to @ref lsquic_stream_writef()
1566 */
1567struct lsquic_reader
1568{
1569    /**
1570     * Not a ssize_t because the read function is not supposed to return
1571     * an error.  If an error occurs in the read function (for example, when
1572     * reading from a file fails), it is supposed to deal with the error
1573     * itself.
1574     */
1575    size_t (*lsqr_read) (void *lsqr_ctx, void *buf, size_t count);
1576    /**
1577     * Return number of bytes remaining in the reader.
1578     */
1579    size_t (*lsqr_size) (void *lsqr_ctx);
1580    void    *lsqr_ctx;
1581};
1582
1583/**
1584 * Write to stream using @ref lsquic_reader.  This is the most generic of
1585 * the write functions -- @ref lsquic_stream_write() and
1586 * @ref lsquic_stream_writev() utilize the same mechanism.
1587 *
1588 * @retval Number of bytes written or -1 on error.
1589 */
1590ssize_t
1591lsquic_stream_writef (lsquic_stream_t *, struct lsquic_reader *);
1592
1593/**
1594 * Flush any buffered data.  This triggers packetizing even a single byte
1595 * into a separate frame.  Flushing a closed stream is an error.
1596 *
1597 * @retval  0   Success
1598 * @retval -1   Failure
1599 */
1600int
1601lsquic_stream_flush (lsquic_stream_t *s);
1602
1603/**
1604 * @typedef lsquic_http_headers_t
1605 * @brief HTTP header list structure. Contains a list of HTTP headers in key/value pairs.
1606 * used in API functions to pass headers.
1607 */
1608struct lsquic_http_headers
1609{
1610    int                     count;
1611    struct lsxpack_header  *headers;
1612};
1613
1614/**
1615 * Send headers in @param headers.  This function must be called before
1616 * writing to the stream.  The value of @param eos is ignored in IETF QUIC.
1617 */
1618int
1619lsquic_stream_send_headers (lsquic_stream_t *s,
1620                               const lsquic_http_headers_t *headers, int eos);
1621
1622/**
1623 * Get header set associated with the stream.  The header set is created by
1624 * @ref hsi_create_header_set() callback.  After this call, the ownership of
1625 * the header set is transferred to the caller.
1626 *
1627 * This call must precede calls to @ref lsquic_stream_read() and
1628 * @ref lsquic_stream_readv().
1629 *
1630 * If the optional header set interface (@ref ea_hsi_if) is not specified,
1631 * this function returns NULL.
1632 */
1633void *
1634lsquic_stream_get_hset (lsquic_stream_t *);
1635
1636/**
1637 * A server may push a stream.  This call creates a new stream in reference
1638 * to stream `s'.  It will behave as if the client made a request: it will
1639 * trigger on_new_stream() event and it can be used as a regular client-
1640 * initiated stream.
1641 *
1642 * `hdr_set' must be set.  It is passed as-is to @lsquic_stream_get_hset.
1643 *
1644 * @retval  0   Stream pushed successfully.
1645 * @retval  1   Stream push failed because it is disabled or because we hit
1646 *                stream limit or connection is going away.
1647 * @retval -1   Stream push failed because of an internal error.
1648 */
1649int
1650lsquic_conn_push_stream (lsquic_conn_t *c, void *hdr_set, lsquic_stream_t *s,
1651    const lsquic_http_headers_t *headers);
1652
1653/**
1654 * Only makes sense in server mode: the client cannot push a stream and this
1655 * function always returns false in client mode.
1656 */
1657int
1658lsquic_conn_is_push_enabled (lsquic_conn_t *);
1659
1660/** Possible values for how are 0, 1, and 2.  See shutdown(2). */
1661int lsquic_stream_shutdown(lsquic_stream_t *s, int how);
1662
1663int lsquic_stream_close(lsquic_stream_t *s);
1664
1665/**
1666 * Return true if peer has not ACKed all data written to the stream.  This
1667 * includes both packetized and buffered data.
1668 */
1669int
1670lsquic_stream_has_unacked_data (lsquic_stream_t *s);
1671
1672/**
1673 * Get certificate chain returned by the server.  This can be used for
1674 * server certificate verification.
1675 *
1676 * The caller releases the stack using sk_X509_free().
1677 */
1678struct stack_st_X509 *
1679lsquic_conn_get_server_cert_chain (lsquic_conn_t *);
1680
1681/** Returns ID of the stream */
1682lsquic_stream_id_t
1683lsquic_stream_id (const lsquic_stream_t *s);
1684
1685/**
1686 * Returns stream ctx associated with the stream.  (The context is what
1687 * is returned by @ref on_new_stream callback).
1688 */
1689lsquic_stream_ctx_t *
1690lsquic_stream_get_ctx (const lsquic_stream_t *s);
1691
1692/**
1693 * Set user-supplied context associated with the stream.
1694 */
1695void
1696lsquic_stream_set_ctx (lsquic_stream_t *stream, lsquic_stream_ctx_t *ctx);
1697
1698/** Returns true if this is a pushed stream */
1699int
1700lsquic_stream_is_pushed (const lsquic_stream_t *s);
1701
1702/**
1703 * Returns true if this stream was rejected, false otherwise.  Use this as
1704 * an aid to distinguish between errors.
1705 */
1706int
1707lsquic_stream_is_rejected (const lsquic_stream_t *s);
1708
1709/**
1710 * Refuse pushed stream.  Call it from @ref on_new_stream.
1711 *
1712 * No need to call lsquic_stream_close() after this.  on_close will be called.
1713 *
1714 * @see lsquic_stream_is_pushed
1715 */
1716int
1717lsquic_stream_refuse_push (lsquic_stream_t *s);
1718
1719/**
1720 * Get information associated with pushed stream:
1721 *
1722 * @param ref_stream_id   Stream ID in response to which push promise was
1723 *                            sent.
1724 * @param hdr_set         Header set.  This object was passed to or generated
1725 *                            by @ref lsquic_conn_push_stream().
1726 *
1727 * @retval   0  Success.
1728 * @retval  -1  This is not a pushed stream.
1729 */
1730int
1731lsquic_stream_push_info (const lsquic_stream_t *,
1732                         lsquic_stream_id_t *ref_stream_id, void **hdr_set);
1733
1734/** Return current priority of the stream */
1735unsigned lsquic_stream_priority (const lsquic_stream_t *s);
1736
1737/**
1738 * Set stream priority.  Valid priority values are 1 through 256, inclusive.
1739 * Lower value means higher priority.
1740 *
1741 * @retval   0  Success.
1742 * @retval  -1  Priority value is invalid.
1743 */
1744int lsquic_stream_set_priority (lsquic_stream_t *s, unsigned priority);
1745
1746/*
1747 * Definitions for Extensible HTTP Priorities:
1748 * https://tools.ietf.org/html/draft-ietf-httpbis-priority-01
1749 */
1750/* This is maximum *value* -- but it's the lowest *priority* */
1751#define LSQUIC_MAX_HTTP_URGENCY 7
1752#define LSQUIC_DEF_HTTP_URGENCY 3
1753#define LSQUIC_DEF_HTTP_INCREMENTAL 0
1754
1755struct lsquic_ext_http_prio
1756{
1757    unsigned char   urgency;
1758    signed char     incremental;
1759};
1760
1761/**
1762 * Get Extensible HTTP Priorities associated with the stream.
1763 *
1764 * Returns zero on success of a negative value on failure.  A failure occurs
1765 * if this is not an HTTP/3 stream or if Extensible HTTP Priorities haven't
1766 * been enabled.  See @ref es_ext_http_prio.
1767 */
1768int
1769lsquic_stream_get_http_prio (lsquic_stream_t *, struct lsquic_ext_http_prio *);
1770
1771/**
1772 * Set Extensible HTTP Priorities of the stream.
1773 *
1774 * Returns zero on success of a negative value on failure.  A failure occurs
1775 * if some internal error occured or if this is not an HTTP/3 stream or if
1776 * Extensible HTTP Priorities haven't been enabled.  See @ref es_ext_http_prio.
1777 */
1778int
1779lsquic_stream_set_http_prio (lsquic_stream_t *,
1780                                        const struct lsquic_ext_http_prio *);
1781
1782/**
1783 * Get a pointer to the connection object.  Use it with lsquic_conn_*
1784 * functions.
1785 */
1786lsquic_conn_t * lsquic_stream_conn(const lsquic_stream_t *s);
1787
1788/** Get connection ID */
1789const lsquic_cid_t *
1790lsquic_conn_id (const lsquic_conn_t *c);
1791
1792/** Get pointer to the engine */
1793lsquic_engine_t *
1794lsquic_conn_get_engine (lsquic_conn_t *c);
1795
1796int
1797lsquic_conn_get_sockaddr(lsquic_conn_t *c,
1798                const struct sockaddr **local, const struct sockaddr **peer);
1799
1800/* Returns previous value */
1801int
1802lsquic_conn_want_datagram_write (lsquic_conn_t *, int is_want);
1803
1804/* Get minimum datagram size.  By default, this value is zero. */
1805size_t
1806lsquic_conn_get_min_datagram_size (lsquic_conn_t *);
1807
1808/* Set minimum datagram size.  This is the minumum value of the buffer passed
1809 * to the on_dg_write() callback.
1810 */
1811int
1812lsquic_conn_set_min_datagram_size (lsquic_conn_t *, size_t sz);
1813
1814struct lsquic_logger_if {
1815    int     (*log_buf)(void *logger_ctx, const char *buf, size_t len);
1816};
1817
1818/**
1819 * Enumerate timestamp styles supported by LSQUIC logger mechanism.
1820 */
1821enum lsquic_logger_timestamp_style {
1822    /**
1823     * No timestamp is generated.
1824     */
1825    LLTS_NONE,
1826
1827    /**
1828     * The timestamp consists of 24 hours, minutes, seconds, and
1829     * milliseconds.  Example: 13:43:46.671
1830     */
1831    LLTS_HHMMSSMS,
1832
1833    /**
1834     * Like above, plus date, e.g: 2017-03-21 13:43:46.671
1835     */
1836    LLTS_YYYYMMDD_HHMMSSMS,
1837
1838    /**
1839     * This is Chrome-like timestamp used by proto-quic.  The timestamp
1840     * includes month, date, hours, minutes, seconds, and microseconds.
1841     *
1842     * Example: 1223/104613.946956 (instead of 12/23 10:46:13.946956).
1843     *
1844     * This is to facilitate reading two logs side-by-side.
1845     */
1846    LLTS_CHROMELIKE,
1847
1848    /**
1849     * The timestamp consists of 24 hours, minutes, seconds, and
1850     * microseconds.  Example: 13:43:46.671123
1851     */
1852    LLTS_HHMMSSUS,
1853
1854    /**
1855     * Date and time using microsecond resolution,
1856     * e.g: 2017-03-21 13:43:46.671123
1857     */
1858    LLTS_YYYYMMDD_HHMMSSUS,
1859
1860    N_LLTS
1861};
1862
1863/**
1864 * Call this if you want to do something with LSQUIC log messages, as they
1865 * are thrown out by default.
1866 */
1867void lsquic_logger_init(const struct lsquic_logger_if *, void *logger_ctx,
1868                        enum lsquic_logger_timestamp_style);
1869
1870/**
1871 * Set log level for all LSQUIC modules.  Acceptable values are debug, info,
1872 * notice, warning, error, alert, emerg, crit (case-insensitive).
1873 *
1874 * @retval  0   Success.
1875 * @retval -1   Failure: log_level is not valid.
1876 */
1877int
1878lsquic_set_log_level (const char *log_level);
1879
1880/**
1881 * E.g. "event=debug"
1882 */
1883int
1884lsquic_logger_lopt (const char *optarg);
1885
1886/**
1887 * Return the list of QUIC versions (as bitmask) this engine instance
1888 * supports.
1889 */
1890unsigned lsquic_engine_quic_versions (const lsquic_engine_t *);
1891
1892/**
1893 * This is one of the flags that can be passed to @ref lsquic_global_init.
1894 * Use it to initialize LSQUIC for use in client mode.
1895 */
1896#define LSQUIC_GLOBAL_CLIENT (1 << 0)
1897
1898/**
1899 * This is one of the flags that can be passed to @ref lsquic_global_init.
1900 * Use it to initialize LSQUIC for use in server mode.
1901 */
1902#define LSQUIC_GLOBAL_SERVER (1 << 1)
1903
1904/**
1905 * Initialize LSQUIC.  This must be called before any other LSQUIC function
1906 * is called.  Returns 0 on success and -1 on failure.
1907 *
1908 * @param flags     This a bitmask of @ref LSQUIC_GLOBAL_CLIENT and
1909 *                    @ref LSQUIC_GLOBAL_SERVER.  At least one of these
1910 *                    flags should be specified.
1911 *
1912 * @retval  0   Success.
1913 * @retval -1   Initialization failed.
1914 *
1915 * @see LSQUIC_GLOBAL_CLIENT
1916 * @see LSQUIC_GLOBAL_SERVER
1917 */
1918int
1919lsquic_global_init (int flags);
1920
1921/**
1922 * Clean up global state created by @ref lsquic_global_init.  Should be
1923 * called after all LSQUIC engine instances are gone.
1924 */
1925void
1926lsquic_global_cleanup (void);
1927
1928/**
1929 * Get QUIC version used by the connection.
1930 *
1931 * @see lsquic_version
1932 */
1933enum lsquic_version
1934lsquic_conn_quic_version (const lsquic_conn_t *c);
1935
1936/* Return keysize or -1 on error */
1937int
1938lsquic_conn_crypto_keysize (const lsquic_conn_t *c);
1939
1940/* Return algorithm keysize or -1 on error */
1941int
1942lsquic_conn_crypto_alg_keysize (const lsquic_conn_t *c);
1943
1944enum lsquic_crypto_ver
1945{
1946    LSQ_CRY_QUIC,
1947    LSQ_CRY_TLSv13,
1948};
1949
1950enum lsquic_crypto_ver
1951lsquic_conn_crypto_ver (const lsquic_conn_t *c);
1952
1953/* Return cipher or NULL on error */
1954const char *
1955lsquic_conn_crypto_cipher (const lsquic_conn_t *c);
1956
1957/** Translate string QUIC version to LSQUIC QUIC version representation */
1958enum lsquic_version
1959lsquic_str2ver (const char *str, size_t len);
1960
1961/** Translate ALPN (e.g. "h3", "h3-23", "h3-Q046") to LSQUIC enum */
1962enum lsquic_version
1963lsquic_alpn2ver (const char *alpn, size_t len);
1964
1965/**
1966 * This function closes all mini connections and marks all full connections
1967 * as going away.  In server mode, this also causes the engine to stop
1968 * creating new connections.
1969 */
1970void
1971lsquic_engine_cooldown (lsquic_engine_t *);
1972
1973/**
1974 * Get user-supplied context associated with the connection.
1975 */
1976lsquic_conn_ctx_t *
1977lsquic_conn_get_ctx (const lsquic_conn_t *);
1978
1979/**
1980 * Set user-supplied context associated with the connection.
1981 */
1982void
1983lsquic_conn_set_ctx (lsquic_conn_t *, lsquic_conn_ctx_t *);
1984
1985/**
1986 * Get peer context associated with the connection.
1987 */
1988void *
1989lsquic_conn_get_peer_ctx (lsquic_conn_t *, const struct sockaddr *local_sa);
1990
1991/** Get SNI sent by the client */
1992const char *
1993lsquic_conn_get_sni (lsquic_conn_t *);
1994
1995/**
1996 * Abort connection.
1997 */
1998void
1999lsquic_conn_abort (lsquic_conn_t *);
2000
2001/**
2002 * Helper function: convert list of versions as specified in the argument
2003 * bitmask to string that can be included as argument to "v=" part of the
2004 * Alt-Svc header.
2005 *
2006 * For example (1<<LSQVER_037)|(1<<LSQVER_038) => "37,38"
2007 *
2008 * This is only applicable to Google QUIC versions.
2009 */
2010const char *
2011lsquic_get_alt_svc_versions (unsigned versions);
2012
2013/**
2014 * Return a NULL-terminated list of HTTP/3 ALPNs, e.g "h3-17", "h3-18", "h3".
2015 */
2016const char *const *
2017lsquic_get_h3_alpns (unsigned versions);
2018
2019/**
2020 * Returns true if provided buffer could be a valid handshake-stage packet,
2021 * false otherwise.  Do not call this function if a connection has already
2022 * been established: it will return incorrect result.
2023 */
2024int
2025lsquic_is_valid_hs_packet (lsquic_engine_t *, const unsigned char *, size_t);
2026
2027/**
2028 * Parse cid from packet stored in `buf' and store it to `cid'.  Returns 0
2029 * on success and -1 on failure.
2030 */
2031int
2032lsquic_cid_from_packet (const unsigned char *, size_t bufsz, lsquic_cid_t *cid);
2033
2034/**
2035 * On success, offset to the CID is returned (a non-negative value).
2036 * `cid_len' is set to the length of the CID.  The server perspective
2037 * is assumed.  `server_cid_len' is set to the length of the CIDs that
2038 * server generates.
2039 *
2040 * On failure, a negative value is returned.
2041 */
2042int
2043lsquic_dcid_from_packet (const unsigned char *, size_t bufsz,
2044                                unsigned server_cid_len, unsigned *cid_len);
2045
2046/**
2047 * Returns true if there are connections to be processed, false otherwise.
2048 * If true, `diff' is set to the difference between the earliest advisory
2049 * tick time and now.  If the former is in the past, the value of `diff'
2050 * is negative.
2051 */
2052int
2053lsquic_engine_earliest_adv_tick (lsquic_engine_t *engine, int *diff);
2054
2055/**
2056 * Return number of connections whose advisory tick time is before current
2057 * time plus `from_now' microseconds from now.  `from_now' can be negative.
2058 */
2059unsigned
2060lsquic_engine_count_attq (lsquic_engine_t *engine, int from_now);
2061
2062enum LSQUIC_CONN_STATUS
2063{
2064    LSCONN_ST_HSK_IN_PROGRESS,
2065    LSCONN_ST_CONNECTED,
2066    LSCONN_ST_HSK_FAILURE,
2067    LSCONN_ST_GOING_AWAY,
2068    LSCONN_ST_TIMED_OUT,
2069    /* If es_honor_prst is not set, the connection will never get public
2070     * reset packets and this flag will not be set.
2071     */
2072    LSCONN_ST_RESET,
2073    LSCONN_ST_USER_ABORTED,
2074    LSCONN_ST_ERROR,
2075    LSCONN_ST_CLOSED,
2076    LSCONN_ST_PEER_GOING_AWAY,
2077    LSCONN_ST_VERNEG_FAILURE,
2078};
2079
2080enum LSQUIC_CONN_STATUS
2081lsquic_conn_status (lsquic_conn_t *, char *errbuf, size_t bufsz);
2082
2083extern const char *const
2084lsquic_ver2str[N_LSQVER];
2085
2086/* Return connection associated with this SSL object */
2087lsquic_conn_t *
2088lsquic_ssl_to_conn (const struct ssl_st *);
2089
2090/* Return session resumption information that can be used on subsequenct
2091 * connection as argument to lsquic_engine_connect().  Call from inside
2092 * SSL's new session callback.
2093 *
2094 * Returns 0 on success.  In this case, `buf' is made to point to newly
2095 * allocated memory containing `buf_sz' bytes.  It is the caller's
2096 * responsibility to free the memory.
2097 */
2098int
2099lsquic_ssl_sess_to_resume_info (struct ssl_st *, struct ssl_session_st *,
2100                                        unsigned char **buf, size_t *buf_sz);
2101
2102#ifdef __cplusplus
2103}
2104#endif
2105
2106#endif //__LSQUIC_H__
2107
2108