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