blob: be9dae928a260dab2eaf707d2de3c15d9a067f5b [file] [log] [blame]
/*
* HTTP/2 mux-demux for connections
*
* Copyright 2017 Willy Tarreau <w@1wt.eu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <common/cfgparse.h>
#include <common/config.h>
#include <common/h1.h>
#include <common/h2.h>
#include <common/hpack-dec.h>
#include <common/hpack-enc.h>
#include <common/hpack-tbl.h>
#include <common/htx.h>
#include <common/initcall.h>
#include <common/net_helper.h>
#include <proto/connection.h>
#include <proto/http_htx.h>
#include <proto/trace.h>
#include <proto/session.h>
#include <proto/stream.h>
#include <proto/stream_interface.h>
#include <types/session.h>
#include <eb32tree.h>
/* dummy streams returned for closed, error, refused, idle and states */
static const struct h2s *h2_closed_stream;
static const struct h2s *h2_error_stream;
static const struct h2s *h2_refused_stream;
static const struct h2s *h2_idle_stream;
/* Connection flags (32 bit), in h2c->flags */
#define H2_CF_NONE 0x00000000
/* Flags indicating why writing to the mux is blocked. */
#define H2_CF_MUX_MALLOC 0x00000001 // mux blocked on lack of connection's mux buffer
#define H2_CF_MUX_MFULL 0x00000002 // mux blocked on connection's mux buffer full
#define H2_CF_MUX_BLOCK_ANY 0x00000003 // aggregate of the mux flags above
/* Flags indicating why writing to the demux is blocked.
* The first two ones directly affect the ability for the mux to receive data
* from the connection. The other ones affect the mux's ability to demux
* received data.
*/
#define H2_CF_DEM_DALLOC 0x00000004 // demux blocked on lack of connection's demux buffer
#define H2_CF_DEM_DFULL 0x00000008 // demux blocked on connection's demux buffer full
#define H2_CF_DEM_MBUSY 0x00000010 // demux blocked on connection's mux side busy
#define H2_CF_DEM_MROOM 0x00000020 // demux blocked on lack of room in mux buffer
#define H2_CF_DEM_SALLOC 0x00000040 // demux blocked on lack of stream's request buffer
#define H2_CF_DEM_SFULL 0x00000080 // demux blocked on stream request buffer full
#define H2_CF_DEM_TOOMANY 0x00000100 // demux blocked waiting for some conn_streams to leave
#define H2_CF_DEM_BLOCK_ANY 0x000001F0 // aggregate of the demux flags above except DALLOC/DFULL
/* other flags */
#define H2_CF_GOAWAY_SENT 0x00001000 // a GOAWAY frame was successfully sent
#define H2_CF_GOAWAY_FAILED 0x00002000 // a GOAWAY frame failed to be sent
#define H2_CF_WAIT_FOR_HS 0x00004000 // We did check that at least a stream was waiting for handshake
#define H2_CF_IS_BACK 0x00008000 // this is an outgoing connection
#define H2_CF_WINDOW_OPENED 0x00010000 // demux increased window already advertised
/* H2 connection state, in h2c->st0 */
enum h2_cs {
H2_CS_PREFACE, // init done, waiting for connection preface
H2_CS_SETTINGS1, // preface OK, waiting for first settings frame
H2_CS_FRAME_H, // first settings frame ok, waiting for frame header
H2_CS_FRAME_P, // frame header OK, waiting for frame payload
H2_CS_FRAME_A, // frame payload OK, trying to send ACK frame
H2_CS_FRAME_E, // frame payload OK, trying to send RST frame
H2_CS_ERROR, // send GOAWAY(errcode) and close the connection ASAP
H2_CS_ERROR2, // GOAWAY(errcode) sent, close the connection ASAP
H2_CS_ENTRIES // must be last
} __attribute__((packed));
/* 32 buffers: one for the ring's root, rest for the mbuf itself */
#define H2C_MBUF_CNT 32
/* H2 connection descriptor */
struct h2c {
struct connection *conn;
enum h2_cs st0; /* mux state */
enum h2_err errcode; /* H2 err code (H2_ERR_*) */
/* 16 bit hole here */
uint32_t flags; /* connection flags: H2_CF_* */
uint32_t streams_limit; /* maximum number of concurrent streams the peer supports */
int32_t max_id; /* highest ID known on this connection, <0 before preface */
uint32_t rcvd_c; /* newly received data to ACK for the connection */
uint32_t rcvd_s; /* newly received data to ACK for the current stream (dsi) */
/* states for the demux direction */
struct hpack_dht *ddht; /* demux dynamic header table */
struct buffer dbuf; /* demux buffer */
int32_t dsi; /* demux stream ID (<0 = idle) */
int32_t dfl; /* demux frame length (if dsi >= 0) */
int8_t dft; /* demux frame type (if dsi >= 0) */
int8_t dff; /* demux frame flags (if dsi >= 0) */
uint8_t dpl; /* demux pad length (part of dfl), init to 0 */
/* 8 bit hole here */
int32_t last_sid; /* last processed stream ID for GOAWAY, <0 before preface */
/* states for the mux direction */
struct buffer mbuf[H2C_MBUF_CNT]; /* mux buffers (ring) */
int32_t msi; /* mux stream ID (<0 = idle) */
int32_t mfl; /* mux frame length (if dsi >= 0) */
int8_t mft; /* mux frame type (if dsi >= 0) */
int8_t mff; /* mux frame flags (if dsi >= 0) */
/* 16 bit hole here */
int32_t miw; /* mux initial window size for all new streams */
int32_t mws; /* mux window size. Can be negative. */
int32_t mfs; /* mux's max frame size */
int timeout; /* idle timeout duration in ticks */
int shut_timeout; /* idle timeout duration in ticks after GOAWAY was sent */
unsigned int nb_streams; /* number of streams in the tree */
unsigned int nb_cs; /* number of attached conn_streams */
unsigned int nb_reserved; /* number of reserved streams */
unsigned int stream_cnt; /* total number of streams seen */
struct proxy *proxy; /* the proxy this connection was created for */
struct task *task; /* timeout management task */
struct eb_root streams_by_id; /* all active streams by their ID */
struct list send_list; /* list of blocked streams requesting to send */
struct list fctl_list; /* list of streams blocked by connection's fctl */
struct list blocked_list; /* list of streams blocked for other reasons (e.g. sfctl, dep) */
struct list sending_list; /* list of h2s scheduled to send data */
struct buffer_wait buf_wait; /* wait list for buffer allocations */
struct wait_event wait_event; /* To be used if we're waiting for I/Os */
};
/* H2 stream state, in h2s->st */
enum h2_ss {
H2_SS_IDLE = 0, // idle
H2_SS_RLOC, // reserved(local)
H2_SS_RREM, // reserved(remote)
H2_SS_OPEN, // open
H2_SS_HREM, // half-closed(remote)
H2_SS_HLOC, // half-closed(local)
H2_SS_ERROR, // an error needs to be sent using RST_STREAM
H2_SS_CLOSED, // closed
H2_SS_ENTRIES // must be last
} __attribute__((packed));
#define H2_SS_MASK(state) (1UL << (state))
#define H2_SS_IDLE_BIT (1UL << H2_SS_IDLE)
#define H2_SS_RLOC_BIT (1UL << H2_SS_RLOC)
#define H2_SS_RREM_BIT (1UL << H2_SS_RREM)
#define H2_SS_OPEN_BIT (1UL << H2_SS_OPEN)
#define H2_SS_HREM_BIT (1UL << H2_SS_HREM)
#define H2_SS_HLOC_BIT (1UL << H2_SS_HLOC)
#define H2_SS_ERROR_BIT (1UL << H2_SS_ERROR)
#define H2_SS_CLOSED_BIT (1UL << H2_SS_CLOSED)
/* HTTP/2 stream flags (32 bit), in h2s->flags */
#define H2_SF_NONE 0x00000000
#define H2_SF_ES_RCVD 0x00000001
#define H2_SF_ES_SENT 0x00000002
#define H2_SF_RST_RCVD 0x00000004 // received RST_STREAM
#define H2_SF_RST_SENT 0x00000008 // sent RST_STREAM
/* stream flags indicating the reason the stream is blocked */
#define H2_SF_BLK_MBUSY 0x00000010 // blocked waiting for mux access (transient)
#define H2_SF_BLK_MROOM 0x00000020 // blocked waiting for room in the mux (must be in send list)
#define H2_SF_BLK_MFCTL 0x00000040 // blocked due to mux fctl (must be in fctl list)
#define H2_SF_BLK_SFCTL 0x00000080 // blocked due to stream fctl (must be in blocked list)
#define H2_SF_BLK_ANY 0x000000F0 // any of the reasons above
/* stream flags indicating how data is supposed to be sent */
#define H2_SF_DATA_CLEN 0x00000100 // data sent using content-length
/* unused flags: 0x00000200, 0x00000400, 0x00000800 */
#define H2_SF_HEADERS_SENT 0x00001000 // a HEADERS frame was sent for this stream
#define H2_SF_OUTGOING_DATA 0x00002000 // set whenever we've seen outgoing data
#define H2_SF_HEADERS_RCVD 0x00004000 // a HEADERS frame was received for this stream
#define H2_SF_WANT_SHUTR 0x00008000 // a stream couldn't shutr() (mux full/busy)
#define H2_SF_WANT_SHUTW 0x00010000 // a stream couldn't shutw() (mux full/busy)
#define H2_SF_KILL_CONN 0x00020000 // kill the whole connection with this stream
/* H2 stream descriptor, describing the stream as it appears in the H2C, and as
* it is being processed in the internal HTTP representation (H1 for now).
*/
struct h2s {
struct conn_stream *cs;
struct session *sess;
struct h2c *h2c;
struct h1m h1m; /* request or response parser state for H1 */
struct eb32_node by_id; /* place in h2c's streams_by_id */
int32_t id; /* stream ID */
uint32_t flags; /* H2_SF_* */
int sws; /* stream window size, to be added to the mux's initial window size */
enum h2_err errcode; /* H2 err code (H2_ERR_*) */
enum h2_ss st;
uint16_t status; /* HTTP response status */
unsigned long long body_len; /* remaining body length according to content-length if H2_SF_DATA_CLEN */
struct buffer rxbuf; /* receive buffer, always valid (buf_empty or real buffer) */
struct wait_event wait_event; /* Wait list, when we're attempting to send a RST but we can't send */
struct wait_event *recv_wait; /* recv wait_event the conn_stream associated is waiting on (via h2_subscribe) */
struct wait_event *send_wait; /* send wait_event the conn_stream associated is waiting on (via h2_subscribe) */
struct list list; /* To be used when adding in h2c->send_list or h2c->fctl_lsit */
struct list sending_list; /* To be used when adding in h2c->sending_list */
};
/* descriptor for an h2 frame header */
struct h2_fh {
uint32_t len; /* length, host order, 24 bits */
uint32_t sid; /* stream id, host order, 31 bits */
uint8_t ft; /* frame type */
uint8_t ff; /* frame flags */
};
/* trace source and events */
static void h2_trace(enum trace_level level, uint64_t mask, \
const struct trace_source *src,
const struct ist where, const struct ist func,
const void *a1, const void *a2, const void *a3, const void *a4);
/* The event representation is split like this :
* strm - application layer
* h2s - internal H2 stream
* h2c - internal H2 connection
* conn - external connection
*
*/
static const struct trace_event h2_trace_events[] = {
#define H2_EV_H2C_NEW (1ULL << 0)
{ .mask = H2_EV_H2C_NEW, .name = "h2c_new", .desc = "new H2 connection" },
#define H2_EV_H2C_RECV (1ULL << 1)
{ .mask = H2_EV_H2C_RECV, .name = "h2c_recv", .desc = "Rx on H2 connection" },
#define H2_EV_H2C_SEND (1ULL << 2)
{ .mask = H2_EV_H2C_SEND, .name = "h2c_send", .desc = "Tx on H2 connection" },
#define H2_EV_H2C_FCTL (1ULL << 3)
{ .mask = H2_EV_H2C_FCTL, .name = "h2c_fctl", .desc = "H2 connection flow-controlled" },
#define H2_EV_H2C_BLK (1ULL << 4)
{ .mask = H2_EV_H2C_BLK, .name = "h2c_blk", .desc = "H2 connection blocked" },
#define H2_EV_H2C_WAKE (1ULL << 5)
{ .mask = H2_EV_H2C_WAKE, .name = "h2c_wake", .desc = "H2 connection woken up" },
#define H2_EV_H2C_END (1ULL << 6)
{ .mask = H2_EV_H2C_END, .name = "h2c_end", .desc = "H2 connection terminated" },
#define H2_EV_H2C_ERR (1ULL << 7)
{ .mask = H2_EV_H2C_ERR, .name = "h2c_err", .desc = "error on H2 connection" },
#define H2_EV_RX_FHDR (1ULL << 8)
{ .mask = H2_EV_RX_FHDR, .name = "rx_fhdr", .desc = "H2 frame header received" },
#define H2_EV_RX_FRAME (1ULL << 9)
{ .mask = H2_EV_RX_FRAME, .name = "rx_frame", .desc = "receipt of any H2 frame" },
#define H2_EV_RX_EOI (1ULL << 10)
{ .mask = H2_EV_RX_EOI, .name = "rx_eoi", .desc = "receipt of end of H2 input (ES or RST)" },
#define H2_EV_RX_PREFACE (1ULL << 11)
{ .mask = H2_EV_RX_PREFACE, .name = "rx_preface", .desc = "receipt of H2 preface" },
#define H2_EV_RX_DATA (1ULL << 12)
{ .mask = H2_EV_RX_DATA, .name = "rx_data", .desc = "receipt of H2 DATA frame" },
#define H2_EV_RX_HDR (1ULL << 13)
{ .mask = H2_EV_RX_HDR, .name = "rx_hdr", .desc = "receipt of H2 HEADERS frame" },
#define H2_EV_RX_PRIO (1ULL << 14)
{ .mask = H2_EV_RX_PRIO, .name = "rx_prio", .desc = "receipt of H2 PRIORITY frame" },
#define H2_EV_RX_RST (1ULL << 15)
{ .mask = H2_EV_RX_RST, .name = "rx_rst", .desc = "receipt of H2 RST_STREAM frame" },
#define H2_EV_RX_SETTINGS (1ULL << 16)
{ .mask = H2_EV_RX_SETTINGS, .name = "rx_settings", .desc = "receipt of H2 SETTINGS frame" },
#define H2_EV_RX_PUSH (1ULL << 17)
{ .mask = H2_EV_RX_PUSH, .name = "rx_push", .desc = "receipt of H2 PUSH_PROMISE frame" },
#define H2_EV_RX_PING (1ULL << 18)
{ .mask = H2_EV_RX_PING, .name = "rx_ping", .desc = "receipt of H2 PING frame" },
#define H2_EV_RX_GOAWAY (1ULL << 19)
{ .mask = H2_EV_RX_GOAWAY, .name = "rx_goaway", .desc = "receipt of H2 GOAWAY frame" },
#define H2_EV_RX_WU (1ULL << 20)
{ .mask = H2_EV_RX_WU, .name = "rx_wu", .desc = "receipt of H2 WINDOW_UPDATE frame" },
#define H2_EV_RX_CONT (1ULL << 21)
{ .mask = H2_EV_RX_CONT, .name = "rx_cont", .desc = "receipt of H2 CONTINUATION frame" },
#define H2_EV_TX_FRAME (1ULL << 22)
{ .mask = H2_EV_TX_FRAME, .name = "tx_frame", .desc = "transmission of any H2 frame" },
#define H2_EV_TX_EOI (1ULL << 23)
{ .mask = H2_EV_TX_EOI, .name = "tx_eoi", .desc = "transmission of H2 end of input (ES or RST)" },
#define H2_EV_TX_PREFACE (1ULL << 24)
{ .mask = H2_EV_TX_PREFACE, .name = "tx_preface", .desc = "transmission of H2 preface" },
#define H2_EV_TX_DATA (1ULL << 25)
{ .mask = H2_EV_TX_DATA, .name = "tx_data", .desc = "transmission of H2 DATA frame" },
#define H2_EV_TX_HDR (1ULL << 26)
{ .mask = H2_EV_TX_HDR, .name = "tx_hdr", .desc = "transmission of H2 HEADERS frame" },
#define H2_EV_TX_PRIO (1ULL << 27)
{ .mask = H2_EV_TX_PRIO, .name = "tx_prio", .desc = "transmission of H2 PRIORITY frame" },
#define H2_EV_TX_RST (1ULL << 28)
{ .mask = H2_EV_TX_RST, .name = "tx_rst", .desc = "transmission of H2 RST_STREAM frame" },
#define H2_EV_TX_SETTINGS (1ULL << 29)
{ .mask = H2_EV_TX_SETTINGS, .name = "tx_settings", .desc = "transmission of H2 SETTINGS frame" },
#define H2_EV_TX_PUSH (1ULL << 30)
{ .mask = H2_EV_TX_PUSH, .name = "tx_push", .desc = "transmission of H2 PUSH_PROMISE frame" },
#define H2_EV_TX_PING (1ULL << 31)
{ .mask = H2_EV_TX_PING, .name = "tx_ping", .desc = "transmission of H2 PING frame" },
#define H2_EV_TX_GOAWAY (1ULL << 32)
{ .mask = H2_EV_TX_GOAWAY, .name = "tx_goaway", .desc = "transmission of H2 GOAWAY frame" },
#define H2_EV_TX_WU (1ULL << 33)
{ .mask = H2_EV_TX_WU, .name = "tx_wu", .desc = "transmission of H2 WINDOW_UPDATE frame" },
#define H2_EV_TX_CONT (1ULL << 34)
{ .mask = H2_EV_TX_CONT, .name = "tx_cont", .desc = "transmission of H2 CONTINUATION frame" },
#define H2_EV_H2S_NEW (1ULL << 35)
{ .mask = H2_EV_H2S_NEW, .name = "h2s_new", .desc = "new H2 stream" },
#define H2_EV_H2S_RECV (1ULL << 36)
{ .mask = H2_EV_H2S_RECV, .name = "h2s_recv", .desc = "Rx for H2 stream" },
#define H2_EV_H2S_SEND (1ULL << 37)
{ .mask = H2_EV_H2S_SEND, .name = "h2s_send", .desc = "Tx for H2 stream" },
#define H2_EV_H2S_FCTL (1ULL << 38)
{ .mask = H2_EV_H2S_FCTL, .name = "h2s_fctl", .desc = "H2 stream flow-controlled" },
#define H2_EV_H2S_BLK (1ULL << 39)
{ .mask = H2_EV_H2S_BLK, .name = "h2s_blk", .desc = "H2 stream blocked" },
#define H2_EV_H2S_WAKE (1ULL << 40)
{ .mask = H2_EV_H2S_WAKE, .name = "h2s_wake", .desc = "H2 stream woken up" },
#define H2_EV_H2S_END (1ULL << 41)
{ .mask = H2_EV_H2S_END, .name = "h2s_end", .desc = "H2 stream terminated" },
#define H2_EV_H2S_ERR (1ULL << 42)
{ .mask = H2_EV_H2S_ERR, .name = "h2s_err", .desc = "error on H2 stream" },
#define H2_EV_STRM_NEW (1ULL << 43)
{ .mask = H2_EV_STRM_NEW, .name = "strm_new", .desc = "app-layer stream creation" },
#define H2_EV_STRM_RECV (1ULL << 44)
{ .mask = H2_EV_STRM_RECV, .name = "strm_recv", .desc = "receiving data for stream" },
#define H2_EV_STRM_SEND (1ULL << 45)
{ .mask = H2_EV_STRM_SEND, .name = "strm_send", .desc = "sending data for stream" },
#define H2_EV_STRM_FULL (1ULL << 46)
{ .mask = H2_EV_STRM_FULL, .name = "strm_full", .desc = "stream buffer full" },
#define H2_EV_STRM_WAKE (1ULL << 47)
{ .mask = H2_EV_STRM_WAKE, .name = "strm_wake", .desc = "stream woken up" },
#define H2_EV_STRM_SHUT (1ULL << 48)
{ .mask = H2_EV_STRM_SHUT, .name = "strm_shut", .desc = "stream shutdown" },
#define H2_EV_STRM_END (1ULL << 49)
{ .mask = H2_EV_STRM_END, .name = "strm_end", .desc = "detaching app-layer stream" },
#define H2_EV_STRM_ERR (1ULL << 50)
{ .mask = H2_EV_STRM_ERR, .name = "strm_err", .desc = "stream error" },
#define H2_EV_PROTO_ERR (1ULL << 51)
{ .mask = H2_EV_PROTO_ERR, .name = "proto_err", .desc = "protocol error" },
{ }
};
static const struct name_desc h2_trace_lockon_args[4] = {
/* arg1 */ { /* already used by the connection */ },
/* arg2 */ { .name="h2s", .desc="H2 stream" },
/* arg3 */ { },
/* arg4 */ { }
};
static const struct name_desc h2_trace_decoding[] = {
#define H2_VERB_CLEAN 1
{ .name="clean", .desc="only user-friendly stuff, generally suitable for level \"user\"" },
#define H2_VERB_MINIMAL 2
{ .name="minimal", .desc="report only h2c/h2s state and flags, no real decoding" },
#define H2_VERB_SIMPLE 3
{ .name="simple", .desc="add request/response status line or frame info when available" },
#define H2_VERB_ADVANCED 4
{ .name="advanced", .desc="add header fields or frame decoding when available" },
#define H2_VERB_COMPLETE 5
{ .name="complete", .desc="add full data dump when available" },
{ /* end */ }
};
static struct trace_source trace_h2 = {
.name = IST("h2"),
.desc = "HTTP/2 multiplexer",
.arg_def = TRC_ARG1_CONN, // TRACE()'s first argument is always a connection
.default_cb = h2_trace,
.known_events = h2_trace_events,
.lockon_args = h2_trace_lockon_args,
.decoding = h2_trace_decoding,
.report_events = ~0, // report everything by default
};
#define TRACE_SOURCE &trace_h2
INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
/* the h2c connection pool */
DECLARE_STATIC_POOL(pool_head_h2c, "h2c", sizeof(struct h2c));
/* the h2s stream pool */
DECLARE_STATIC_POOL(pool_head_h2s, "h2s", sizeof(struct h2s));
/* The default connection window size is 65535, it may only be enlarged using
* a WINDOW_UPDATE message. Since the window must never be larger than 2G-1,
* we'll pretend we already received the difference between the two to send
* an equivalent window update to enlarge it to 2G-1.
*/
#define H2_INITIAL_WINDOW_INCREMENT ((1U<<31)-1 - 65535)
/* maximum amount of data we're OK with re-aligning for buffer optimizations */
#define MAX_DATA_REALIGN 1024
/* a few settings from the global section */
static int h2_settings_header_table_size = 4096; /* initial value */
static int h2_settings_initial_window_size = 65535; /* initial value */
static unsigned int h2_settings_max_concurrent_streams = 100;
static int h2_settings_max_frame_size = 0; /* unset */
/* a dmumy closed stream */
static const struct h2s *h2_closed_stream = &(const struct h2s){
.cs = NULL,
.h2c = NULL,
.st = H2_SS_CLOSED,
.errcode = H2_ERR_STREAM_CLOSED,
.flags = H2_SF_RST_RCVD,
.id = 0,
};
/* a dmumy closed stream returning a PROTOCOL_ERROR error */
static const struct h2s *h2_error_stream = &(const struct h2s){
.cs = NULL,
.h2c = NULL,
.st = H2_SS_CLOSED,
.errcode = H2_ERR_PROTOCOL_ERROR,
.flags = 0,
.id = 0,
};
/* a dmumy closed stream returning a REFUSED_STREAM error */
static const struct h2s *h2_refused_stream = &(const struct h2s){
.cs = NULL,
.h2c = NULL,
.st = H2_SS_CLOSED,
.errcode = H2_ERR_REFUSED_STREAM,
.flags = 0,
.id = 0,
};
/* and a dummy idle stream for use with any unannounced stream */
static const struct h2s *h2_idle_stream = &(const struct h2s){
.cs = NULL,
.h2c = NULL,
.st = H2_SS_IDLE,
.errcode = H2_ERR_STREAM_CLOSED,
.id = 0,
};
static struct task *h2_timeout_task(struct task *t, void *context, unsigned short state);
static int h2_send(struct h2c *h2c);
static int h2_recv(struct h2c *h2c);
static int h2_process(struct h2c *h2c);
static struct task *h2_io_cb(struct task *t, void *ctx, unsigned short state);
static inline struct h2s *h2c_st_by_id(struct h2c *h2c, int id);
static int h2c_decode_headers(struct h2c *h2c, struct buffer *rxbuf, uint32_t *flags, unsigned long long *body_len);
static int h2_frt_transfer_data(struct h2s *h2s);
static struct task *h2_deferred_shut(struct task *t, void *ctx, unsigned short state);
static struct h2s *h2c_bck_stream_new(struct h2c *h2c, struct conn_stream *cs, struct session *sess);
static void h2s_alert(struct h2s *h2s);
/* returns a h2c state as an abbreviated 3-letter string, or "???" if unknown */
static inline const char *h2c_st_to_str(enum h2_cs st)
{
switch (st) {
case H2_CS_PREFACE: return "PRF";
case H2_CS_SETTINGS1: return "STG";
case H2_CS_FRAME_H: return "FRH";
case H2_CS_FRAME_P: return "FRP";
case H2_CS_FRAME_A: return "FRA";
case H2_CS_FRAME_E: return "FRE";
case H2_CS_ERROR: return "ERR";
case H2_CS_ERROR2: return "ER2";
default: return "???";
}
}
/* returns a h2s state as an abbreviated 3-letter string, or "???" if unknown */
static inline const char *h2s_st_to_str(enum h2_ss st)
{
switch (st) {
case H2_SS_IDLE: return "IDL"; // idle
case H2_SS_RLOC: return "RSL"; // reserved local
case H2_SS_RREM: return "RSR"; // reserved remote
case H2_SS_OPEN: return "OPN"; // open
case H2_SS_HREM: return "HCR"; // half-closed remote
case H2_SS_HLOC: return "HCL"; // half-closed local
case H2_SS_ERROR : return "ERR"; // error
case H2_SS_CLOSED: return "CLO"; // closed
default: return "???";
}
}
/* the H2 traces always expect that arg1, if non-null, is of type connection
* (from which we can derive h2c), that arg2, if non-null, is of type h2s, and
* that arg3, if non-null, is either of type htx for tx headers, or of type
* buffer for everything else.
*/
static void h2_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
const struct ist where, const struct ist func,
const void *a1, const void *a2, const void *a3, const void *a4)
{
const struct connection *conn = a1;
const struct h2c *h2c = conn ? conn->ctx : NULL;
const struct h2s *h2s = a2;
const struct buffer *buf = a3;
const struct htx *htx;
int pos;
if (!h2c) // nothing to add
return;
if (src->verbosity > H2_VERB_CLEAN) {
chunk_appendf(&trace_buf, " : h2c=%p(%c,%s)", h2c, conn_is_back(conn) ? 'B' : 'F', h2c_st_to_str(h2c->st0));
if (h2c->errcode)
chunk_appendf(&trace_buf, " err=%s/%02x", h2_err_str(h2c->errcode), h2c->errcode);
if (h2c->dsi >= 0 &&
(mask & (H2_EV_RX_FRAME|H2_EV_RX_FHDR)) == (H2_EV_RX_FRAME|H2_EV_RX_FHDR)) {
chunk_appendf(&trace_buf, " dft=%s/%02x", h2_ft_str(h2c->dft), h2c->dff);
}
if (h2s) {
if (h2s->id <= 0)
chunk_appendf(&trace_buf, " dsi=%d", h2c->dsi);
chunk_appendf(&trace_buf, " h2s=%p(%d,%s)", h2s, h2s->id, h2s_st_to_str(h2s->st));
if (h2s->id && h2s->errcode)
chunk_appendf(&trace_buf, " err=%s/%02x", h2_err_str(h2s->errcode), h2s->errcode);
}
}
/* Let's dump decoded requests and responses right after parsing. They
* are traced at level USER with a few recognizable flags.
*/
if ((mask == (H2_EV_RX_FRAME|H2_EV_RX_HDR|H2_EV_STRM_NEW) ||
mask == (H2_EV_RX_FRAME|H2_EV_RX_HDR)) && buf)
htx = htxbuf(buf); // recv req/res
else if (mask == (H2_EV_TX_FRAME|H2_EV_TX_HDR))
htx = a3; // send req/res
else
htx = NULL;
if (level == TRACE_LEVEL_USER && src->verbosity != H2_VERB_MINIMAL && htx && (pos = htx_get_head(htx)) != -1) {
const struct htx_blk *blk = htx_get_blk(htx, pos);
const struct htx_sl *sl = htx_get_blk_ptr(htx, blk);
enum htx_blk_type type = htx_get_blk_type(blk);
if (type == HTX_BLK_REQ_SL)
chunk_appendf(&trace_buf, " : [%d] H2 REQ: %.*s %.*s %.*s",
h2s ? h2s->id : h2c->dsi,
HTX_SL_P1_LEN(sl), HTX_SL_P1_PTR(sl),
HTX_SL_P2_LEN(sl), HTX_SL_P2_PTR(sl),
HTX_SL_P3_LEN(sl), HTX_SL_P3_PTR(sl));
else if (type == HTX_BLK_RES_SL)
chunk_appendf(&trace_buf, " : [%d] H2 RES: %.*s %.*s %.*s",
h2s ? h2s->id : h2c->dsi,
HTX_SL_P1_LEN(sl), HTX_SL_P1_PTR(sl),
HTX_SL_P2_LEN(sl), HTX_SL_P2_PTR(sl),
HTX_SL_P3_LEN(sl), HTX_SL_P3_PTR(sl));
}
}
/* returns true if the connection is allowed to expire, false otherwise. A
* connection may expire when:
* - it has no stream
* - it has data in the mux buffer
* - it has streams in the blocked list
* - it has streams in the fctl list
* - it has streams in the send list
* Otherwise it means some streams are waiting in the data layer and it should
* not expire.
*/
static inline int h2c_may_expire(const struct h2c *h2c)
{
return eb_is_empty(&h2c->streams_by_id) ||
br_data(h2c->mbuf) ||
!LIST_ISEMPTY(&h2c->blocked_list) ||
!LIST_ISEMPTY(&h2c->fctl_list) ||
!LIST_ISEMPTY(&h2c->send_list) ||
!LIST_ISEMPTY(&h2c->sending_list);
}
static __inline int
h2c_is_dead(const struct h2c *h2c)
{
if (eb_is_empty(&h2c->streams_by_id) && /* don't close if streams exist */
((h2c->conn->flags & CO_FL_ERROR) || /* errors close immediately */
(h2c->st0 >= H2_CS_ERROR && !h2c->task) || /* a timeout stroke earlier */
(!(h2c->conn->owner)) || /* Nobody's left to take care of the connection, drop it now */
(!br_data(h2c->mbuf) && /* mux buffer empty, also process clean events below */
(conn_xprt_read0_pending(h2c->conn) ||
(h2c->last_sid >= 0 && h2c->max_id >= h2c->last_sid)))))
return 1;
return 0;
}
/*****************************************************/
/* functions below are for dynamic buffer management */
/*****************************************************/
/* indicates whether or not the we may call the h2_recv() function to attempt
* to receive data into the buffer and/or demux pending data. The condition is
* a bit complex due to some API limits for now. The rules are the following :
* - if an error or a shutdown was detected on the connection and the buffer
* is empty, we must not attempt to receive
* - if the demux buf failed to be allocated, we must not try to receive and
* we know there is nothing pending
* - if no flag indicates a blocking condition, we may attempt to receive,
* regardless of whether the demux buffer is full or not, so that only
* de demux part decides whether or not to block. This is needed because
* the connection API indeed prevents us from re-enabling receipt that is
* already enabled in a polled state, so we must always immediately stop
* as soon as the demux can't proceed so as never to hit an end of read
* with data pending in the buffers.
* - otherwise must may not attempt
*/
static inline int h2_recv_allowed(const struct h2c *h2c)
{
if (b_data(&h2c->dbuf) == 0 &&
(h2c->st0 >= H2_CS_ERROR ||
h2c->conn->flags & CO_FL_ERROR ||
conn_xprt_read0_pending(h2c->conn)))
return 0;
if (!(h2c->flags & H2_CF_DEM_DALLOC) &&
!(h2c->flags & H2_CF_DEM_BLOCK_ANY))
return 1;
return 0;
}
/* restarts reading on the connection if it was not enabled */
static inline void h2c_restart_reading(const struct h2c *h2c, int consider_buffer)
{
if (!h2_recv_allowed(h2c))
return;
if ((!consider_buffer || !b_data(&h2c->dbuf))
&& (h2c->wait_event.events & SUB_RETRY_RECV))
return;
tasklet_wakeup(h2c->wait_event.tasklet);
}
/* returns true if the front connection has too many conn_streams attached */
static inline int h2_frt_has_too_many_cs(const struct h2c *h2c)
{
return h2c->nb_cs > h2_settings_max_concurrent_streams;
}
/* Tries to grab a buffer and to re-enable processing on mux <target>. The h2c
* flags are used to figure what buffer was requested. It returns 1 if the
* allocation succeeds, in which case the connection is woken up, or 0 if it's
* impossible to wake up and we prefer to be woken up later.
*/
static int h2_buf_available(void *target)
{
struct h2c *h2c = target;
struct h2s *h2s;
if ((h2c->flags & H2_CF_DEM_DALLOC) && b_alloc_margin(&h2c->dbuf, 0)) {
h2c->flags &= ~H2_CF_DEM_DALLOC;
h2c_restart_reading(h2c, 1);
return 1;
}
if ((h2c->flags & H2_CF_MUX_MALLOC) && b_alloc_margin(br_tail(h2c->mbuf), 0)) {
h2c->flags &= ~H2_CF_MUX_MALLOC;
if (h2c->flags & H2_CF_DEM_MROOM) {
h2c->flags &= ~H2_CF_DEM_MROOM;
h2c_restart_reading(h2c, 1);
}
return 1;
}
if ((h2c->flags & H2_CF_DEM_SALLOC) &&
(h2s = h2c_st_by_id(h2c, h2c->dsi)) && h2s->cs &&
b_alloc_margin(&h2s->rxbuf, 0)) {
h2c->flags &= ~H2_CF_DEM_SALLOC;
h2c_restart_reading(h2c, 1);
return 1;
}
return 0;
}
static inline struct buffer *h2_get_buf(struct h2c *h2c, struct buffer *bptr)
{
struct buffer *buf = NULL;
if (likely(!LIST_ADDED(&h2c->buf_wait.list)) &&
unlikely((buf = b_alloc_margin(bptr, 0)) == NULL)) {
h2c->buf_wait.target = h2c;
h2c->buf_wait.wakeup_cb = h2_buf_available;
HA_SPIN_LOCK(BUF_WQ_LOCK, &buffer_wq_lock);
LIST_ADDQ(&buffer_wq, &h2c->buf_wait.list);
HA_SPIN_UNLOCK(BUF_WQ_LOCK, &buffer_wq_lock);
__conn_xprt_stop_recv(h2c->conn);
}
return buf;
}
static inline void h2_release_buf(struct h2c *h2c, struct buffer *bptr)
{
if (bptr->size) {
b_free(bptr);
offer_buffers(NULL, tasks_run_queue);
}
}
static inline void h2_release_mbuf(struct h2c *h2c)
{
struct buffer *buf;
unsigned int count = 0;
while (b_size(buf = br_head_pick(h2c->mbuf))) {
b_free(buf);
count++;
}
if (count)
offer_buffers(NULL, tasks_run_queue);
}
/* returns the number of allocatable outgoing streams for the connection taking
* the last_sid and the reserved ones into account.
*/
static inline int h2_streams_left(const struct h2c *h2c)
{
int ret;
/* consider the number of outgoing streams we're allowed to create before
* reaching the last GOAWAY frame seen. max_id is the last assigned id,
* nb_reserved is the number of streams which don't yet have an ID.
*/
ret = (h2c->last_sid >= 0) ? h2c->last_sid : 0x7FFFFFFF;
ret = (unsigned int)(ret - h2c->max_id) / 2 - h2c->nb_reserved - 1;
if (ret < 0)
ret = 0;
return ret;
}
/* returns the number of streams in use on a connection to figure if it's
* idle or not. We check nb_cs and not nb_streams as the caller will want
* to know if it was the last one after a detach().
*/
static int h2_used_streams(struct connection *conn)
{
struct h2c *h2c = conn->ctx;
return h2c->nb_cs;
}
/* returns the number of concurrent streams available on the connection */
static int h2_avail_streams(struct connection *conn)
{
struct server *srv = objt_server(conn->target);
struct h2c *h2c = conn->ctx;
int ret1, ret2;
/* RFC7540#6.8: Receivers of a GOAWAY frame MUST NOT open additional
* streams on the connection.
*/
if (h2c->last_sid >= 0)
return 0;
if (h2c->st0 >= H2_CS_ERROR)
return 0;
/* note: may be negative if a SETTINGS frame changes the limit */
ret1 = h2c->streams_limit - h2c->nb_streams;
/* we must also consider the limit imposed by stream IDs */
ret2 = h2_streams_left(h2c);
ret1 = MIN(ret1, ret2);
if (ret1 > 0 && srv && srv->max_reuse >= 0) {
ret2 = h2c->stream_cnt <= srv->max_reuse ? srv->max_reuse - h2c->stream_cnt + 1: 0;
ret1 = MIN(ret1, ret2);
}
return ret1;
}
/*****************************************************************/
/* functions below are dedicated to the mux setup and management */
/*****************************************************************/
/* Initialize the mux once it's attached. For outgoing connections, the context
* is already initialized before installing the mux, so we detect incoming
* connections from the fact that the context is still NULL (even during mux
* upgrades). <input> is always used as Input buffer and may contain data. It is
* the caller responsibility to not reuse it anymore. Returns < 0 on error.
*/
static int h2_init(struct connection *conn, struct proxy *prx, struct session *sess,
struct buffer *input)
{
struct h2c *h2c;
struct task *t = NULL;
void *conn_ctx = conn->ctx;
TRACE_ENTER(H2_EV_H2C_NEW);
h2c = pool_alloc(pool_head_h2c);
if (!h2c)
goto fail_no_h2c;
if (conn_is_back(conn)) {
h2c->flags = H2_CF_IS_BACK;
h2c->shut_timeout = h2c->timeout = prx->timeout.server;
if (tick_isset(prx->timeout.serverfin))
h2c->shut_timeout = prx->timeout.serverfin;
} else {
h2c->flags = H2_CF_NONE;
h2c->shut_timeout = h2c->timeout = prx->timeout.client;
if (tick_isset(prx->timeout.clientfin))
h2c->shut_timeout = prx->timeout.clientfin;
}
h2c->proxy = prx;
h2c->task = NULL;
if (tick_isset(h2c->timeout)) {
t = task_new(tid_bit);
if (!t)
goto fail;
h2c->task = t;
t->process = h2_timeout_task;
t->context = h2c;
t->expire = tick_add(now_ms, h2c->timeout);
}
h2c->wait_event.tasklet = tasklet_new();
if (!h2c->wait_event.tasklet)
goto fail;
h2c->wait_event.tasklet->process = h2_io_cb;
h2c->wait_event.tasklet->context = h2c;
h2c->wait_event.events = 0;
h2c->ddht = hpack_dht_alloc(h2_settings_header_table_size);
if (!h2c->ddht)
goto fail;
/* Initialise the context. */
h2c->st0 = H2_CS_PREFACE;
h2c->conn = conn;
h2c->streams_limit = h2_settings_max_concurrent_streams;
h2c->max_id = -1;
h2c->errcode = H2_ERR_NO_ERROR;
h2c->rcvd_c = 0;
h2c->rcvd_s = 0;
h2c->nb_streams = 0;
h2c->nb_cs = 0;
h2c->nb_reserved = 0;
h2c->stream_cnt = 0;
h2c->dbuf = *input;
h2c->dsi = -1;
h2c->msi = -1;
h2c->last_sid = -1;
br_init(h2c->mbuf, sizeof(h2c->mbuf) / sizeof(h2c->mbuf[0]));
h2c->miw = 65535; /* mux initial window size */
h2c->mws = 65535; /* mux window size */
h2c->mfs = 16384; /* initial max frame size */
h2c->streams_by_id = EB_ROOT;
LIST_INIT(&h2c->send_list);
LIST_INIT(&h2c->fctl_list);
LIST_INIT(&h2c->blocked_list);
LIST_INIT(&h2c->sending_list);
LIST_INIT(&h2c->buf_wait.list);
conn->ctx = h2c;
if (t)
task_queue(t);
if (h2c->flags & H2_CF_IS_BACK) {
/* FIXME: this is temporary, for outgoing connections we need
* to immediately allocate a stream until the code is modified
* so that the caller calls ->attach(). For now the outgoing cs
* is stored as conn->ctx by the caller and saved in conn_ctx.
*/
struct h2s *h2s;
h2s = h2c_bck_stream_new(h2c, conn_ctx, sess);
if (!h2s)
goto fail_stream;
}
/* prepare to read something */
h2c_restart_reading(h2c, 1);
TRACE_LEAVE(H2_EV_H2C_NEW, conn);
return 0;
fail_stream:
hpack_dht_free(h2c->ddht);
fail:
task_destroy(t);
if (h2c->wait_event.tasklet)
tasklet_free(h2c->wait_event.tasklet);
pool_free(pool_head_h2c, h2c);
fail_no_h2c:
conn->ctx = conn_ctx; /* restore saved ctx */
TRACE_DEVEL("leaving in error", H2_EV_H2C_NEW|H2_EV_H2C_END|H2_EV_H2C_ERR);
return -1;
}
/* returns the next allocatable outgoing stream ID for the H2 connection, or
* -1 if no more is allocatable.
*/
static inline int32_t h2c_get_next_sid(const struct h2c *h2c)
{
int32_t id = (h2c->max_id + 1) | 1;
if ((id & 0x80000000U) || (h2c->last_sid >= 0 && id > h2c->last_sid))
id = -1;
return id;
}
/* returns the stream associated with id <id> or NULL if not found */
static inline struct h2s *h2c_st_by_id(struct h2c *h2c, int id)
{
struct eb32_node *node;
if (id == 0)
return (struct h2s *)h2_closed_stream;
if (id > h2c->max_id)
return (struct h2s *)h2_idle_stream;
node = eb32_lookup(&h2c->streams_by_id, id);
if (!node)
return (struct h2s *)h2_closed_stream;
return container_of(node, struct h2s, by_id);
}
/* release function. This one should be called to free all resources allocated
* to the mux.
*/
static void h2_release(struct h2c *h2c)
{
struct connection *conn = NULL;;
TRACE_ENTER(H2_EV_H2C_END);
if (h2c) {
/* The connection must be aattached to this mux to be released */
if (h2c->conn && h2c->conn->ctx == h2c)
conn = h2c->conn;
TRACE_DEVEL("freeing h2c", H2_EV_H2C_END, conn);
hpack_dht_free(h2c->ddht);
if (LIST_ADDED(&h2c->buf_wait.list)) {
HA_SPIN_LOCK(BUF_WQ_LOCK, &buffer_wq_lock);
LIST_DEL(&h2c->buf_wait.list);
HA_SPIN_UNLOCK(BUF_WQ_LOCK, &buffer_wq_lock);
}
h2_release_buf(h2c, &h2c->dbuf);
h2_release_mbuf(h2c);
if (h2c->task) {
h2c->task->context = NULL;
task_wakeup(h2c->task, TASK_WOKEN_OTHER);
h2c->task = NULL;
}
if (h2c->wait_event.tasklet)
tasklet_free(h2c->wait_event.tasklet);
if (conn && h2c->wait_event.events != 0)
conn->xprt->unsubscribe(conn, conn->xprt_ctx, h2c->wait_event.events,
&h2c->wait_event);
pool_free(pool_head_h2c, h2c);
}
if (conn) {
conn->mux = NULL;
conn->ctx = NULL;
TRACE_DEVEL("freeing conn", H2_EV_H2C_END, conn);
conn_stop_tracking(conn);
conn_full_close(conn);
if (conn->destroy_cb)
conn->destroy_cb(conn);
conn_free(conn);
}
TRACE_LEAVE(H2_EV_H2C_END);
}
/******************************************************/
/* functions below are for the H2 protocol processing */
/******************************************************/
/* returns the stream if of stream <h2s> or 0 if <h2s> is NULL */
static inline __maybe_unused int h2s_id(const struct h2s *h2s)
{
return h2s ? h2s->id : 0;
}
/* returns the sum of the stream's own window size and the mux's initial
* window, which together form the stream's effective window size.
*/
static inline int h2s_mws(const struct h2s *h2s)
{
return h2s->sws + h2s->h2c->miw;
}
/* returns true of the mux is currently busy as seen from stream <h2s> */
static inline __maybe_unused int h2c_mux_busy(const struct h2c *h2c, const struct h2s *h2s)
{
if (h2c->msi < 0)
return 0;
if (h2c->msi == h2s_id(h2s))
return 0;
return 1;
}
/* marks an error on the connection */
static inline __maybe_unused void h2c_error(struct h2c *h2c, enum h2_err err)
{
TRACE_POINT(H2_EV_H2C_ERR, h2c->conn,,, (void *)(long)(err));
h2c->errcode = err;
h2c->st0 = H2_CS_ERROR;
}
/* marks an error on the stream. It may also update an already closed stream
* (e.g. to report an error after an RST was received).
*/
static inline __maybe_unused void h2s_error(struct h2s *h2s, enum h2_err err)
{
if (h2s->id && h2s->st != H2_SS_ERROR) {
TRACE_POINT(H2_EV_H2S_ERR, h2s->h2c->conn, h2s,, (void *)(long)(err));
h2s->errcode = err;
if (h2s->st < H2_SS_ERROR)
h2s->st = H2_SS_ERROR;
if (h2s->cs)
cs_set_error(h2s->cs);
}
}
/* attempt to notify the data layer of recv availability */
static void __maybe_unused h2s_notify_recv(struct h2s *h2s)
{
struct wait_event *sw;
if (h2s->recv_wait) {
TRACE_POINT(H2_EV_STRM_WAKE, h2s->h2c->conn, h2s);
sw = h2s->recv_wait;
sw->events &= ~SUB_RETRY_RECV;
tasklet_wakeup(sw->tasklet);
h2s->recv_wait = NULL;
}
}
/* attempt to notify the data layer of send availability */
static void __maybe_unused h2s_notify_send(struct h2s *h2s)
{
struct wait_event *sw;
if (h2s->send_wait && !LIST_ADDED(&h2s->sending_list)) {
TRACE_POINT(H2_EV_STRM_WAKE, h2s->h2c->conn, h2s);
sw = h2s->send_wait;
sw->events &= ~SUB_RETRY_SEND;
LIST_ADDQ(&h2s->h2c->sending_list, &h2s->sending_list);
tasklet_wakeup(sw->tasklet);
}
}
/* alerts the data layer, trying to wake it up by all means, following
* this sequence :
* - if the h2s' data layer is subscribed to recv, then it's woken up for recv
* - if its subscribed to send, then it's woken up for send
* - if it was subscribed to neither, its ->wake() callback is called
* It is safe to call this function with a closed stream which doesn't have a
* conn_stream anymore.
*/
static void __maybe_unused h2s_alert(struct h2s *h2s)
{
TRACE_ENTER(H2_EV_H2S_WAKE, h2s->h2c->conn, h2s);
if (h2s->recv_wait || h2s->send_wait) {
h2s_notify_recv(h2s);
h2s_notify_send(h2s);
}
else if (h2s->cs && h2s->cs->data_cb->wake != NULL) {
TRACE_POINT(H2_EV_STRM_WAKE, h2s->h2c->conn, h2s);
h2s->cs->data_cb->wake(h2s->cs);
}
TRACE_LEAVE(H2_EV_H2S_WAKE, h2s->h2c->conn, h2s);
}
/* writes the 24-bit frame size <len> at address <frame> */
static inline __maybe_unused void h2_set_frame_size(void *frame, uint32_t len)
{
uint8_t *out = frame;
*out = len >> 16;
write_n16(out + 1, len);
}
/* reads <bytes> bytes from buffer <b> starting at relative offset <o> from the
* current pointer, dealing with wrapping, and stores the result in <dst>. It's
* the caller's responsibility to verify that there are at least <bytes> bytes
* available in the buffer's input prior to calling this function. The buffer
* is assumed not to hold any output data.
*/
static inline __maybe_unused void h2_get_buf_bytes(void *dst, size_t bytes,
const struct buffer *b, int o)
{
readv_bytes(dst, bytes, b_peek(b, o), b_wrap(b) - b_peek(b, o), b_orig(b));
}
static inline __maybe_unused uint16_t h2_get_n16(const struct buffer *b, int o)
{
return readv_n16(b_peek(b, o), b_wrap(b) - b_peek(b, o), b_orig(b));
}
static inline __maybe_unused uint32_t h2_get_n32(const struct buffer *b, int o)
{
return readv_n32(b_peek(b, o), b_wrap(b) - b_peek(b, o), b_orig(b));
}
static inline __maybe_unused uint64_t h2_get_n64(const struct buffer *b, int o)
{
return readv_n64(b_peek(b, o), b_wrap(b) - b_peek(b, o), b_orig(b));
}
/* Peeks an H2 frame header from offset <o> of buffer <b> into descriptor <h>.
* The algorithm is not obvious. It turns out that H2 headers are neither
* aligned nor do they use regular sizes. And to add to the trouble, the buffer
* may wrap so each byte read must be checked. The header is formed like this :
*
* b0 b1 b2 b3 b4 b5..b8
* +----------+---------+--------+----+----+----------------------+
* |len[23:16]|len[15:8]|len[7:0]|type|flag|sid[31:0] (big endian)|
* +----------+---------+--------+----+----+----------------------+
*
* Here we read a big-endian 64 bit word from h[1]. This way in a single read
* we get the sid properly aligned and ordered, and 16 bits of len properly
* ordered as well. The type and flags can be extracted using bit shifts from
* the word, and only one extra read is needed to fetch len[16:23].
* Returns zero if some bytes are missing, otherwise non-zero on success. The
* buffer is assumed not to contain any output data.
*/
static __maybe_unused int h2_peek_frame_hdr(const struct buffer *b, int o, struct h2_fh *h)
{
uint64_t w;
if (b_data(b) < o + 9)
return 0;
w = h2_get_n64(b, o + 1);
h->len = *(uint8_t*)b_peek(b, o) << 16;
h->sid = w & 0x7FFFFFFF; /* RFC7540#4.1: R bit must be ignored */
h->ff = w >> 32;
h->ft = w >> 40;
h->len += w >> 48;
return 1;
}
/* skip the next 9 bytes corresponding to the frame header possibly parsed by
* h2_peek_frame_hdr() above.
*/
static inline __maybe_unused void h2_skip_frame_hdr(struct buffer *b)
{
b_del(b, 9);
}
/* same as above, automatically advances the buffer on success */
static inline __maybe_unused int h2_get_frame_hdr(struct buffer *b, struct h2_fh *h)
{
int ret;
ret = h2_peek_frame_hdr(b, 0, h);
if (ret > 0)
h2_skip_frame_hdr(b);
return ret;
}
/* try to fragment the headers frame present at the beginning of buffer <b>,
* enforcing a limit of <mfs> bytes per frame. Returns 0 on failure, 1 on
* success. Typical causes of failure include a buffer not large enough to
* add extra frame headers. The existing frame size is read in the current
* frame. Its EH flag will be cleared if CONTINUATION frames need to be added,
* and its length will be adjusted. The stream ID for continuation frames will
* be copied from the initial frame's.
*/
static int h2_fragment_headers(struct buffer *b, uint32_t mfs)
{
size_t remain = b->data - 9;
int extra_frames = (remain - 1) / mfs;
size_t fsize;
char *fptr;
int frame;
if (b->data <= mfs + 9)
return 1;
/* Too large a frame, we need to fragment it using CONTINUATION
* frames. We start from the end and move tails as needed.
*/
if (b->data + extra_frames * 9 > b->size)
return 0;
for (frame = extra_frames; frame; frame--) {
fsize = ((remain - 1) % mfs) + 1;
remain -= fsize;
/* move data */
fptr = b->area + 9 + remain + (frame - 1) * 9;
memmove(fptr + 9, b->area + 9 + remain, fsize);
b->data += 9;
/* write new frame header */
h2_set_frame_size(fptr, fsize);
fptr[3] = H2_FT_CONTINUATION;
fptr[4] = (frame == extra_frames) ? H2_F_HEADERS_END_HEADERS : 0;
write_n32(fptr + 5, read_n32(b->area + 5));
}
b->area[4] &= ~H2_F_HEADERS_END_HEADERS;
h2_set_frame_size(b->area, remain);
return 1;
}
/* marks stream <h2s> as CLOSED and decrement the number of active streams for
* its connection if the stream was not yet closed. Please use this exclusively
* before closing a stream to ensure stream count is well maintained.
*/
static inline void h2s_close(struct h2s *h2s)
{
if (h2s->st != H2_SS_CLOSED) {
TRACE_ENTER(H2_EV_H2S_END, h2s->h2c->conn, h2s);
h2s->h2c->nb_streams--;
if (!h2s->id)
h2s->h2c->nb_reserved--;
if (h2s->cs) {
if (!(h2s->cs->flags & CS_FL_EOS) && !b_data(&h2s->rxbuf))
h2s_notify_recv(h2s);
}
TRACE_LEAVE(H2_EV_H2S_END, h2s->h2c->conn, h2s);
}
h2s->st = H2_SS_CLOSED;
}
/* detaches an H2 stream from its H2C and releases it to the H2S pool. */
/* h2s_destroy should only ever be called by the thread that owns the stream,
* that means that a tasklet should be used if we want to destroy the h2s
* from another thread
*/
static void h2s_destroy(struct h2s *h2s)
{
struct connection *conn = h2s->h2c->conn;
TRACE_ENTER(H2_EV_H2S_END, conn, h2s);
h2s_close(h2s);
eb32_delete(&h2s->by_id);
if (b_size(&h2s->rxbuf)) {
b_free(&h2s->rxbuf);
offer_buffers(NULL, tasks_run_queue);
}
if (h2s->send_wait != NULL)
h2s->send_wait->events &= ~SUB_RETRY_SEND;
if (h2s->recv_wait != NULL)
h2s->recv_wait->events &= ~SUB_RETRY_RECV;
/* There's no need to explicitly call unsubscribe here, the only
* reference left would be in the h2c send_list/fctl_list, and if
* we're in it, we're getting out anyway
*/
LIST_DEL_INIT(&h2s->list);
if (LIST_ADDED(&h2s->sending_list)) {
/* It should be OK to call tasklet_remove_from_tasklet_list()
* here, as only the thread responsible for the tasklet should
* be called here.
*/
tasklet_remove_from_tasklet_list(h2s->send_wait->tasklet);
LIST_DEL_INIT(&h2s->sending_list);
}
/* ditto, calling tasklet_free() here should be ok */
tasklet_free(h2s->wait_event.tasklet);
pool_free(pool_head_h2s, h2s);
TRACE_LEAVE(H2_EV_H2S_END, conn);
}
/* allocates a new stream <id> for connection <h2c> and adds it into h2c's
* stream tree. In case of error, nothing is added and NULL is returned. The
* causes of errors can be any failed memory allocation. The caller is
* responsible for checking if the connection may support an extra stream
* prior to calling this function.
*/
static struct h2s *h2s_new(struct h2c *h2c, int id)
{
struct h2s *h2s;
TRACE_ENTER(H2_EV_H2S_NEW, h2c->conn);
h2s = pool_alloc(pool_head_h2s);
if (!h2s)
goto out;
h2s->wait_event.tasklet = tasklet_new();
if (!h2s->wait_event.tasklet) {
pool_free(pool_head_h2s, h2s);
goto out;
}
h2s->send_wait = NULL;
h2s->recv_wait = NULL;
h2s->wait_event.tasklet->process = h2_deferred_shut;
h2s->wait_event.tasklet->context = h2s;
h2s->wait_event.events = 0;
LIST_INIT(&h2s->list);
LIST_INIT(&h2s->sending_list);
h2s->h2c = h2c;
h2s->cs = NULL;
h2s->sws = 0;
h2s->flags = H2_SF_NONE;
h2s->errcode = H2_ERR_NO_ERROR;
h2s->st = H2_SS_IDLE;
h2s->status = 0;
h2s->body_len = 0;
h2s->rxbuf = BUF_NULL;
if (h2c->flags & H2_CF_IS_BACK) {
h1m_init_req(&h2s->h1m);
h2s->h1m.err_pos = -1; // don't care about errors on the request path
h2s->h1m.flags |= H1_MF_TOLOWER;
} else {
h1m_init_res(&h2s->h1m);
h2s->h1m.err_pos = -1; // don't care about errors on the response path
h2s->h1m.flags |= H1_MF_TOLOWER;
}
h2s->by_id.key = h2s->id = id;
if (id > 0)
h2c->max_id = id;
else
h2c->nb_reserved++;
eb32_insert(&h2c->streams_by_id, &h2s->by_id);
h2c->nb_streams++;
h2c->stream_cnt++;
TRACE_LEAVE(H2_EV_H2S_NEW, h2c->conn, h2s);
return h2s;
out_free_h2s:
pool_free(pool_head_h2s, h2s);
out:
TRACE_DEVEL("leaving in error", H2_EV_H2S_ERR|H2_EV_H2S_END, h2c->conn);
return NULL;
}
/* creates a new stream <id> on the h2c connection and returns it, or NULL in
* case of memory allocation error.
*/
static struct h2s *h2c_frt_stream_new(struct h2c *h2c, int id)
{
struct session *sess = h2c->conn->owner;
struct conn_stream *cs;
struct h2s *h2s;
TRACE_ENTER(H2_EV_H2S_NEW, h2c->conn);
if (h2c->nb_streams >= h2_settings_max_concurrent_streams)
goto out;
h2s = h2s_new(h2c, id);
if (!h2s)
goto out;
cs = cs_new(h2c->conn);
if (!cs)
goto out_close;
cs->flags |= CS_FL_NOT_FIRST;
h2s->cs = cs;
cs->ctx = h2s;
h2c->nb_cs++;
if (stream_create_from_cs(cs) < 0)
goto out_free_cs;
/* We want the accept date presented to the next stream to be the one
* we have now, the handshake time to be null (since the next stream
* is not delayed by a handshake), and the idle time to count since
* right now.
*/
sess->accept_date = date;
sess->tv_accept = now;
sess->t_handshake = 0;
/* OK done, the stream lives its own life now */
if (h2_frt_has_too_many_cs(h2c))
h2c->flags |= H2_CF_DEM_TOOMANY;
TRACE_LEAVE(H2_EV_H2S_NEW, h2c->conn);
return h2s;
out_free_cs:
h2c->nb_cs--;
cs_free(cs);
h2s->cs = NULL;
out_close:
h2s_destroy(h2s);
out:
sess_log(sess);
TRACE_LEAVE(H2_EV_H2S_NEW|H2_EV_H2S_ERR|H2_EV_H2S_END, h2c->conn);
return NULL;
}
/* allocates a new stream associated to conn_stream <cs> on the h2c connection
* and returns it, or NULL in case of memory allocation error or if the highest
* possible stream ID was reached.
*/
static struct h2s *h2c_bck_stream_new(struct h2c *h2c, struct conn_stream *cs, struct session *sess)
{
struct h2s *h2s = NULL;
TRACE_ENTER(H2_EV_H2S_NEW, h2c->conn);
if (h2c->nb_streams >= h2c->streams_limit)
goto out;
if (h2_streams_left(h2c) < 1)
goto out;
/* Defer choosing the ID until we send the first message to create the stream */
h2s = h2s_new(h2c, 0);
if (!h2s)
goto out;
h2s->cs = cs;
h2s->sess = sess;
cs->ctx = h2s;
h2c->nb_cs++;
out:
if (likely(h2s))
TRACE_LEAVE(H2_EV_H2S_NEW, h2c->conn, h2s);
else
TRACE_LEAVE(H2_EV_H2S_NEW|H2_EV_H2S_ERR|H2_EV_H2S_END, h2c->conn, h2s);
return h2s;
}
/* try to send a settings frame on the connection. Returns > 0 on success, 0 if
* it couldn't do anything. It may return an error in h2c. See RFC7540#11.3 for
* the various settings codes.
*/
static int h2c_send_settings(struct h2c *h2c)
{
struct buffer *res;
char buf_data[100]; // enough for 15 settings
struct buffer buf;
int mfs;
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_SETTINGS, h2c->conn);
if (h2c_mux_busy(h2c, NULL)) {
h2c->flags |= H2_CF_DEM_MBUSY;
goto out;
}
chunk_init(&buf, buf_data, sizeof(buf_data));
chunk_memcpy(&buf,
"\x00\x00\x00" /* length : 0 for now */
"\x04\x00" /* type : 4 (settings), flags : 0 */
"\x00\x00\x00\x00", /* stream ID : 0 */
9);
if (h2c->flags & H2_CF_IS_BACK) {
/* send settings_enable_push=0 */
chunk_memcat(&buf, "\x00\x02\x00\x00\x00\x00", 6);
}
if (h2_settings_header_table_size != 4096) {
char str[6] = "\x00\x01"; /* header_table_size */
write_n32(str + 2, h2_settings_header_table_size);
chunk_memcat(&buf, str, 6);
}
if (h2_settings_initial_window_size != 65535) {
char str[6] = "\x00\x04"; /* initial_window_size */
write_n32(str + 2, h2_settings_initial_window_size);
chunk_memcat(&buf, str, 6);
}
if (h2_settings_max_concurrent_streams != 0) {
char str[6] = "\x00\x03"; /* max_concurrent_streams */
/* Note: 0 means "unlimited" for haproxy's config but not for
* the protocol, so never send this value!
*/
write_n32(str + 2, h2_settings_max_concurrent_streams);
chunk_memcat(&buf, str, 6);
}
mfs = h2_settings_max_frame_size;
if (mfs > global.tune.bufsize)
mfs = global.tune.bufsize;
if (!mfs)
mfs = global.tune.bufsize;
if (mfs != 16384) {
char str[6] = "\x00\x05"; /* max_frame_size */
/* note: similarly we could also emit MAX_HEADER_LIST_SIZE to
* match bufsize - rewrite size, but at the moment it seems
* that clients don't take care of it.
*/
write_n32(str + 2, mfs);
chunk_memcat(&buf, str, 6);
}
h2_set_frame_size(buf.area, buf.data - 9);
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
ret = b_istput(res, ist2(buf.area, buf.data));
if (unlikely(ret <= 0)) {
if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
h2c->flags |= H2_CF_DEM_MROOM;
}
else {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = 0;
}
}
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_SETTINGS, h2c->conn);
return ret;
}
/* Try to receive a connection preface, then upon success try to send our
* preface which is a SETTINGS frame. Returns > 0 on success or zero on
* missing data. It may return an error in h2c.
*/
static int h2c_frt_recv_preface(struct h2c *h2c)
{
int ret1;
int ret2;
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_PREFACE, h2c->conn);
ret1 = b_isteq(&h2c->dbuf, 0, b_data(&h2c->dbuf), ist(H2_CONN_PREFACE));
if (unlikely(ret1 <= 0)) {
if (ret1 < 0)
sess_log(h2c->conn->owner);
if (ret1 < 0 || conn_xprt_read0_pending(h2c->conn))
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
ret2 = 0;
goto out;
}
ret2 = h2c_send_settings(h2c);
if (ret2 > 0)
b_del(&h2c->dbuf, ret1);
out:
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_PREFACE, h2c->conn);
return ret2;
}
/* Try to send a connection preface, then upon success try to send our
* preface which is a SETTINGS frame. Returns > 0 on success or zero on
* missing data. It may return an error in h2c.
*/
static int h2c_bck_send_preface(struct h2c *h2c)
{
struct buffer *res;
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_PREFACE, h2c->conn);
if (h2c_mux_busy(h2c, NULL)) {
h2c->flags |= H2_CF_DEM_MBUSY;
goto out;
}
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
if (!b_data(res)) {
/* preface not yet sent */
ret = b_istput(res, ist(H2_CONN_PREFACE));
if (unlikely(ret <= 0)) {
if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
else {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = 0;
goto out;
}
}
}
ret = h2c_send_settings(h2c);
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_PREFACE, h2c->conn);
return ret;
}
/* try to send a GOAWAY frame on the connection to report an error or a graceful
* shutdown, with h2c->errcode as the error code. Returns > 0 on success or zero
* if nothing was done. It uses h2c->last_sid as the advertised ID, or copies it
* from h2c->max_id if it's not set yet (<0). In case of lack of room to write
* the message, it subscribes the requester (either <h2s> or <h2c>) to future
* notifications. It sets H2_CF_GOAWAY_SENT on success, and H2_CF_GOAWAY_FAILED
* on unrecoverable failure. It will not attempt to send one again in this last
* case so that it is safe to use h2c_error() to report such errors.
*/
static int h2c_send_goaway_error(struct h2c *h2c, struct h2s *h2s)
{
struct buffer *res;
char str[17];
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_GOAWAY, h2c->conn);
if (h2c->flags & H2_CF_GOAWAY_FAILED) {
ret = 1; // claim that it worked
goto out;
}
if (h2c_mux_busy(h2c, h2s)) {
if (h2s)
h2s->flags |= H2_SF_BLK_MBUSY;
else
h2c->flags |= H2_CF_DEM_MBUSY;
goto out;
}
/* len: 8, type: 7, flags: none, sid: 0 */
memcpy(str, "\x00\x00\x08\x07\x00\x00\x00\x00\x00", 9);
if (h2c->last_sid < 0)
h2c->last_sid = h2c->max_id;
write_n32(str + 9, h2c->last_sid);
write_n32(str + 13, h2c->errcode);
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
if (h2s)
h2s->flags |= H2_SF_BLK_MROOM;
else
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
ret = b_istput(res, ist2(str, 17));
if (unlikely(ret <= 0)) {
if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
if (h2s)
h2s->flags |= H2_SF_BLK_MROOM;
else
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
else {
/* we cannot report this error using GOAWAY, so we mark
* it and claim a success.
*/
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
h2c->flags |= H2_CF_GOAWAY_FAILED;
ret = 1;
goto out;
}
}
h2c->flags |= H2_CF_GOAWAY_SENT;
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_GOAWAY, h2c->conn);
return ret;
}
/* Try to send an RST_STREAM frame on the connection for the indicated stream
* during mux operations. This stream must be valid and cannot be closed
* already. h2s->id will be used for the stream ID and h2s->errcode will be
* used for the error code. h2s->st will be update to H2_SS_CLOSED if it was
* not yet.
*
* Returns > 0 on success or zero if nothing was done. In case of lack of room
* to write the message, it subscribes the stream to future notifications.
*/
static int h2s_send_rst_stream(struct h2c *h2c, struct h2s *h2s)
{
struct buffer *res;
char str[13];
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_RST, h2c->conn, h2s);
if (!h2s || h2s->st == H2_SS_CLOSED) {
ret = 1;
goto out;
}
/* RFC7540#5.4.2: To avoid looping, an endpoint MUST NOT send a
* RST_STREAM in response to a RST_STREAM frame.
*/
if (h2c->dsi == h2s->id && h2c->dft == H2_FT_RST_STREAM) {
ret = 1;
goto ignore;
}
if (h2c_mux_busy(h2c, h2s)) {
h2s->flags |= H2_SF_BLK_MBUSY;
goto out;
}
/* len: 4, type: 3, flags: none */
memcpy(str, "\x00\x00\x04\x03\x00", 5);
write_n32(str + 5, h2s->id);
write_n32(str + 9, h2s->errcode);
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
h2s->flags |= H2_SF_BLK_MROOM;
goto out;
}
ret = b_istput(res, ist2(str, 13));
if (unlikely(ret <= 0)) {
if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
h2s->flags |= H2_SF_BLK_MROOM;
goto out;
}
else {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = 0;
goto out;
}
}
ignore:
h2s->flags |= H2_SF_RST_SENT;
h2s_close(h2s);
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_RST, h2c->conn, h2s);
return ret;
}
/* Try to send an RST_STREAM frame on the connection for the stream being
* demuxed using h2c->dsi for the stream ID. It will use h2s->errcode as the
* error code, even if the stream is one of the dummy ones, and will update
* h2s->st to H2_SS_CLOSED if it was not yet.
*
* Returns > 0 on success or zero if nothing was done. In case of lack of room
* to write the message, it blocks the demuxer and subscribes it to future
* notifications. It's worth mentioning that an RST may even be sent for a
* closed stream.
*/
static int h2c_send_rst_stream(struct h2c *h2c, struct h2s *h2s)
{
struct buffer *res;
char str[13];
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_RST, h2c->conn, h2s);
/* RFC7540#5.4.2: To avoid looping, an endpoint MUST NOT send a
* RST_STREAM in response to a RST_STREAM frame.
*/
if (h2c->dft == H2_FT_RST_STREAM) {
ret = 1;
goto ignore;
}
if (h2c_mux_busy(h2c, h2s)) {
h2c->flags |= H2_CF_DEM_MBUSY;
goto out;
}
/* len: 4, type: 3, flags: none */
memcpy(str, "\x00\x00\x04\x03\x00", 5);
write_n32(str + 5, h2c->dsi);
write_n32(str + 9, h2s->errcode);
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
ret = b_istput(res, ist2(str, 13));
if (unlikely(ret <= 0)) {
if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
else {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = 0;
goto out;
}
}
ignore:
if (h2s->id) {
h2s->flags |= H2_SF_RST_SENT;
h2s_close(h2s);
}
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_RST, h2c->conn, h2s);
return ret;
}
/* try to send an empty DATA frame with the ES flag set to notify about the
* end of stream and match a shutdown(write). If an ES was already sent as
* indicated by HLOC/ERROR/RESET/CLOSED states, nothing is done. Returns > 0
* on success or zero if nothing was done. In case of lack of room to write the
* message, it subscribes the requesting stream to future notifications.
*/
static int h2_send_empty_data_es(struct h2s *h2s)
{
struct h2c *h2c = h2s->h2c;
struct buffer *res;
char str[9];
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_DATA|H2_EV_TX_EOI, h2c->conn, h2s);
if (h2s->st == H2_SS_HLOC || h2s->st == H2_SS_ERROR || h2s->st == H2_SS_CLOSED) {
ret = 1;
goto out;
}
if (h2c_mux_busy(h2c, h2s)) {
h2s->flags |= H2_SF_BLK_MBUSY;
goto out;
}
/* len: 0x000000, type: 0(DATA), flags: ES=1 */
memcpy(str, "\x00\x00\x00\x00\x01", 5);
write_n32(str + 5, h2s->id);
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
h2s->flags |= H2_SF_BLK_MROOM;
goto out;
}
ret = b_istput(res, ist2(str, 9));
if (likely(ret > 0)) {
h2s->flags |= H2_SF_ES_SENT;
}
else if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
h2s->flags |= H2_SF_BLK_MROOM;
}
else {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = 0;
}
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_DATA|H2_EV_TX_EOI, h2c->conn, h2s);
return ret;
}
/* wake a specific stream and assign its conn_stream som CS_FL_* flags among
* CS_FL_ERR_PENDING and CS_FL_ERROR if needed. The stream's state
* is automatically updated accordingly. If the stream is orphaned, it is
* destroyed.
*/
static void h2s_wake_one_stream(struct h2s *h2s)
{
struct h2c *h2c = h2s->h2c;
TRACE_ENTER(H2_EV_H2S_WAKE, h2c->conn, h2s);
if (!h2s->cs) {
/* this stream was already orphaned */
h2s_destroy(h2s);
TRACE_DEVEL("leaving with no h2s", H2_EV_H2S_WAKE, h2c->conn);
return;
}
if (conn_xprt_read0_pending(h2s->h2c->conn)) {
if (h2s->st == H2_SS_OPEN)
h2s->st = H2_SS_HREM;
else if (h2s->st == H2_SS_HLOC)
h2s_close(h2s);
}
if ((h2s->h2c->st0 >= H2_CS_ERROR || h2s->h2c->conn->flags & CO_FL_ERROR) ||
(h2s->h2c->last_sid > 0 && (!h2s->id || h2s->id > h2s->h2c->last_sid))) {
h2s->cs->flags |= CS_FL_ERR_PENDING;
if (h2s->cs->flags & CS_FL_EOS)
h2s->cs->flags |= CS_FL_ERROR;
if (h2s->st < H2_SS_ERROR)
h2s->st = H2_SS_ERROR;
}
h2s_alert(h2s);
TRACE_LEAVE(H2_EV_H2S_WAKE, h2c->conn);
}
/* wake the streams attached to the connection, whose id is greater than <last>
* or unassigned.
*/
static void h2_wake_some_streams(struct h2c *h2c, int last)
{
struct eb32_node *node;
struct h2s *h2s;
TRACE_ENTER(H2_EV_H2S_WAKE, h2c->conn);
/* Wake all streams with ID > last */
node = eb32_lookup_ge(&h2c->streams_by_id, last + 1);
while (node) {
h2s = container_of(node, struct h2s, by_id);
node = eb32_next(node);
h2s_wake_one_stream(h2s);
}
/* Wake all streams with unassigned ID (ID == 0) */
node = eb32_lookup(&h2c->streams_by_id, 0);
while (node) {
h2s = container_of(node, struct h2s, by_id);
if (h2s->id > 0)
break;
node = eb32_next(node);
h2s_wake_one_stream(h2s);
}
TRACE_LEAVE(H2_EV_H2S_WAKE, h2c->conn);
}
/* Wake up all blocked streams whose window size has become positive after the
* mux's initial window was adjusted. This should be done after having processed
* SETTINGS frames which have updated the mux's initial window size.
*/
static void h2c_unblock_sfctl(struct h2c *h2c)
{
struct h2s *h2s;
struct eb32_node *node;
TRACE_ENTER(H2_EV_H2C_WAKE, h2c->conn);
node = eb32_first(&h2c->streams_by_id);
while (node) {
h2s = container_of(node, struct h2s, by_id);
if (h2s->flags & H2_SF_BLK_SFCTL && h2s_mws(h2s) > 0) {
h2s->flags &= ~H2_SF_BLK_SFCTL;
LIST_DEL_INIT(&h2s->list);
if (h2s->send_wait)
LIST_ADDQ(&h2c->send_list, &h2s->list);
}
node = eb32_next(node);
}
TRACE_LEAVE(H2_EV_H2C_WAKE, h2c->conn);
}
/* processes a SETTINGS frame whose payload is <payload> for <plen> bytes, and
* ACKs it if needed. Returns > 0 on success or zero on missing data. It may
* return an error in h2c. The caller must have already verified frame length
* and stream ID validity. Described in RFC7540#6.5.
*/
static int h2c_handle_settings(struct h2c *h2c)
{
unsigned int offset;
int error;
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_SETTINGS, h2c->conn);
if (h2c->dff & H2_F_SETTINGS_ACK) {
if (h2c->dfl) {
error = H2_ERR_FRAME_SIZE_ERROR;
goto fail;
}
goto done;
}
/* process full frame only */
if (b_data(&h2c->dbuf) < h2c->dfl)
goto out0;
/* parse the frame */
for (offset = 0; offset < h2c->dfl; offset += 6) {
uint16_t type = h2_get_n16(&h2c->dbuf, offset);
int32_t arg = h2_get_n32(&h2c->dbuf, offset + 2);
switch (type) {
case H2_SETTINGS_INITIAL_WINDOW_SIZE:
/* we need to update all existing streams with the
* difference from the previous iws.
*/
if (arg < 0) { // RFC7540#6.5.2
error = H2_ERR_FLOW_CONTROL_ERROR;
goto fail;
}
h2c->miw = arg;
break;
case H2_SETTINGS_MAX_FRAME_SIZE:
if (arg < 16384 || arg > 16777215) { // RFC7540#6.5.2
error = H2_ERR_PROTOCOL_ERROR;
goto fail;
}
h2c->mfs = arg;
break;
case H2_SETTINGS_ENABLE_PUSH:
if (arg < 0 || arg > 1) { // RFC7540#6.5.2
error = H2_ERR_PROTOCOL_ERROR;
goto fail;
}
break;
case H2_SETTINGS_MAX_CONCURRENT_STREAMS:
if (h2c->flags & H2_CF_IS_BACK) {
/* the limit is only for the backend; for the frontend it is our limit */
if ((unsigned int)arg > h2_settings_max_concurrent_streams)
arg = h2_settings_max_concurrent_streams;
h2c->streams_limit = arg;
}
break;
}
}
/* need to ACK this frame now */
h2c->st0 = H2_CS_FRAME_A;
done:
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_SETTINGS, h2c->conn);
return 1;
fail:
if (!(h2c->flags & H2_CF_IS_BACK))
sess_log(h2c->conn->owner);
h2c_error(h2c, error);
out0:
TRACE_DEVEL("leaving with missing data or error", H2_EV_RX_FRAME|H2_EV_RX_SETTINGS, h2c->conn);
return 0;
}
/* try to send an ACK for a settings frame on the connection. Returns > 0 on
* success or one of the h2_status values.
*/
static int h2c_ack_settings(struct h2c *h2c)
{
struct buffer *res;
char str[9];
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_SETTINGS, h2c->conn);
if (h2c_mux_busy(h2c, NULL)) {
h2c->flags |= H2_CF_DEM_MBUSY;
goto out;
}
memcpy(str,
"\x00\x00\x00" /* length : 0 (no data) */
"\x04" "\x01" /* type : 4, flags : ACK */
"\x00\x00\x00\x00" /* stream ID */, 9);
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
ret = b_istput(res, ist2(str, 9));
if (unlikely(ret <= 0)) {
if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
h2c->flags |= H2_CF_DEM_MROOM;
}
else {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = 0;
}
}
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_SETTINGS, h2c->conn);
return ret;
}
/* processes a PING frame and schedules an ACK if needed. The caller must pass
* the pointer to the payload in <payload>. Returns > 0 on success or zero on
* missing data. The caller must have already verified frame length
* and stream ID validity.
*/
static int h2c_handle_ping(struct h2c *h2c)
{
/* schedule a response */
if (!(h2c->dff & H2_F_PING_ACK))
h2c->st0 = H2_CS_FRAME_A;
return 1;
}
/* Try to send a window update for stream id <sid> and value <increment>.
* Returns > 0 on success or zero on missing room or failure. It may return an
* error in h2c.
*/
static int h2c_send_window_update(struct h2c *h2c, int sid, uint32_t increment)
{
struct buffer *res;
char str[13];
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_WU, h2c->conn);
if (h2c_mux_busy(h2c, NULL)) {
h2c->flags |= H2_CF_DEM_MBUSY;
goto out;
}
/* length: 4, type: 8, flags: none */
memcpy(str, "\x00\x00\x04\x08\x00", 5);
write_n32(str + 5, sid);
write_n32(str + 9, increment);
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
ret = b_istput(res, ist2(str, 13));
if (unlikely(ret <= 0)) {
if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
h2c->flags |= H2_CF_DEM_MROOM;
}
else {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = 0;
}
}
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_WU, h2c->conn);
return ret;
}
/* try to send pending window update for the connection. It's safe to call it
* with no pending updates. Returns > 0 on success or zero on missing room or
* failure. It may return an error in h2c.
*/
static int h2c_send_conn_wu(struct h2c *h2c)
{
int ret = 1;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_WU, h2c->conn);
if (h2c->rcvd_c <= 0)
goto out;
if (!(h2c->flags & H2_CF_WINDOW_OPENED)) {
/* increase the advertised connection window to 2G on
* first update.
*/
h2c->flags |= H2_CF_WINDOW_OPENED;
h2c->rcvd_c += H2_INITIAL_WINDOW_INCREMENT;
}
/* send WU for the connection */
ret = h2c_send_window_update(h2c, 0, h2c->rcvd_c);
if (ret > 0)
h2c->rcvd_c = 0;
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_WU, h2c->conn);
return ret;
}
/* try to send pending window update for the current dmux stream. It's safe to
* call it with no pending updates. Returns > 0 on success or zero on missing
* room or failure. It may return an error in h2c.
*/
static int h2c_send_strm_wu(struct h2c *h2c)
{
int ret = 1;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_WU, h2c->conn);
if (h2c->rcvd_s <= 0)
goto out;
/* send WU for the stream */
ret = h2c_send_window_update(h2c, h2c->dsi, h2c->rcvd_s);
if (ret > 0)
h2c->rcvd_s = 0;
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_WU, h2c->conn);
return ret;
}
/* try to send an ACK for a ping frame on the connection. Returns > 0 on
* success, 0 on missing data or one of the h2_status values.
*/
static int h2c_ack_ping(struct h2c *h2c)
{
struct buffer *res;
char str[17];
int ret = 0;
TRACE_ENTER(H2_EV_TX_FRAME|H2_EV_TX_PING, h2c->conn);
if (b_data(&h2c->dbuf) < 8)
goto out;
if (h2c_mux_busy(h2c, NULL)) {
h2c->flags |= H2_CF_DEM_MBUSY;
goto out;
}
memcpy(str,
"\x00\x00\x08" /* length : 8 (same payload) */
"\x06" "\x01" /* type : 6, flags : ACK */
"\x00\x00\x00\x00" /* stream ID */, 9);
/* copy the original payload */
h2_get_buf_bytes(str + 9, 8, &h2c->dbuf, 0);
res = br_tail(h2c->mbuf);
retry:
if (!h2_get_buf(h2c, res)) {
h2c->flags |= H2_CF_MUX_MALLOC;
h2c->flags |= H2_CF_DEM_MROOM;
goto out;
}
ret = b_istput(res, ist2(str, 17));
if (unlikely(ret <= 0)) {
if (!ret) {
if ((res = br_tail_add(h2c->mbuf)) != NULL)
goto retry;
h2c->flags |= H2_CF_MUX_MFULL;
h2c->flags |= H2_CF_DEM_MROOM;
}
else {
h2c_error(h2c, H2_ERR_INTERNAL_ERROR);
ret = 0;
}
}
out:
TRACE_LEAVE(H2_EV_TX_FRAME|H2_EV_TX_PING, h2c->conn);
return ret;
}
/* processes a WINDOW_UPDATE frame whose payload is <payload> for <plen> bytes.
* Returns > 0 on success or zero on missing data. It may return an error in
* h2c or h2s. The caller must have already verified frame length and stream ID
* validity. Described in RFC7540#6.9.
*/
static int h2c_handle_window_update(struct h2c *h2c, struct h2s *h2s)
{
int32_t inc;
int error;
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_WU, h2c->conn);
/* process full frame only */
if (b_data(&h2c->dbuf) < h2c->dfl)
goto out0;
inc = h2_get_n32(&h2c->dbuf, 0);
if (h2c->dsi != 0) {
/* stream window update */
/* it's not an error to receive WU on a closed stream */
if (h2s->st == H2_SS_CLOSED)
goto done;
if (!inc) {
error = H2_ERR_PROTOCOL_ERROR;
goto strm_err;
}
if (h2s_mws(h2s) >= 0 && h2s_mws(h2s) + inc < 0) {
error = H2_ERR_FLOW_CONTROL_ERROR;
goto strm_err;
}
h2s->sws += inc;
if (h2s_mws(h2s) > 0 && (h2s->flags & H2_SF_BLK_SFCTL)) {
h2s->flags &= ~H2_SF_BLK_SFCTL;
LIST_DEL_INIT(&h2s->list);
if (h2s->send_wait)
LIST_ADDQ(&h2c->send_list, &h2s->list);
}
}
else {
/* connection window update */
if (!inc) {
error = H2_ERR_PROTOCOL_ERROR;
goto conn_err;
}
if (h2c->mws >= 0 && h2c->mws + inc < 0) {
error = H2_ERR_FLOW_CONTROL_ERROR;
goto conn_err;
}
h2c->mws += inc;
}
done:
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_WU, h2c->conn);
return 1;
conn_err:
h2c_error(h2c, error);
out0:
TRACE_DEVEL("leaving on missing data or error", H2_EV_RX_FRAME|H2_EV_RX_WU, h2c->conn);
return 0;
strm_err:
h2s_error(h2s, error);
h2c->st0 = H2_CS_FRAME_E;
TRACE_DEVEL("leaving on stream error", H2_EV_RX_FRAME|H2_EV_RX_WU, h2c->conn);
return 0;
}
/* processes a GOAWAY frame, and signals all streams whose ID is greater than
* the last ID. Returns > 0 on success or zero on missing data. The caller must
* have already verified frame length and stream ID validity. Described in
* RFC7540#6.8.
*/
static int h2c_handle_goaway(struct h2c *h2c)
{
int last;
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_GOAWAY, h2c->conn);
/* process full frame only */
if (b_data(&h2c->dbuf) < h2c->dfl) {
TRACE_DEVEL("leaving on missing data", H2_EV_RX_FRAME|H2_EV_RX_GOAWAY, h2c->conn);
return 0;
}
last = h2_get_n32(&h2c->dbuf, 0);
h2c->errcode = h2_get_n32(&h2c->dbuf, 4);
if (h2c->last_sid < 0)
h2c->last_sid = last;
h2_wake_some_streams(h2c, last);
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_GOAWAY, h2c->conn);
return 1;
}
/* processes a PRIORITY frame, and either skips it or rejects if it is
* invalid. Returns > 0 on success or zero on missing data. It may return an
* error in h2c. The caller must have already verified frame length and stream
* ID validity. Described in RFC7540#6.3.
*/
static int h2c_handle_priority(struct h2c *h2c)
{
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_PRIO, h2c->conn);
/* process full frame only */
if (b_data(&h2c->dbuf) < h2c->dfl) {
TRACE_DEVEL("leaving on missing data", H2_EV_RX_FRAME|H2_EV_RX_PRIO, h2c->conn);
return 0;
}
if (h2_get_n32(&h2c->dbuf, 0) == h2c->dsi) {
/* 7540#5.3 : can't depend on itself */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
TRACE_DEVEL("leaving on error", H2_EV_RX_FRAME|H2_EV_RX_PRIO, h2c->conn);
return 0;
}
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_PRIO, h2c->conn);
return 1;
}
/* processes an RST_STREAM frame, and sets the 32-bit error code on the stream.
* Returns > 0 on success or zero on missing data. The caller must have already
* verified frame length and stream ID validity. Described in RFC7540#6.4.
*/
static int h2c_handle_rst_stream(struct h2c *h2c, struct h2s *h2s)
{
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_RST|H2_EV_RX_EOI, h2c->conn, h2s);
/* process full frame only */
if (b_data(&h2c->dbuf) < h2c->dfl) {
TRACE_DEVEL("leaving on missing data", H2_EV_RX_FRAME|H2_EV_RX_RST|H2_EV_RX_EOI, h2c->conn, h2s);
return 0;
}
/* late RST, already handled */
if (h2s->st == H2_SS_CLOSED) {
TRACE_DEVEL("leaving on stream closed", H2_EV_RX_FRAME|H2_EV_RX_RST|H2_EV_RX_EOI, h2c->conn, h2s);
return 1;
}
h2s->errcode = h2_get_n32(&h2c->dbuf, 0);
h2s_close(h2s);
if (h2s->cs) {
cs_set_error(h2s->cs);
h2s_alert(h2s);
}
h2s->flags |= H2_SF_RST_RCVD;
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_RST|H2_EV_RX_EOI, h2c->conn, h2s);
return 1;
}
/* processes a HEADERS frame. Returns h2s on success or NULL on missing data.
* It may return an error in h2c or h2s. The caller must consider that the
* return value is the new h2s in case one was allocated (most common case).
* Described in RFC7540#6.2. Most of the
* errors here are reported as connection errors since it's impossible to
* recover from such errors after the compression context has been altered.
*/
static struct h2s *h2c_frt_handle_headers(struct h2c *h2c, struct h2s *h2s)
{
struct buffer rxbuf = BUF_NULL;
unsigned long long body_len = 0;
uint32_t flags = 0;
int error;
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_HDR, h2c->conn, h2s);
if (!b_size(&h2c->dbuf))
goto out; // empty buffer
if (b_data(&h2c->dbuf) < h2c->dfl && !b_full(&h2c->dbuf))
goto out; // incomplete frame
/* now either the frame is complete or the buffer is complete */
if (h2s->st != H2_SS_IDLE) {
/* The stream exists/existed, this must be a trailers frame */
if (h2s->st != H2_SS_CLOSED) {
error = h2c_decode_headers(h2c, &h2s->rxbuf, &h2s->flags, &body_len);
/* unrecoverable error ? */
if (h2c->st0 >= H2_CS_ERROR)
goto out;
if (error == 0)
goto out; // missing data
if (error < 0) {
/* Failed to decode this frame (e.g. too large request)
* but the HPACK decompressor is still synchronized.
*/
h2s_error(h2s, H2_ERR_INTERNAL_ERROR);
h2c->st0 = H2_CS_FRAME_E;
goto out;
}
goto done;
}
/* the connection was already killed by an RST, let's consume
* the data and send another RST.
*/
error = h2c_decode_headers(h2c, &rxbuf, &flags, &body_len);
h2s = (struct h2s*)h2_error_stream;
goto send_rst;
}
else if (h2c->dsi <= h2c->max_id || !(h2c->dsi & 1)) {
/* RFC7540#5.1.1 stream id > prev ones, and must be odd here */
error = H2_ERR_PROTOCOL_ERROR;
sess_log(h2c->conn->owner);
goto conn_err;
}
else if (h2c->flags & H2_CF_DEM_TOOMANY)
goto out; // IDLE but too many cs still present
error = h2c_decode_headers(h2c, &rxbuf, &flags, &body_len);
/* unrecoverable error ? */
if (h2c->st0 >= H2_CS_ERROR)
goto out;
if (error <= 0) {
if (error == 0)
goto out; // missing data
/* Failed to decode this stream (e.g. too large request)
* but the HPACK decompressor is still synchronized.
*/
h2s = (struct h2s*)h2_error_stream;
goto send_rst;
}
/* Note: we don't emit any other logs below because ff we return
* positively from h2c_frt_stream_new(), the stream will report the error,
* and if we return in error, h2c_frt_stream_new() will emit the error.
*/
h2s = h2c_frt_stream_new(h2c, h2c->dsi);
if (!h2s) {
h2s = (struct h2s*)h2_refused_stream;
goto send_rst;
}
h2s->st = H2_SS_OPEN;
h2s->rxbuf = rxbuf;
h2s->flags |= flags;
h2s->body_len = body_len;
done:
if (h2c->dff & H2_F_HEADERS_END_STREAM)
h2s->flags |= H2_SF_ES_RCVD;
if (h2s->flags & H2_SF_ES_RCVD) {
if (h2s->st == H2_SS_OPEN)
h2s->st = H2_SS_HREM;
else
h2s_close(h2s);
}
/* update the max stream ID if the request is being processed */
if (h2s->id > h2c->max_id)
h2c->max_id = h2s->id;
TRACE_USER("rcvd H2 request ", H2_EV_RX_FRAME|H2_EV_RX_HDR|H2_EV_STRM_NEW, h2c->conn,, &rxbuf);
return h2s;
conn_err:
h2c_error(h2c, error);
goto out;
out:
h2_release_buf(h2c, &rxbuf);
TRACE_DEVEL("leaving on missing data or error", H2_EV_RX_FRAME|H2_EV_RX_HDR, h2c->conn, h2s);
return NULL;
send_rst:
/* make the demux send an RST for the current stream. We may only
* do this if we're certain that the HEADERS frame was properly
* decompressed so that the HPACK decoder is still kept up to date.
*/
h2_release_buf(h2c, &rxbuf);
h2c->st0 = H2_CS_FRAME_E;
TRACE_USER("rejected H2 request", H2_EV_RX_FRAME|H2_EV_RX_HDR|H2_EV_STRM_NEW|H2_EV_STRM_END, h2c->conn,, &rxbuf);
TRACE_DEVEL("leaving on error", H2_EV_RX_FRAME|H2_EV_RX_HDR, h2c->conn, h2s);
return h2s;
}
/* processes a HEADERS frame. Returns h2s on success or NULL on missing data.
* It may return an error in h2c or h2s. Described in RFC7540#6.2. Most of the
* errors here are reported as connection errors since it's impossible to
* recover from such errors after the compression context has been altered.
*/
static struct h2s *h2c_bck_handle_headers(struct h2c *h2c, struct h2s *h2s)
{
struct buffer rxbuf = BUF_NULL;
unsigned long long body_len = 0;
uint32_t flags = 0;
int error;
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_HDR, h2c->conn, h2s);
if (!b_size(&h2c->dbuf))
goto fail; // empty buffer
if (b_data(&h2c->dbuf) < h2c->dfl && !b_full(&h2c->dbuf))
goto fail; // incomplete frame
if (h2s->st != H2_SS_CLOSED) {
error = h2c_decode_headers(h2c, &h2s->rxbuf, &h2s->flags, &h2s->body_len);
}
else {
/* the connection was already killed by an RST, let's consume
* the data and send another RST.
*/
error = h2c_decode_headers(h2c, &rxbuf, &flags, &body_len);
h2s = (struct h2s*)h2_error_stream;
h2c->st0 = H2_CS_FRAME_E;
goto send_rst;
}
/* unrecoverable error ? */
if (h2c->st0 >= H2_CS_ERROR)
goto fail;
if (h2s->st != H2_SS_OPEN && h2s->st != H2_SS_HLOC) {
/* RFC7540#5.1 */
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
h2c->st0 = H2_CS_FRAME_E;
goto fail;
}
if (error <= 0) {
if (error == 0)
goto fail; // missing data
/* stream error : send RST_STREAM */
h2s_error(h2s, H2_ERR_PROTOCOL_ERROR);
h2c->st0 = H2_CS_FRAME_E;
goto fail;
}
if (h2c->dff & H2_F_HEADERS_END_STREAM)
h2s->flags |= H2_SF_ES_RCVD;
if (h2s->cs && h2s->cs->flags & CS_FL_ERROR && h2s->st < H2_SS_ERROR)
h2s->st = H2_SS_ERROR;
else if (h2s->flags & H2_SF_ES_RCVD) {
if (h2s->st == H2_SS_OPEN)
h2s->st = H2_SS_HREM;
else if (h2s->st == H2_SS_HLOC)
h2s_close(h2s);
}
TRACE_USER("rcvd H2 response", H2_EV_RX_FRAME|H2_EV_RX_HDR, h2c->conn,, &h2s->rxbuf);
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_HDR, h2c->conn, h2s);
return h2s;
fail:
TRACE_DEVEL("leaving on missing data or error", H2_EV_RX_FRAME|H2_EV_RX_HDR, h2c->conn, h2s);
return NULL;
send_rst:
/* make the demux send an RST for the current stream. We may only
* do this if we're certain that the HEADERS frame was properly
* decompressed so that the HPACK decoder is still kept up to date.
*/
h2_release_buf(h2c, &rxbuf);
h2c->st0 = H2_CS_FRAME_E;
TRACE_USER("rejected H2 response", H2_EV_RX_FRAME|H2_EV_RX_HDR|H2_EV_STRM_NEW|H2_EV_STRM_END, h2c->conn,, &rxbuf);
TRACE_DEVEL("leaving on error", H2_EV_RX_FRAME|H2_EV_RX_HDR, h2c->conn, h2s);
return h2s;
}
/* processes a DATA frame. Returns > 0 on success or zero on missing data.
* It may return an error in h2c or h2s. Described in RFC7540#6.1.
*/
static int h2c_frt_handle_data(struct h2c *h2c, struct h2s *h2s)
{
int error;
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_DATA, h2c->conn, h2s);
/* note that empty DATA frames are perfectly valid and sometimes used
* to signal an end of stream (with the ES flag).
*/
if (!b_size(&h2c->dbuf) && h2c->dfl)
goto fail; // empty buffer
if (b_data(&h2c->dbuf) < h2c->dfl && !b_full(&h2c->dbuf))
goto fail; // incomplete frame
/* now either the frame is complete or the buffer is complete */
if (h2s->st != H2_SS_OPEN && h2s->st != H2_SS_HLOC) {
/* RFC7540#6.1 */
error = H2_ERR_STREAM_CLOSED;
goto strm_err;
}
if ((h2s->flags & H2_SF_DATA_CLEN) && (h2c->dfl - h2c->dpl) > h2s->body_len) {
/* RFC7540#8.1.2 */
error = H2_ERR_PROTOCOL_ERROR;
goto strm_err;
}
if (!h2_frt_transfer_data(h2s))
goto fail;
/* call the upper layers to process the frame, then let the upper layer
* notify the stream about any change.
*/
if (!h2s->cs) {
/* The upper layer has already closed, this may happen on
* 4xx/redirects during POST, or when receiving a response
* from an H2 server after the client has aborted.
*/
error = H2_ERR_CANCEL;
goto strm_err;
}
if (h2c->st0 >= H2_CS_ERROR)
goto fail;
if (h2s->st >= H2_SS_ERROR) {
/* stream error : send RST_STREAM */
h2c->st0 = H2_CS_FRAME_E;
}
/* check for completion : the callee will change this to FRAME_A or
* FRAME_H once done.
*/
if (h2c->st0 == H2_CS_FRAME_P)
goto fail;
/* last frame */
if (h2c->dff & H2_F_DATA_END_STREAM) {
h2s->flags |= H2_SF_ES_RCVD;
if (h2s->st == H2_SS_OPEN)
h2s->st = H2_SS_HREM;
else
h2s_close(h2s);
if (h2s->flags & H2_SF_DATA_CLEN && h2s->body_len) {
/* RFC7540#8.1.2 */
error = H2_ERR_PROTOCOL_ERROR;
goto strm_err;
}
}
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_DATA, h2c->conn, h2s);
return 1;
strm_err:
h2s_error(h2s, error);
h2c->st0 = H2_CS_FRAME_E;
fail:
TRACE_DEVEL("leaving on missing data or error", H2_EV_RX_FRAME|H2_EV_RX_DATA, h2c->conn, h2s);
return 0;
}
/* check that the current frame described in h2c->{dsi,dft,dfl,dff,...} is
* valid for the current stream state. This is needed only after parsing the
* frame header but in practice it can be performed at any time during
* H2_CS_FRAME_P since no state transition happens there. Returns >0 on success
* or 0 in case of error, in which case either h2s or h2c will carry an error.
*/
static int h2_frame_check_vs_state(struct h2c *h2c, struct h2s *h2s)
{
TRACE_ENTER(H2_EV_RX_FRAME|H2_EV_RX_FHDR, h2c->conn, h2s);
if (h2s->st == H2_SS_IDLE &&
h2c->dft != H2_FT_HEADERS && h2c->dft != H2_FT_PRIORITY) {
/* RFC7540#5.1: any frame other than HEADERS or PRIORITY in
* this state MUST be treated as a connection error
*/
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
if (!h2c->nb_streams && !(h2c->flags & H2_CF_IS_BACK)) {
/* only log if no other stream can report the error */
sess_log(h2c->conn->owner);
}
TRACE_DEVEL("leaving in error (idle&!hdrs&!prio)", H2_EV_RX_FRAME|H2_EV_RX_FHDR|H2_EV_PROTO_ERR, h2c->conn, h2s);
return 0;
}
if (h2s->st == H2_SS_IDLE && (h2c->flags & H2_CF_IS_BACK)) {
/* only PUSH_PROMISE would be permitted here */
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
TRACE_DEVEL("leaving in error (idle&back)", H2_EV_RX_FRAME|H2_EV_RX_FHDR|H2_EV_PROTO_ERR, h2c->conn, h2s);
return 0;
}
if (h2s->st == H2_SS_HREM && h2c->dft != H2_FT_WINDOW_UPDATE &&
h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY) {
/* RFC7540#5.1: any frame other than WU/PRIO/RST in
* this state MUST be treated as a stream error.
* 6.2, 6.6 and 6.10 further mandate that HEADERS/
* PUSH_PROMISE/CONTINUATION cause connection errors.
*/
if (h2_ft_bit(h2c->dft) & H2_FT_HDR_MASK)
h2c_error(h2c, H2_ERR_PROTOCOL_ERROR);
else
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
TRACE_DEVEL("leaving in error (hrem&!wu&!rst&!prio)", H2_EV_RX_FRAME|H2_EV_RX_FHDR|H2_EV_PROTO_ERR, h2c->conn, h2s);
return 0;
}
/* Below the management of frames received in closed state is a
* bit hackish because the spec makes strong differences between
* streams closed by receiving RST, sending RST, and seeing ES
* in both directions. In addition to this, the creation of a
* new stream reusing the identifier of a closed one will be
* detected here. Given that we cannot keep track of all closed
* streams forever, we consider that unknown closed streams were
* closed on RST received, which allows us to respond with an
* RST without breaking the connection (eg: to abort a transfer).
* Some frames have to be silently ignored as well.
*/
if (h2s->st == H2_SS_CLOSED && h2c->dsi) {
if (!(h2c->flags & H2_CF_IS_BACK) && h2_ft_bit(h2c->dft) & H2_FT_HDR_MASK) {
/* #5.1.1: The identifier of a newly
* established stream MUST be numerically
* greater than all streams that the initiating
* endpoint has opened or reserved. This
* governs streams that are opened using a
* HEADERS frame and streams that are reserved
* using PUSH_PROMISE. An endpoint that
* receives an unexpected stream identifier
* MUST respond with a connection error.
*/
h2c_error(h2c, H2_ERR_STREAM_CLOSED);
TRACE_DEVEL("leaving in error (closed&hdrmask)", H2_EV_RX_FRAME|H2_EV_RX_FHDR|H2_EV_PROTO_ERR, h2c->conn, h2s);
return 0;
}
if (h2s->flags & H2_SF_RST_RCVD &&
!(h2_ft_bit(h2c->dft) & (H2_FT_HDR_MASK | H2_FT_RST_STREAM_BIT | H2_FT_PRIORITY_BIT | H2_FT_WINDOW_UPDATE_BIT))) {
/* RFC7540#5.1:closed: an endpoint that
* receives any frame other than PRIORITY after
* receiving a RST_STREAM MUST treat that as a
* stream error of type STREAM_CLOSED.
*
* Note that old streams fall into this category
* and will lead to an RST being sent.
*
* However, we cannot generalize this to all frame types. Those
* carrying compression state must still be processed before
* being dropped or we'll desynchronize the decoder. This can
* happen with request trailers received after sending an
* RST_STREAM, or with header/trailers responses received after
* sending RST_STREAM (aborted stream).
*
* In addition, since our CLOSED streams always carry the
* RST_RCVD bit, we don't want to accidently catch valid
* frames for a closed stream, i.e. RST/PRIO/WU.
*/
h2s_error(h2s, H2_ERR_STREAM_CLOSED);
h2c->st0 = H2_CS_FRAME_E;
TRACE_DEVEL("leaving in error (rst_rcvd&!hdrmask)", H2_EV_RX_FRAME|H2_EV_RX_FHDR|H2_EV_PROTO_ERR, h2c->conn, h2s);
return 0;
}
/* RFC7540#5.1:closed: if this state is reached as a
* result of sending a RST_STREAM frame, the peer that
* receives the RST_STREAM might have already sent
* frames on the stream that cannot be withdrawn. An
* endpoint MUST ignore frames that it receives on
* closed streams after it has sent a RST_STREAM
* frame. An endpoint MAY choose to limit the period
* over which it ignores frames and treat frames that
* arrive after this time as being in error.
*/
if (h2s->id && !(h2s->flags & H2_SF_RST_SENT)) {
/* RFC7540#5.1:closed: any frame other than
* PRIO/WU/RST in this state MUST be treated as
* a connection error
*/
if (h2c->dft != H2_FT_RST_STREAM &&
h2c->dft != H2_FT_PRIORITY &&
h2c->dft != H2_FT_WINDOW_UPDATE) {
h2c_error(h2c, H2_ERR_STREAM_CLOSED);
TRACE_DEVEL("leaving in error (rst_sent&!rst&!prio&!wu)", H2_EV_RX_FRAME|H2_EV_RX_FHDR|H2_EV_PROTO_ERR, h2c->conn, h2s);
return 0;
}
}
}
TRACE_LEAVE(H2_EV_RX_FRAME|H2_EV_RX_FHDR, h2c->conn, h2s);
return 1;
}
/* process Rx frames to be demultiplexed */
static void h2_process_demux(struct h2c *h2c)
{
struct h2s *h2s = NULL, *tmp_h2s;
struct h2_fh hdr;
unsigned int padlen = 0;
int32_t old_iw = h2c->miw;
TRACE_ENTER(H2_EV_H2C_WAKE, h2c->conn);
if (h2c->st0 >= H2_CS_ERROR)
goto out;
if (unlikely(h2c->st0 < H2_CS_FRAME_H)) {
if (h2c->st0 == H2_CS_PREFACE) {
TRACE_STATE("expecting preface", H2_EV_RX_PREFACE, h2c->conn);
if (h2c->flags & H2_CF_IS_BACK)
goto out;
if (unlikely(h2c_frt_recv_preface(h2c) <= 0)) {
/* RFC7540#3.5: a GOAWAY frame MAY be omitted */
if (h2c->st0 == H2_CS_ERROR) {
TRACE_PROTO("failed to receive preface", H2_EV_RX_PREFACE|H2_EV_PROTO_ERR, h2c->conn);
h2c->st0 = H2_CS_ERROR2;
sess_log(h2c->conn->owner);
}
goto fail;
}
TRACE_PROTO("received preface", H2_EV_RX_PREFACE, h2c->conn);