10 HTTP/2 与 HTTP/3


 TL;DR
HTTP/2 的帧与 stream 在 nginx 里怎么落地,HTTP/3 的 QUIC 怎么被接住,以及两者的状态机分别挪到了哪里——为什么 worker_connections 在 HTTP/2 下要重新算。
难度 中等

上一章拆的是 HTTP/1.1:一条连接、一个请求、一个顺序状态机。
这一章做对照 —— HTTP/2 把这套结构换成了什么,HTTP/3 又把什么换掉了。

读完之后你应该能回答:

  1. HTTP/2 的多路复用,在 nginx 的代码里具体落在哪个结构体上?
  2. HTTP/2 的帧解析状态机放在哪?它和 HTTP/1.1 的请求行解析器是什么关系?
  3. HPACK 和 QPACK 在 nginx 里各自对应哪几个文件?
  4. HTTP/3 的 QUIC 是怎么从 UDP socket 接到 HTTP 请求上的?
  5. 为什么 worker_connections 在 HTTP/2 下的换算和 HTTP/1.1 不一样?

本文所有行号基于 /work/ai/cwork/nginx,版本是 nginx 1.31.11
(mainline,HEAD e76b6746c)。

10.1 三层协议,三种状态机

先把三者的差别摆平。它们不是「同一个东西的新旧版本」,
而是三种不同的连接组织方式
:

维度 HTTP/1.1 HTTP/2 HTTP/3
传输 TCP TCP UDP + QUIC
一条连接上有几个请求 1 个(顺序) N 个(并发) N 个(并发)
请求怎么被切分 文本行(CRLF 分隔) 帧(9 字节头 + 载荷) 帧(变长整数 + 载荷)
头压缩 无 HPACK QPACK
请求行 有 没有(拆成伪头) 没有
nginx 里的状态机 r->state(字节级) h2c->state.handler(帧级) st->state(帧级)
请求对象怎么造 一个 ngx_http_request_t 每 stream 一个 每 stream 一个
复用连接的手段 Connection: keep-alive 连接本身就是复用的 QUIC 连接 ID

一句话概括三者的差别:

HTTP/1.1:  连接 ──── 请求1 ──── 请求2 ──── 请求3        (排队,一趟一个)
HTTP/2:    连接 ═╤═ stream 1
                 ╞═ stream 2   (并发,一趟多个)
                 ╘═ stream 3
HTTP/3:    QUIC 连接 ═╤═ stream 1
                      ╞═ stream 2   (并发,底层换成了 UDP)
                      ╘═ stream 3

关键洞察:HTTP/2 和 HTTP/3 的请求处理几乎共用同一套 HTTP 语义代码。
HTTP/2 在 src/http/v2/,HTTP/3 在 src/http/v3/,
但它们最终都调用同一个 ngx_http_process_request()
(src/http/ngx_http_request.c:2126)——
也就是说,location 查找、上游、内容处理这些逻辑是共享的,
两套协议各自只负责「把字节变成 ngx_http_request_t」这一段。

这就是为什么 nginx 加 HTTP/2 的改动量比想象中小:
它没有重写请求处理,只是换了一个前端。

10.2 HTTP/2:帧 + stream

10.2.1 前言嗅探:怎么知道对端说的是 HTTP/2

HTTP/2 的第一个字节是一段固定的前言
PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n。
nginx 在 ngx_http_wait_request_handler()
(src/http/ngx_http_request.c:377)里做嗅探,
嗅探代码在这段的末尾:

// src/http/ngx_http_request.c:500-521
#if (NGX_HTTP_V2)

    h2scf = ngx_http_get_module_srv_conf(hc->conf_ctx, ngx_http_v2_module);

    if (!hc->ssl && (h2scf->enable || hc->addr_conf->http2)) {

        size = ngx_min(sizeof(NGX_HTTP_V2_PREFACE) - 1,
                       (size_t) (b->last - b->pos));

        if (ngx_memcmp(b->pos, NGX_HTTP_V2_PREFACE, size) == 0) {

            if (size == sizeof(NGX_HTTP_V2_PREFACE) - 1) {
                ngx_http_v2_init(rev);
                return;
            }

            ngx_post_event(rev, &ngx_posted_events);
            return;
        }
    }
#endif

注意 !hc->ssl —— 走 TLS 时不做嗅探,
因为 ALPN 协商已经确定了协议(src/http/ngx_http_request.c:853)。

10.2.2 连接的建立

ngx_http_v2_init()(src/http/v2/ngx_http_v2.c:205)干的事:

