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