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