// src/http/v2/ngx_http_v2.c:287-296
    h2c->state.handler = ngx_http_v2_state_preface;

    ngx_queue_init(&h2c->waiting);
    ngx_queue_init(&h2c->closed);

    c->data = h2c;

    if (ngx_exiting) {
        ngx_http_v2_finalize_connection(h2c, NGX_HTTP_V2_NO_ERROR);
        return;

h2c->state.handler 就是 HTTP/2 的状态机——
一个函数指针,指向当前该执行哪个帧处理器。
这是和 HTTP/1.1 最大的结构差别:

HTTP/1.1 HTTP/2
状态存哪 r->state(一个 enum) h2c->state.handler(一个函数指针)
粒度 字节 帧
谁能改状态 只有解析器 任何帧处理器都能改

因为是函数指针,HTTP/2 的状态机可以在不同层次之间跳转:
一个 HEADERS 帧可能因为载荷不完整而返回去等更多数据,
也可能因为收到 CONTINUATION 帧而跳到另一个处理器。

10.2.3 帧状态机

帧类型到处理器的映射是一张函数指针表
(src/http/v2/ngx_http_v2.c:187):

// src/http/v2/ngx_http_v2.c:187-198
static ngx_http_v2_handler_pt ngx_http_v2_frame_states[] = {
    ngx_http_v2_state_data,               /* NGX_HTTP_V2_DATA_FRAME */
    ngx_http_v2_state_headers,            /* NGX_HTTP_V2_HEADERS_FRAME */
    ngx_http_v2_state_priority,           /* NGX_HTTP_V2_PRIORITY_FRAME */
    ngx_http_v2_state_rst_stream,         /* NGX_HTTP_V2_RST_STREAM_FRAME */
    ngx_http_v2_state_settings,           /* NGX_HTTP_V2_SETTINGS_FRAME */
    ngx_http_v2_state_push_promise,       /* NGX_HTTP_V2_PUSH_PROMISE_FRAME */
    ngx_http_v2_state_ping,               /* NGX_HTTP_V2_PING_FRAME */
    ngx_http_v2_state_goaway,             /* NGX_HTTP_V2_GOAWAY_FRAME */
    ngx_http_v2_state_window_update,      /* NGX_HTTP_V2_WINDOW_UPDATE_FRAME */
    ngx_http_v2_state_continuation        /* NGX_HTTP_V2_CONTINUATION_FRAME */
};

10 种帧类型,下标就是帧类型号。分派在 ngx_http_v2_state_head()
(src/http/v2/ngx_http_v2.c:883):

// src/http/v2/ngx_http_v2.c:883-919
ngx_http_v2_state_head(ngx_http_v2_connection_t *h2c, u_char *pos, u_char *end)
{
    uint32_t    head;
    ngx_uint_t  type;

    if (end - pos < NGX_HTTP_V2_FRAME_HEADER_SIZE) {
        return ngx_http_v2_state_save(h2c, pos, end, ngx_http_v2_state_head);
    }

    head = ngx_http_v2_parse_uint32(pos);

    h2c->state.length = ngx_http_v2_parse_length(head);
    h2c->state.flags = pos[4];

    h2c->state.sid = ngx_http_v2_parse_sid(&pos[5]);

    pos += NGX_HTTP_V2_FRAME_HEADER_SIZE;

    type = ngx_http_v2_parse_type(head);

    ngx_log_debug4(NGX_LOG_DEBUG_HTTP, h2c->connection->log, 0,
                   "http2 frame type:%ui f:%Xd l:%uz sid:%ui",
                   type, h2c->state.flags, h2c->state.length, h2c->state.sid);

    if (type >= NGX_HTTP_V2_FRAME_STATES) {

        if (type == NGX_HTTP_V2_PRIORITY_UPDATE_FRAME) {
            return ngx_http_v2_state_priority_update(h2c, pos, end);
        }

        ngx_log_error(NGX_LOG_INFO, h2c->connection->log, 0,
                      "client sent frame with unknown type %ui", type);
        return ngx_http_v2_state_skip(h2c, pos, end);
    }

    return ngx_http_v2_frame_states[type](h2c, pos, end);
}

9 字节帧头(NGX_HTTP_V2_FRAME_HEADER_SIZE,src/http/v2/ngx_http_v2.h:27):
3 字节长度 + 1 字节类型 + 1 字节标志 + 4 字节 stream id。

整个状态机是这样转的:

              ┌──────────────┐
              │ state_preface│  验证 "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
              └──────┬───────┘
                     ▼
              ┌──────────────┐
              │  state_head  │  读 9 字节帧头
              └──────┬───────┘
                     ▼
      ┌──────────────┴───────────────┐
      ▼                              ▼
┌───────────┐              ┌──────────────────┐
│ state_data│              │ frame_states[t]  │  按帧类型分派
│ (DATA)    │              │  headers/settings │
└─────┬─────┘              │  window_update/… │
      │                    └────────┬─────────┘
      │                             ▼
      │                    ┌──────────────────┐
      │                    │ state_headers    │  HEADERS 帧
      │                    │ state_header_block│ HPACK 解码
      │                    │ state_process_header│ 逐个头处理
      │                    └────────┬─────────┘
      │                             ▼
      │                    ┌──────────────────┐
      │                    │ ngx_http_v2_      │
      │                    │   run_request()  │  → 进 HTTP 主干
      │                    └──────────────────┘
      ▼
┌────────────────┐
│state_read_data │  把载荷塞进 r->request_body
└────────────────┘

载荷不完整怎么办:ngx_http_v2_state_save()
(src/http/v2/ngx_http_v2.c:2670)把当前状态和已读的那点字节
存进 h2c->state.buffer(16 字节,NGX_HTTP_V2_STATE_BUFFER_SIZE),
返回去等下一次可读事件。下次进来先把这 16 字节拼回去
(src/http/v2/ngx_http_v2.c:397:
end = ngx_cpymem(p, h2c->state.buffer, h2c->state.buffer_used);)。

10.2.4 stream:多路复用的落点

多路复用的核心是 ngx_http_v2_stream_t
(src/http/v2/ngx_http_v2.h:183):

// src/http/v2/ngx_http_v2.h:183-224
struct ngx_http_v2_stream_s {
    ngx_http_request_t              *request;
    ngx_http_v2_connection_t        *connection;
    ngx_http_v2_node_t              *node;

    ngx_uint_t                       queued;

    /*
     * A change to SETTINGS_INITIAL_WINDOW_SIZE could cause the
     * send_window to become negative, hence it's signed.
     */
    ssize_t                          send_window;
    size_t                           recv_window;

    ngx_buf_t                       *preread;

    ngx_uint_t                       frames;

    ngx_http_v2_out_frame_t         *free_frames;
    ngx_chain_t                     *free_frame_headers;
    ngx_chain_t                     *free_bufs;

    ngx_queue_t                     queue;

    ngx_array_t                     *cookies;
    ngx_array_t                     *priorities;

    ngx_http_priority_state_t        priority;

    ngx_pool_t                      *pool;

    unsigned                         initialized:1;
    unsigned                         waiting:1;
    unsigned                         blocked:1;
    unsigned                         exhausted:1;
    unsigned                         in_closed:1;
    unsigned                         out_closed:1;
    unsigned                         rst_sent:1;
    unsigned                         no_flow_control:1;
    unsigned                         skip_data:1;
    unsigned                         priority_update:1;
};

每个 stream 有自己的 ngx_http_request_t(stream->request)、
自己的流控窗口(send_window / recv_window)、
自己的内存池(pool)、自己的输出帧队列(free_frames)。

这是「多路复用」的物理形态:N 个 stream = N 个独立的请求上下文,
共用一个 TCP 连接
。

stream 的创建在 ngx_http_v2_create_stream()(src/http/v2/ngx_http_v2.c:3064)。
它有一段很有意思的代码 —— 造一个「假连接」:

// src/http/v2/ngx_http_v2.c:3116-3141
    ngx_memcpy(log, h2c->connection->log, sizeof(ngx_log_t));

    log->data = ctx;
    log->action = "reading client request headers";

    ngx_memzero(rev, sizeof(ngx_event_t));

    rev->data = fc;
    rev->ready = 1;
    rev->handler = ngx_http_v2_close_stream_handler;
    rev->log = log;

    ngx_memcpy(wev, rev, sizeof(ngx_event_t));

    wev->write = 1;

    ngx_memcpy(fc, h2c->connection, sizeof(ngx_connection_t));

    fc->data = h2c->http_connection;
    fc->read = rev;
    fc->write = wev;
    fc->sent = 0;
    fc->log = log;
    fc->buffered = 0;
    fc->sndlowat = 1;
    fc->tcp_nodelay = NGX_TCP_NODELAY_DISABLED;

为什么要造假连接?因为 HTTP 主干代码(写过滤器、上游模块、
日志模块)全都认 r->connection 是一个真连接。
造一个 ngx_connection_t 的浅拷贝(ngx_memcpy(fc, h2c->connection, ...)),
再把 read / write 换成 stream 自己的事件,
主干代码就完全不用知道自己在 HTTP/2 上跑。

这是 nginx 里最值得学的一招:用数据结构上的伪装,
换取代码路径上的复用
。
一个 stream 在主干代码眼里就是「一条只有它自己的连接」。

10.2.5 伪头与请求行

HTTP/2 没有请求行。方法、路径、协议、authority 被拆成四个伪头
(以 : 开头)::method、:path、:scheme、:authority。

nginx 在 ngx_http_v2_construct_request_line()(src/http/v2/ngx_http_v2.c:3618)
里把伪头拼回一条假的请求行:

// src/http/v2/ngx_http_v2.c:3618-3647
ngx_http_v2_construct_request_line(ngx_http_request_t *r)
{
    u_char  *p;

    static const u_char ending[] = " HTTP/2.0";

    if (r->request_line.len) {
        return NGX_OK;
    }

    if (r->method_name.len == 0
        || r->schema.len == 0
        || r->unparsed_uri.len == 0)
    {
        if (r->method_name.len == 0) {
            ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                          "client sent no :method header");

        } else if (r->schema.len == 0) {
            ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                          "client sent no :scheme header");

        } else {
            ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                          "client sent no :path header");
        }

        ngx_http_finalize_request(r, NGX_HTTP_BAD_REQUEST);
        return NGX_ERROR;
    }

拼出来的结果是 GET /path HTTP/2.0 —— 给日志和 $request_line 变量用的。
所以 HTTP/2 下 access log 里还是能看到一行请求行,
那是 nginx 伪造出来的,不是网络上真的传了这么一行。

拼装本身在 src/http/v2/ngx_http_v2.c:3649:

// src/http/v2/ngx_http_v2.c:3649-3651
    r->request_line.len = r->method_name.len + 1
                          + r->unparsed_uri.len
                          + sizeof(ending) - 1;

这个函数有两处调用点(src/http/v2/ngx_http_v2.c:1800 和 :3969),
但开头那句 if (r->request_line.len) { return NGX_OK; }
保证只会真正拼一次 —— 拼好之后缓存起来复用。

10.2.6 HPACK

HTTP/2 的头压缩是 HPACK(RFC 7541)。nginx 的实现在
src/http/v2/ngx_http_v2_table.c(动态表)和
ngx_http_v2.c(解码状态机)。

HPACK 的解码状态机在 ngx_http_v2_state_field_len()、
ngx_http_v2_state_field_huff()、ngx_http_v2_state_field_raw()
(src/http/v2/ngx_http_v2.c:1473、1560、1615)这几个状态之间转。

关键的一点:HPACK 的动态表是连接级的,
存在 h2c->hpack(src/http/v2/ngx_http_v2.h:148),
所以同一个连接的所有 stream 共享一张表。

坑:HPACK 动态表被投毒是 HTTP/2 的经典攻击面。
攻击者发一批「同一个名字、很长值」的头,把动态表撑爆,
后面所有人的头压缩率归零(CRIME 那一类)。
nginx 的对策是给每个 stream 限一个头总长度:
h2c->state.header_limit
= large_client_header_buffers.size × large_client_header_buffers.num
(src/http/v2/ngx_http_v2.c:1261),
超了就 ENHANCE_YOUR_CALM
(src/http/v2/ngx_http_v2.c:1750)。

10.2.7 输出:帧怎么排队

HTTP/2 的响应不是直接写 socket,而是先排成帧队列。

输出过滤器 ngx_http_v2_filter_module 装在 HTTP 输出链的头部
(src/http/v2/ngx_http_v2_filter_module.c:1780):

// src/http/v2/ngx_http_v2_filter_module.c:1779-1789
static ngx_int_t
ngx_http_v2_filter_init(ngx_conf_t *cf)
{
    ngx_http_next_header_filter = ngx_http_top_header_filter;
    ngx_http_top_header_filter = ngx_http_v2_header_filter;

    ngx_http_next_early_hints_filter = ngx_http_top_early_hints_filter;
    ngx_http_top_early_hints_filter = ngx_http_v2_early_hints_filter;

    return NGX_OK;
}

ngx_http_v2_header_filter()(src/http/v2/ngx_http_v2_filter_module.c:107)
把 HTTP 头转成 HEADERS 帧,
ngx_http_v2_send_chain()(src/http/v2/ngx_http_v2_filter_module.c:1063)
把响应体切成 DATA 帧。

每个 stream 的帧先进自己的队列,
最后由连接统一按优先级刷出去
。
刷出的动作在 ngx_http_v2_send_output_queue()
(src/http/v2/ngx_http_v2.c:507):

// src/http/v2/ngx_http_v2.c:530-544
    for (frame = h2c->last_out; frame; frame = fn) {
        frame->last->next = cl;
        cl = frame->first;

        fn = frame->next;
        frame->next = out;
        out = frame;

        ngx_log_debug4(NGX_LOG_DEBUG_HTTP, c->log, 0,
                       "http2 frame out: %p sid:%ui bl:%d len:%uz",
                       out, out->stream ? out->stream->node->id : 0,
                       out->blocked, out->length);
    }

    cl = c->send_chain(c, cl, 0);

优先级排序在 ngx_http_v2_stream_precedes()
(src/http/v2/ngx_http_v2.h:245)—— 先比 urgency,
再比 incremental,最后按 stream id FIFO。

坑:HTTP/2 的优先级实现(RFC 7540 §5.3.2)后来被 RFC 9218
(Extensible Priorities)废弃了。nginx 支持 priority 伪头
(ngx_http_v2_process_priority(),src/http/v2/ngx_http_v2.c:3826),
但那是另一套(RFC 9218 的 urgency/incremental 模型),
和 HTTP/2 原本的「依赖树」不是一回事。

10.2.8 流控

HTTP/2 有两级流控:

级别 变量 位置
连接级 h2c->send_window / h2c->recv_window src/http/v2/ngx_http_v2.h:137
stream 级 stream->send_window / stream->recv_window src/http/v2/ngx_http_v2.h:194

默认窗口 65535(NGX_HTTP_V2_DEFAULT_WINDOW,
src/http/v2/ngx_http_v2.h:51),
上限 2^31-1(NGX_HTTP_V2_MAX_WINDOW,src/http/v2/ngx_http_v2.h:50)。

收数据的一侧在 ngx_http_v2_state_data()(src/http/v2/ngx_http_v2.c:923):
先用连接级窗口卡一道 —— 超过 h2c->recv_window 直接
FLOW_CTRL_ERROR(src/http/v2/ngx_http_v2.c:977);
再扣窗口,窗口低于上限的 1/4 就发 WINDOW_UPDATE 补回来
(src/http/v2/ngx_http_v2.c:983:
if (h2c->recv_window < NGX_HTTP_V2_MAX_WINDOW / 4))。

stream 级窗口同理,在 ngx_http_v2_state_data() 里另行检查
(src/http/v2/ngx_http_v2.c:1005)——
超了是终结那一条 stream(ngx_http_v2_terminate_stream()),
不是掐断整条连接。

10.3 HTTP/3:QUIC 接住 UDP

HTTP/3 的改动最大:传输层从 TCP 换成了 QUIC。
这一版的 nginx 把 QUIC 直接实现进了事件层 ——
src/event/quic/ 是一个独立于 HTTP 的 QUIC 栈。

10.3.1 三层拆解

┌─────────────────────────────────────────┐
│  UDP socket (recvmsg / sendmsg)         │  src/event/quic/ngx_event_quic_udp.c
├─────────────────────────────────────────┤
│  QUIC 连接 / 流 / 确认 / 拥塞控制        │  src/event/quic/ngx_event_quic*.c
├─────────────────────────────────────────┤
│  HTTP/3 帧 + QPACK                      │  src/http/v3/ngx_http_v3_parse.c
├─────────────────────────────────────────┤
│  HTTP/3 请求语义                        │  src/http/v3/ngx_http_v3_request.c
└─────────────────────────────────────────┘

注意这个分层和 HTTP/2 完全不同:
HTTP/2 的 HPACK 在 src/http/v2/ 里,跟帧解析混在一起;
HTTP/3 的 QUIC 在 src/event/quic/ 里,跟 HTTP 完全解耦。

10.3.2 UDP 收包

UDP 收包用 recvmsg() 而不是 recv() ——
因为 QUIC 需要拿到源地址和目的地址
(连接迁移、connid 路由都要用)。

普通 UDP 用 ngx_event_recvmsg()(src/event/ngx_event_udp.c:25),
但 QUIC 有自己的一套:ngx_quic_recvmsg()
(src/event/quic/ngx_event_quic_udp.c:20)——
它要按地址哈希把包分给对应的 QUIC 连接。

// src/event/quic/ngx_event_quic_udp.c:20-38
ngx_quic_recvmsg(ngx_event_t *ev)
{
    ssize_t             n;
    ngx_str_t           key;
    ngx_buf_t           buf;
    ngx_log_t          *log;
    ngx_err_t           err;
    socklen_t          socklen, local_socklen;
    ngx_event_t        *rev, *wev;
    ngx_socket_t        cfd;
    struct iovec        iov[1];
    struct msghdr       msg;
    ngx_sockaddr_t      sa, lsa;
    struct sockaddr    *sockaddr, *local_sockaddr;
    ngx_listening_t    *ls;
    ngx_event_conf_t   *ecf;
    ngx_connection_t   *c, *lc;
    ngx_quic_socket_t  *qsock;
    static u_char       buffer[NGX_QUIC_MAX_UDP_PAYLOAD_SIZE];

收下来之后:按地址找到 QUIC 连接,
交给 ngx_quic_input_handler()(src/event/quic/ngx_event_quic.c:406):

// src/event/quic/ngx_event_quic.c:444-465
    b = c->udp->buffer;
    if (b == NULL) {
        return;
    }

    rc = ngx_quic_handle_datagram(c, b, NULL);

    if (rc == NGX_ERROR) {
        ngx_quic_close_connection(c, NGX_ERROR);
        return;
    }

    if (rc == NGX_DONE) {
        return;
    }

    /* rc == NGX_OK */

    qc->send_timer_set = 0;
    ngx_add_timer(rev, qc->tp.max_idle_timeout);

    ngx_quic_connstate_dbg(c);

10.3.3 QUIC 流:HTTP/3 的「stream」从哪来

HTTP/3 的每个请求也是一个 QUIC 双向流。
QUIC 流的建立在 ngx_quic_get_stream()(src/event/quic/ngx_event_quic_streams.c:382):

// src/event/quic/ngx_event_quic_streams.c:382-398
ngx_quic_get_stream(ngx_connection_t *c, uint64_t id)
{
    uint64_t                min_id;
    ngx_event_t            *rev;
    ngx_quic_stream_t      *qs;
    ngx_quic_connection_t  *qc;

    qc = ngx_quic_get_connection(c);

    qs = ngx_quic_find_stream(&qc->streams.tree, id);

    if (qs) {
        return qs;
    }

    if (qc->shutdown || qc->closing) {
        return NGX_QUIC_STREAM_GONE;

stream id 的位含义(RFC 9000 §2.1,nginx 里是
NGX_QUIC_STREAM_SERVER_INITIATED = 0x01、
NGX_QUIC_STREAM_UNIDIRECTIONAL = 0x02,
见 src/event/quic/ngx_event_quic.h:43):
最低位是发起方(0 = 客户端,1 = 服务端),
次低位是方向(0 = 双向,1 = 单向)。
所以客户端发起的双向流 id 是 0、4、8……(每次 +4),
客户端发起的单向流是 2、6、10……。

nginx 里到处用 id >> 2 把这个四进制序号还原成「第几个流」
(src/http/v3/ngx_http_v3_request.c:200:
n = c->quic->id >> 2;)。

新建的流先进 qc->streams.uninitialized 队列,
等 TLS 握手完成(ngx_quic_do_init_streams(),
src/event/quic/ngx_event_quic_streams.c:615)才批量初始化。

初始化时通过 rev->handler = ngx_quic_init_stream_handler
(src/event/quic/ngx_event_quic_streams.c:479)挂上回调,
最后调 c->listening->handler(c) —— 这一步把控制权交回 HTTP 层。

// src/event/quic/ngx_event_quic_streams.c:554-575
static void
ngx_quic_init_stream_handler(ngx_event_t *ev)
{
    ngx_connection_t   *c;
    ngx_quic_stream_t  *qs;

    c = ev->data;
    qs = c->quic;

    ngx_log_debug0(NGX_LOG_DEBUG_EVENT, c->log, 0, "quic init stream");

    if ((qs->id & NGX_QUIC_STREAM_UNIDIRECTIONAL) == 0) {
        c->write->active = 1;
        c->write->ready = 1;
    }

    c->read->active = 1;

    ngx_queue_remove(&qs->queue);

    c->listening->handler(c);
}

10.3.4 HTTP/3 侧:init_stream 的分岔

ngx_http_v3_init_stream()(src/http/v3/ngx_http_v3_request.c:59)
是 HTTP/3 的入口,它按流的类型分岔:

// src/http/v3/ngx_http_v3_request.c:59-97
ngx_http_v3_init_stream(ngx_connection_t *c)
{
    ngx_http_connection_t     *hc, *phc;
    ngx_http_v3_srv_conf_t    *h3scf;
    ngx_http_core_loc_conf_t  *clcf;

    hc = c->data;

    hc->ssl = 1;

    clcf = ngx_http_get_module_loc_conf(hc->conf_ctx, ngx_http_core_module);

    if (c->quic == NULL) {
        h3scf = ngx_http_get_module_srv_conf(hc->conf_ctx, ngx_http_v3_module);
        h3scf->quic.idle_timeout = clcf->keepalive_timeout;

        ngx_quic_run(c, &h3scf->quic);
        return;
    }

    phc = ngx_http_quic_get_connection(c);

    if (phc->ssl_servername) {
        hc->ssl_servername = phc->ssl_servername;
#if (NGX_PCRE)
        hc->ssl_servername_regex = phc->ssl_servername_regex;
#endif
        hc->conf_ctx = phc->conf_ctx;

        ngx_set_connection_log(c, clcf->error_log);
    }

    if (c->quic->id & NGX_QUIC_STREAM_UNIDIRECTIONAL) {
        ngx_http_v3_init_uni_stream(c);

    } else  {
        ngx_http_v3_init_request_stream(c);
    }
}

三个岔路:

情况 去哪
c->quic == NULL 第一次进来的那个连接 —— 启动 QUIC(ngx_quic_run())
单向流 ngx_http_v3_init_uni_stream()(src/http/v3/ngx_http_v3_uni.c:26)
双向流 ngx_http_v3_init_request_stream()(src/http/v3/ngx_http_v3_request.c:180)

单向流在 HTTP/3 里是控制流:
QPACK 的编码器/解码器流、SETTINGS 确认流都走这里。
ngx_http_v3_init_uni_stream() 按流类型分派到不同处理器
(src/http/v3/ngx_http_v3_uni.c:105 的 ngx_http_v3_register_uni_stream()),
读的时候走 ngx_http_v3_uni_read_handler()(src/http/v3/ngx_http_v3_uni.c:173),
再调 ngx_http_v3_parse_uni()(src/http/v3/ngx_http_v3_parse.c:1895)解帧。

双向流才是请求。ngx_http_v3_init_request_stream()
(src/http/v3/ngx_http_v3_request.c:180)算了一下 stream id 来限流:

// src/http/v3/ngx_http_v3_request.c:200-207
    n = c->quic->id >> 2;

    if (n >= clcf->keepalive_requests * 2) {
        ngx_http_v3_finalize_connection(c, NGX_HTTP_V3_ERR_EXCESSIVE_LOAD,
                                        "too many requests per connection");
        ngx_http_close_connection(c);
        return;
    }

然后挂上 rev->handler = ngx_http_v3_wait_request_handler,
等请求头。

10.3.5 请求头解析:QPACK

ngx_http_v3_wait_request_handler()(src/http/v3/ngx_http_v3_request.c:275)
读完头之后建请求对象:

// src/http/v3/ngx_http_v3_request.c:374-392
    r = ngx_http_create_request(c);
    if (r == NULL) {
        ngx_http_close_connection(c);
        return;
    }

    r->http_version = NGX_HTTP_VERSION_30;

    r->v3_parse = ngx_pcalloc(r->pool, sizeof(ngx_http_v3_parse_t));
    if (r->v3_parse == NULL) {
        ngx_http_close_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
        return;
    }

    r->v3_parse->header_limit = cscf->large_client_header_buffers.size
                                * cscf->large_client_header_buffers.num;

    c->data = r;
    c->requests = (c->quic->id >> 2) + 1;

注意 r->v3_parse —— HTTP/3 的解析状态挂在请求对象上,
不像 HTTP/2 挂在连接上(h2c->state)。
原因很简单:HTTP/3 的每个 QUIC 流只有这一个请求,
没有共享状态的需要。

然后 ngx_http_v3_process_request()(src/http/v3/ngx_http_v3_request.c:463)
开始解帧:

// src/http/v3/ngx_http_v3_request.c:535-545
        p = b->pos;

        rc = ngx_http_v3_parse_headers(c, st, b);

        if (rc > 0) {
            ngx_quic_reset_stream(c, rc);
            ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
                          "client sent invalid header");
            ngx_http_finalize_request(r, NGX_HTTP_BAD_REQUEST);
            break;
        }

ngx_http_v3_parse_headers()(src/http/v3/ngx_http_v3_parse.c:248)
是 HTTP/3 的帧解析状态机 —— 结构和 HTTP/2 的 state_head 类似,
但它解的是 HTTP/3 帧(类型 + 变长整数长度 + 载荷),
不是 HTTP/2 帧(9 字节固定头)。

QPACK 的解码在 ngx_http_v3_parse_decoder()
(src/http/v3/ngx_http_v3_parse.c:1706)和 ngx_http_v3_parse_field_rep()
(src/http/v3/ngx_http_v3_parse.c:499)等一堆函数里,
动态表在 src/http/v3/ngx_http_v3_table.c。

10.3.6 输出:HTTP/3 帧怎么发出去

HTTP/3 的输出过滤器在 src/http/v3/ngx_http_v3_filter_module.c。
它把 HTTP 头编成 HEADERS 帧、响应体编成 DATA 帧:

// src/http/v3/ngx_http_v3_filter_module.c:818-820
        b->last = (u_char *) ngx_http_v3_encode_varlen_int(chunk,
                                                       NGX_HTTP_V3_FRAME_DATA);
        b->last = (u_char *) ngx_http_v3_encode_varlen_int(b->last, size);

变长整数(varint) 是 HTTP/3 和 HTTP/2 最大的编码差别:
HTTP/2 长度是固定 3 字节,HTTP/3 用 1-8 字节的变长整数,
小数字省空间。

数据进了 QUIC 流之后,最终的出口是
ngx_quic_stream_send_chain()(src/event/quic/ngx_event_quic_streams.c:954)——
它挂在流的 send_chain 上(src/event/quic/ngx_event_quic_streams.c:767)。
再往下由 QUIC 层负责加密、编号、组包,
经 ngx_sendmsg()(src/event/quic/ngx_event_quic_output.c:472)发出去。

对照着看:HTTP/2 的出口是 c->send_chain()
(src/http/v2/ngx_http_v2.c:544),
HTTP/3 的出口是 ngx_quic_stream_send_chain()——
差别就在于后者还要再穿过一层 QUIC 的加密与丢包重传。

10.3.7 HTTP/3 的连接级状态

HTTP/3 的连接级状态在 ngx_http_v3_session_t 里
(src/http/v3/ngx_http_v3.h:123),
在 ngx_http_v3_init_session()(src/http/v3/ngx_http_v3.c:18)里创建:

// src/http/v3/ngx_http_v3.c:17-30
ngx_int_t
ngx_http_v3_init_session(ngx_connection_t *c)
{
    ngx_pool_cleanup_t     *cln;
    ngx_http_connection_t  *hc;
    ngx_http_v3_session_t  *h3c;

    hc = c->data;

    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0, "http3 init session");

    h3c = ngx_pcalloc(c->pool, sizeof(ngx_http_v3_session_t));
    if (h3c == NULL) {
        goto failed;

会话里存着 QPACK 表、keepalive 定时器、总字节计数(防洪用)。

防洪机制在 ngx_http_v3_check_flood()(src/http/v3/ngx_http_v3.c:96):

// src/http/v3/ngx_http_v3.c:95-111
ngx_int_t
ngx_http_v3_check_flood(ngx_connection_t *c)
{
    ngx_http_v3_session_t  *h3c;

    h3c = ngx_http_v3_get_session(c);

    if (h3c->total_bytes / 8 > h3c->payload_bytes + 1048576) {
        ngx_log_error(NGX_LOG_INFO, c->log, 0, "http3 flood detected");

        ngx_http_v3_finalize_connection(c, NGX_HTTP_V3_ERR_NO_ERROR,
                                        "HTTP/3 flood detected");
        return NGX_ERROR;
    }

    return NGX_OK;
}

总字节 / 8 > 载荷字节 + 1MB 就判定为洪水 ——
这是「头部字节远多于内容」的经典放大攻击特征。
HTTP/2 那边有对应的 ngx_http_v2_read_handler() 里的同样判断
(src/http/v2/ngx_http_v2.c:432)。

10.4 状态机挪到了哪里

这是本章最该记住的一张表。

层次 HTTP/1.1 HTTP/2 HTTP/3
字节 → 帧 无(直接就是行) h2c->state.handler
(src/http/v2/ngx_http_v2.c:187)
st->state
(src/http/v3/ngx_http_v3_parse.c:266)
帧 → 请求 r->state
(src/http/ngx_http_parse.c:111)
ngx_http_v2_state_process_header
(src/http/v2/ngx_http_v2.c:1702)
ngx_http_v3_process_header
(src/http/v3/ngx_http_v3_request.c:613)
请求 → 主干 ngx_http_process_request
(src/http/ngx_http_request.c:2126)
同一个 同一个
连接对象 ngx_http_connection_t ngx_http_v2_connection_t
(src/http/v2/ngx_http_v2.h:124)
ngx_http_v3_session_t
一个连接的请求数 1 N(http2_max_concurrent_streams,默认 128) N(http3_max_concurrent_streams,默认也是 128,src/http/v3/ngx_http_v3_module.c:233)
流控 无 连接级 + stream 级 QUIC 层管
头压缩 无 HPACK(src/http/v2/ngx_http_v2_table.c) QPACK(src/http/v3/ngx_http_v3_table.c)
传输 TCP TCP UDP + QUIC(src/event/quic/)

一句话:HTTP/1.1 的状态机在字节上,HTTP/2 和 HTTP/3 的状态机在帧上,
而 HTTP 主干(ngx_http_process_request() 往下)三者共用。

10.5 为什么 worker_connections 的算法不一样

这一节回答一个运维上非常实际的问题。

10.5.1 worker_connections 是什么

worker_connections 指令定义在 src/event/ngx_event.c:123,
它限制的是一个 worker 进程能同时持有的连接数:

// src/event/ngx_event.c:121-128
static ngx_command_t  ngx_event_core_commands[] = {

    { ngx_string("worker_connections"),
      NGX_EVENT_CONF|NGX_CONF_TAKE1,
      ngx_event_connections,
      0,
      0,
      NULL },

它数的是连接,不是请求。

10.5.2 HTTP/1.1 下的算法

HTTP/1.1 里,一条连接同一时刻只处理一个请求
(keepalive 期间也是排队)。
所以:

能服务的并发请求数 ≈ worker_connections × worker_processes

内存约束通常比连接数约束更紧 ——
每个连接要占 client_header_buffer_size(默认 1k)加上
各种 pool。一个 worker 撑 10000 条连接,内存就上去了。

10.5.3 HTTP/2 下的算法

HTTP/2 里,一条连接上可以同时有 N 个活跃请求。
N 的上限是 http2_max_concurrent_streams,默认 128
(src/http/v2/ngx_http_v2_module.c:346):

// src/http/v2/ngx_http_v2_module.c:346-347
    ngx_conf_merge_uint_value(conf->concurrent_streams,
                              prev->concurrent_streams, 128);

nginx 在收到 HEADERS 帧时检查这个上限
(src/http/v2/ngx_http_v2.c:1267):

// src/http/v2/ngx_http_v2.c:1267-1273
    if (h2c->processing >= h2scf->concurrent_streams) {
        ngx_log_error(NGX_LOG_INFO, h2c->connection->log, 0,
                      "concurrent streams exceeded %ui", h2c->processing);

        status = NGX_HTTP_V2_REFUSED_STREAM;
        goto rst_stream;
    }

所以正确的换算是:

能服务的并发请求数 ≈ worker_connections × worker_processes × http2_max_concurrent_streams

但这不代表 worker_connections 可以照抄 HTTP/1.1 的值。
原因在 ngx_http_v2_create_stream() 里 —— 每个 stream 都要独立开销:

每 stream 的开销 从哪来
一个 ngx_http_request_t ngx_http_create_request(),src/http/v2/ngx_http_v2.c:3143
一个内存池 h2scf->pool_size,默认 4096(src/http/v2/ngx_http_v2_module.c:344)
一个 client_header_buffer_size 缓冲 src/http/v2/ngx_http_v2.c:3158
一个假连接 + 假事件 + 假日志 src/http/v2/ngx_http_v2.c:3086 起

所以 HTTP/2 下的实际瓶颈是内存:

单连接内存 ≈ client_header_buffer_size
           + http2_max_concurrent_streams × (pool_size + 请求结构体 + 缓冲)

坑:HTTP/2 下把 worker_connections 从 1024 调到 4096 是危险的。
4096 条连接 × 128 个 stream = 524288 个并发请求上下文。
哪怕每个只占 4k 池,也是 2GB 内存。
实践中 HTTP/2 应该降 worker_connections、保持
http2_max_concurrent_streams 默认或调小,
让总并发请求数落在可控范围。

另一个坑:worker_connections 还受 open file resource limit 约束。
nginx 启动时会检查并告警(src/event/ngx_event.c:529):
「worker_connections exceed open file resource limit」。
HTTP/2 下连接数少(因为复用),这个约束反而更宽松。

10.5.4 HTTP/3 下的算法

HTTP/3 的换算又不一样,因为一个 UDP socket 服务多个 QUIC 连接:

UDP socket 数 ≈ worker_connections(但每个 socket 承载 N 个 QUIC 连接)
QUIC 连接数 ≈ UDP socket 数 × 每 socket 的连接数(由 connid 哈希决定)

QUIC 连接不受 worker_connections 的直接限制 ——
它们不是 ngx_connection_t 意义上的连接。
但每个 QUIC 连接仍然要占内存(收发窗口、ACK 表、流的状态)。

10.5.5 三者的对照

HTTP/1.1 HTTP/2 HTTP/3
worker_connections 数的东西 TCP 连接 TCP 连接 UDP socket
一条「连接」能带几个请求 1 最多 128 取决于 QUIC
单个请求的内存开销 一份缓冲 一份池 + 一份结构体 同 HTTP/2
换算公式 C × P C × P × S C × P × 每 socket 连接数
主要瓶颈 文件描述符 内存 内存 + CPU(加密)

10.6 小结

  • 三者的结构差别:HTTP/1.1 是「连接 + 顺序状态机」,
    HTTP/2 是「连接 + 帧 + stream」,HTTP/3 是「UDP + QUIC + 流」。
  • HTTP/2 的多路复用落在 ngx_http_v2_stream_t
    (src/http/v2/ngx_http_v2.h:183)上 ——
    每个 stream 一个独立请求、独立内存池、独立流控窗口,
    共用一个 TCP 连接。
  • HTTP/2 的状态机在 h2c->state.handler(函数指针),
    帧类型到处理器是一张表(src/http/v2/ngx_http_v2.c:187)。
  • HTTP/2 用「假连接」复用 HTTP 主干:
    ngx_http_v2_create_stream() 造一个 ngx_connection_t 浅拷贝,
    主干代码完全不用改。
  • HTTP/2 没有请求行,nginx 用
    ngx_http_v2_construct_request_line() 伪造一条给日志用。
  • HTTP/3 的 QUIC 在 src/event/quic/,跟 HTTP 完全解耦;
    UDP 收包用 recvmsg(),单 QUIC 连接由 connid 哈希索引。
  • HTTP/3 的解析状态挂在请求对象上(r->v3_parse,
    src/http/ngx_http_request.h:463),
    不像 HTTP/2 挂在连接上(h2c->state)。
  • 状态机的落点:
    HTTP/1.1 在字节上,HTTP/2 和 HTTP/3 在帧上,
    但 ngx_http_process_request() 往下三者共用。
  • worker_connections 的算法:
    HTTP/1.1 是 C × P,HTTP/2 是 C × P × S
    (S = http2_max_concurrent_streams,默认 128),
    HTTP/3 数的是 UDP socket。
    HTTP/2 下真正的瓶颈从文件描述符变成了内存。

下一篇进 L6「反向代理与负载均衡」:
upstream 怎么选后端、连接怎么复用、四种调度算法各按什么挑。

参考

  • 源码树:/work/ai/cwork/nginx(nginx 1.31.11,HEAD e76b6746c)
  • RFC 7540:Hypertext Transfer Protocol Version 2
  • RFC 7541:HPACK: Header Compression for HTTP/2
  • RFC 9114:HTTP/3
  • RFC 9204:QPACK: Field Compression for HTTP/3
  • RFC 9000:QUIC: A UDP-Based Multiplexed and Secure Transport
  • nginx 官方文档:http2_module.html、http_v3_module.html

文章作者: growdu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 growdu !
  目录