09 请求解析


 TL;DR
一个 HTTP/1.1 请求在 nginx 里怎么从裸字节变成 ngx_http_request_t:请求行的字节状态机、请求头的哈希分派、缓冲区满了怎么办、chunked 请求体怎么解、keepalive 又是怎么判断的。
难度 中等

前面几章讲的是「连接怎么来、事件怎么转、内存从哪拿」。
这一章第一次进入 HTTP 语义本身:一堆字节怎么变成一个请求对象。

读完之后你应该能回答:

  1. 一个请求从 socket 里的字节到 ngx_http_request_t 填满,一共经过哪几步?
  2. 请求行的解析是一遍扫完的吗?跨 TCP 包的请求行怎么续上?
  3. 请求头缓冲区满了会发生什么?large_client_header_buffers 是怎么参与决策的?
  4. Transfer-Encoding: chunked 的请求体是怎么解的?解到什么程度为止?
  5. keepalive 是由谁决定的?Connection: close 与 HTTP/1.0 各起什么作用?

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

9.1 从字节到请求对象:五步

先把全局的骨架摆出来。nginx 的 HTTP/1.1 请求处理是一条单向的状态机,
每一步由一个 rev->handler 串起来:

 accept
   │
   ▼
ngx_http_wait_request_handler()          src/http/ngx_http_request.c:377
   │  读第一段字节,嗅探是不是 HTTP/2 前言
   ▼
ngx_http_process_request_line()          src/http/ngx_http_request.c:1115
   │  ── ngx_http_parse_request_line()    src/http/ngx_http_parse.c:108
   │  ── ngx_http_process_request_uri()   src/http/ngx_http_request.c:1280
   ▼
ngx_http_process_request_headers()       src/http/ngx_http_request.c:1401
   │  ── ngx_http_parse_header_line()     src/http/ngx_http_parse.c:871
   │  ── ngx_http_process_request_header()src/http/ngx_http_request.c:2024
   ▼
ngx_http_process_request()               src/http/ngx_http_request.c:2126
   │  (进入 location 查找、上游、内容处理)
   ▼
ngx_http_read_client_request_body()      src/http/ngx_http_request_body.c:32
   │  ── ngx_http_do_read_client_request_body()
   │                                        src/http/ngx_http_request_body.c:295
   │  ── ngx_http_parse_chunked()          src/http/ngx_http_parse.c:2204
   ▼
ngx_http_set_keepalive()                 src/http/ngx_http_request.c:3352

五步的分工是这样分的:

步骤 谁在管 输入 输出
1. 嗅探 ngx_http_wait_request_handler 首个 TCP 段 判断是不是 HTTP/2
2. 请求行 ngx_http_process_request_line METHOD URI HTTP/x.y\r\n r->method、r->uri、r->http_version
3. 请求头 ngx_http_process_request_headers 一串 Name: Value\r\n r->headers_in.headers 链表 + 若干具名字段
4. 请求头后处理 ngx_http_process_request_header 已填好的 headers_in content_length_n、chunked、connection_type
5. 请求体 ngx_http_read_client_request_body Content-Length 或 chunked r->request_body

第 4 步常被忽略 —— 它不是「解析」,是语义裁决:
把 Content-Length: 100 从字符串变成数字、把
Transfer-Encoding: chunked 变成一个标志位、决定这个连接能不能复用。

一个关键设计:第 2、3 步的解析器(ngx_http_parse_*)都是无状态的,
状态存在请求对象 r 里(r->state、r->header_name_start 这些)。
这让它们可以被包在 for(;;) 循环里反复调用 —— 一次读不全就退出,
下次有数据了接着扫。这是 nginx 处理「TCP 分包」的全部机制,
没有第二套。

9.2 请求行:一个字节一个状态的扫描

ngx_http_process_request_line() 的核心是一个死循环:

// src/http/ngx_http_request.c:1149-1157
        rc = ngx_http_parse_request_line(r, r->header_in);

        if (rc == NGX_OK) {

            /* the request line has been parsed successfully */

            r->request_line.len = r->request_end - r->request_start;
            r->request_line.data = r->request_start;
            r->request_length = r->header_in->pos - r->request_start;

注意 for( ;; ) 的结构(src/http/ngx_http_request.c:1139 起):
rc == NGX_AGAIN 时先 ngx_http_read_request_header(r) 补数据,
再调解析器;解析器返回 NGX_AGAIN 表示「还没扫完」,
r->state 记住了断点,循环再来一遍。

9.2.1 状态机的形状

ngx_http_parse_request_line() 是一个逐字节的状态机
(src/http/ngx_http_parse.c:107 起):

// src/http/ngx_http_parse.c:107-139
ngx_int_t
ngx_http_parse_request_line(ngx_http_request_t *r, ngx_buf_t *b)
{
    u_char  c, ch, *p, *m;
    enum {
        sw_start = 0,
        sw_method,
        sw_spaces_before_uri,
        sw_schema,
        sw_schema_slash,
        sw_schema_slash_slash,
        sw_spaces_before_host,
        sw_host_start,
        sw_host,
        sw_host_end,
        sw_host_ip_literal,
        sw_port_start,
        sw_port,
        sw_after_slash_in_uri,
        sw_check_uri,
        sw_uri,
        sw_http_09,
        sw_http_H,
        sw_http_HT,
        sw_http_HTT,
        sw_http_HTTP,
        sw_first_major_digit,
        sw_major_digit,
        sw_first_minor_digit,
        sw_minor_digit,
        sw_spaces_after_digit,
        sw_almost_done
    } state;

27 个状态,按字节推进:

sw_start
   │ 看到 'G'
   ▼
sw_method ──看到 ' '──► sw_spaces_before_uri
                              │ 看到 '/'
                              ▼
                         sw_after_slash_in_uri
                              │ 逐字符
                              ▼
                            sw_uri ──看到 ' '──► sw_http_09
                                                  │
                      sw_http_H → HT → HTT → HTTP ──┘
                              │
                              ▼
                  sw_first_major_digit → sw_major_digit
                              │
                              ▼
                  sw_first_minor_digit → sw_minor_digit
                              │
                              ▼
                     sw_spaces_after_digit ──CRLF──► sw_almost_done

三个要点:

  1. 方法名是靠长度 + 首字母匹配的,不是查表。
    sw_method 状态里按 p - m(长度)分派,
    长度 3 查 GET / PUT,长度 4 查 POST / COPY / MOVE ……
    匹配不上就落到 NGX_HTTP_UNKNOWN。
  2. 版本号是逐字母确认的:sw_http_H、sw_http_HT、
    sw_http_HTT、sw_http_HTTP 四个状态一个字母一个字母地等。
    这样 HTTP/1.1 和 HTTP/11.1 混进来会立刻被拒。
  3. sw_schema / sw_host 那一串只在「绝对 URI」时才走。
    代理请求发来的 GET http://example.com/x HTTP/1.1 会先解析 schema 和 host,
    普通 origin-form 的 GET /x HTTP/1.1 直接跳过。

坑:ngx_http_parse_request_line() 返回的错误码不是统一的。
NGX_HTTP_PARSE_INVALID_METHOD / NGX_HTTP_PARSE_INVALID_VERSION /
NGX_HTTP_PARSE_INVALID_REQUEST / NGX_HTTP_PARSE_INVALID_09_METHOD
四种,对应的 HTTP 状态码不一样(版本不对返 505,方法不对返 400)。
分派逻辑在 src/http/ngx_http_request.c:1237-1247。

9.2.2 URI 还要再解一遍

请求行扫完,ngx_http_process_request_uri()(src/http/ngx_http_request.c:1280)
接手。它做两件事:

URI 形态 判断依据 处理
简单 URI r->complex_uri == 0 且 quoted_uri == 0 直接指向原缓冲区,零拷贝
复杂 URI 含 .、//、%、# 调 ngx_http_parse_complex_uri() 解码

判断是在 ngx_http_parse_uri() 里做的(src/http/ngx_http_parse.c:1134),
它只做扫描和标记,不改数据:

// src/http/ngx_http_parse.c:1134-1146
ngx_http_parse_uri(ngx_http_request_t *r)
{
    u_char  *p, ch;
    enum {
        sw_start = 0,
        sw_after_slash_in_uri,
        sw_check_uri,
        sw_uri
    } state;

    state = sw_start;

    for (p = r->uri_start; p != r->uri_end; p++) {

看到 .、%、/、# 就置 r->complex_uri = 1 或 r->quoted_uri = 1。

真正解码的是 ngx_http_parse_complex_uri()(src/http/ngx_http_parse.c:1285),
它处理 %XX 解码、. / .. 消解、// 合并:

// src/http/ngx_http_parse.c:1284-1306
ngx_int_t
ngx_http_parse_complex_uri(ngx_http_request_t *r, ngx_uint_t merge_slashes)
{
    u_char  c, ch, decoded, *p, *u;
    enum {
        sw_usual = 0,
        sw_slash,
        sw_dot,
        sw_dot_dot,
        sw_quoted,
        sw_quoted_second
    } state, quoted_state;

#if (NGX_SUPPRESS_WARN)
    decoded = '\0';
    quoted_state = sw_usual;
#endif

    state = sw_usual;
    p = r->uri_start;
    u = r->uri.data;
    r->uri_ext = NULL;
    r->args_start = NULL;

坑:merge_slashes 由 merge_slashes 指令控制(默认开)。
关掉之后 //a//b 和 /a/b 会变成不同的 location。
这是「为什么同一个 URL 有时 404 有时 200」这类问题的常见答案之一。

9.3 请求头:一个循环 + 一张哈希表

请求行的解析结果出来后,ngx_http_process_request_line() 把
rev->handler 换成 ngx_http_process_request_headers(src/http/ngx_http_request.c:1229),
然后调用它。HTTP/1.0 请求是个例外 —— 它没有请求头,直接进
ngx_http_process_request()(src/http/ngx_http_request.c:1214)。

9.3.1 解析循环

ngx_http_process_request_headers()(src/http/ngx_http_request.c:1401)
的结构和请求行那边一模一样:for(;;) + NGX_AGAIN 续扫。

每轮做三件事:

// src/http/ngx_http_request.c:1483-1488
        rc = ngx_http_parse_header_line(r, r->header_in,
                                        cscf->underscores_in_headers);

        if (rc == NGX_OK) {

            r->request_length += r->header_in->pos - r->header_name_start;

ngx_http_parse_header_line()(src/http/ngx_http_parse.c:871)本身是
一次只解一个头的状态机:

// src/http/ngx_http_parse.c:870-885
ngx_int_t
ngx_http_parse_header_line(ngx_http_request_t *r, ngx_buf_t *b,
    ngx_uint_t allow_underscores)
{
    u_char      c, ch, *p;
    ngx_uint_t  hash, i;
    enum {
        sw_start = 0,
        sw_name,
        sw_space_before_value,
        sw_value,
        sw_space_after_value,
        sw_ignore_line,
        sw_almost_done,
        sw_header_almost_done
    } state;

八个状态。注意 sw_ignore_line —— 这是给「一行太长放不下」准备的:
头字段名之后如果还跟着非冒号的内容,就整行忽略掉。

返回码有四种:

返回码 含义 后果
NGX_OK 解出一个头 落进链表,继续解下一个
NGX_HTTP_PARSE_HEADER_DONE 解到空行,头部结束 进 ngx_http_process_request_header()
NGX_AGAIN 数据不够 读更多再来
NGX_HTTP_PARSE_INVALID_HEADER 非法 400

9.3.2 头字段进链表,然后查哈希表

解出一个头之后,先推进 r->headers_in.headers 链表
(src/http/ngx_http_request.c:1512):

// src/http/ngx_http_request.c:1512-1526
            h = ngx_list_push(&r->headers_in.headers);
            if (h == NULL) {
                ngx_http_close_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);
                break;
            }

            h->hash = r->header_hash;

            h->key.len = r->header_name_end - r->header_name_start;
            h->key.data = r->header_name_start;
            h->key.data[h->key.len] = '\0';

            h->value.len = r->header_end - r->header_start;
            h->value.data = r->header_start;
            h->value.data[h->value.len] = '\0';

然后查一张预编译的哈希表 cmcf->headers_in_hash,
命中了就调表里登记的处理函数:

// src/http/ngx_http_request.c:1541-1546
            hh = ngx_hash_find(&cmcf->headers_in_hash, h->hash,
                               h->lowcase_key, h->key.len);

            if (hh && hh->handler(r, h, hh->offset) != NGX_OK) {
                break;
            }

这张表是 ngx_http_header_t 数组(src/http/ngx_http_request.h:172):

// src/http/ngx_http_request.h:173-177
typedef struct {
    ngx_str_t                         name;
    ngx_uint_t                        offset;
    ngx_http_header_handler_pt        handler;
} ngx_http_header_t;

数组本体在 src/http/ngx_http_request.c:79 起,
里面登记的是「语义特殊、需要额外处理」的头:

头 处理函数 位置 干什么
Host ngx_http_process_host src/http/ngx_http_request.c:83 选虚拟服务器
Connection ngx_http_process_connection src/http/ngx_http_request.c:1919 判 keepalive
Proxy-Connection ngx_http_process_proxy_connection src/http/ngx_http_request.c:89 HTTP/2 下直接拒
If-Modified-Since 等 ngx_http_process_unique_header_line src/http/ngx_http_request.c:93 查重复
User-Agent ngx_http_process_user_agent src/http/ngx_http_request.c:108 认 msie/opera

Connection 头的处理决定了连接类型(src/http/ngx_http_request.c:1919):

// src/http/ngx_http_request.c:1919-1934
ngx_http_process_connection(ngx_http_request_t *r, ngx_table_elt_t *h,
    ngx_uint_t offset)
{
    if (ngx_http_process_header_line(r, h, offset) != NGX_OK) {
        return NGX_ERROR;
    }

    if (ngx_strcasestrn(h->value.data, "close", 5 - 1)) {
        r->headers_in.connection_type = NGX_HTTP_CONNECTION_CLOSE;

    } else if (ngx_strcasestrn(h->value.data, "keep-alive", 10 - 1)) {
        r->headers_in.connection_type = NGX_HTTP_CONNECTION_KEEP_ALIVE;
    }

    return NGX_OK;
}

坑:Connection 头里的每一个 token 都要被认,
而 ngx_strcasestrn 只找第一个匹配。
Connection: close, foo 里 close 在前面,没问题;
但 Connection: foo, close 也会命中(子串搜索),
语义上却不该这么判。nginx 这里没做严格的 token 切分。

9.3.3 请求头解析完之后

空行一到,ngx_http_parse_header_line() 返回
NGX_HTTP_PARSE_HEADER_DONE,循环进入最后一段
(src/http/ngx_http_request.c:1555):

// src/http/ngx_http_request.c:1555-1575
        if (rc == NGX_HTTP_PARSE_HEADER_DONE) {

            /* a whole header has been parsed successfully */

            ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                           "http header done");

            r->request_length += r->header_in->pos - r->header_name_start;

            r->http_state = NGX_HTTP_PROCESS_REQUEST_STATE;

            rc = ngx_http_process_request_header(r);

            if (rc != NGX_OK) {
                break;
            }

            ngx_http_process_request(r);

            break;
        }

ngx_http_process_request_header()(src/http/ngx_http_request.c:2024)
是第 4 步,做语义裁决:

// src/http/ngx_http_request.c:2024-2040
ngx_http_process_request_header(ngx_http_request_t *r)
{
    ngx_http_core_srv_conf_t  *cscf;

    if (r->headers_in.server.len == 0
        && ngx_http_set_virtual_server(r, &r->headers_in.server)
           == NGX_ERROR)
    {
        return NGX_ERROR;
    }

    if (r->headers_in.host == NULL && r->http_version > NGX_HTTP_VERSION_10) {
        ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                   "client sent HTTP/1.1 request without \"Host\" header");
        ngx_http_finalize_request(r, NGX_HTTP_BAD_REQUEST);
        return NGX_ERROR;
    }

它做四件事:

  1. 补默认虚拟服务器(HTTP/1.0 常常没有 Host)。
  2. HTTP/1.1 必须有 Host,缺了就 400。
  3. Content-Length 转数字(src/http/ngx_http_request.c:2043)。
  4. 判定 chunked(下面详述)。

9.4 大头:请求头缓冲区满了怎么办

这一节是本章的重点。nginx 处理「头太大」有一套三级机制。

9.4.1 三个尺寸

配置项 默认值 作用 默认值出处
client_header_buffer_size 1k 每连接第一块缓冲区 src/http/ngx_http_core_module.c:3630
large_client_header_buffers 4 × 8k 头太大时的备用缓冲区 src/http/ngx_http_core_module.c:3632
client_header_timeout 60s 多久没读完头就断 src/http/ngx_http_core_module.c:3628

(这三个默认值都写在 ngx_http_core_merge_loc_conf() 里,
用 ngx_conf_merge_*_value() 合并;指令本身的注册在
src/http/ngx_http_core_module.c:234、:241、:248。)

large_client_header_buffers 的语义是「最多几个、每个多大」:
默认 4 块、每块 8k,所以单个请求头最多能占
4 × 8k = 32k(还要减去已被占用的块)。

9.4.2 触发点

请求行和请求头各有一个触发点,都是同一句判断:

// src/http/ngx_http_request.c:1252-1256
        /* NGX_AGAIN: a request line parsing is still incomplete */

        if (r->header_in->pos == r->header_in->end) {

            rv = ngx_http_alloc_large_header_buffer(r, 1);

请求头那边是 rv = ngx_http_alloc_large_header_buffer(r, 0)
(src/http/ngx_http_request.c:1437),
唯一的差别是第二个参数 request_line(1 = 请求行,0 = 请求头)。

判断条件是 pos == end —— 缓冲区读满了,而解析还没完成。

9.4.3 扩容的两条路

ngx_http_alloc_large_header_buffer()(src/http/ngx_http_request.c:1657)
的决策分两层:

第一层:能不能再要一块更大的。

// src/http/ngx_http_request.c:1683-1688
    if (r->state != 0
        && (size_t) (r->header_in->pos - old)
                                     >= cscf->large_client_header_buffers.size)
    {
        return NGX_DECLINED;
    }

r->state != 0 表示「当前这行还没解完」。如果这一行本身就超过了
large_client_header_buffers.size,那再给多大的一块都没用 —— 直接拒绝。

第二层:还有没有空闲的备用块。

// src/http/ngx_http_request.c:1690-1708
    hc = r->http_connection;

    if (hc->free) {
        cl = hc->free;
        hc->free = cl->next;

        b = cl->buf;

        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                       "http large header free: %p %uz",
                       b->pos, b->end - b->last);

    } else if (hc->nbusy < cscf->large_client_header_buffers.num) {

        b = ngx_create_temp_buf(r->connection->pool,
                                cscf->large_client_header_buffers.size);
        if (b == NULL) {
            return NGX_ERROR;
        }
  • hc->free 非空 → 拿一块用过的(复用)。
  • hc->nbusy < large_client_header_buffers.num → 新分配一块。
  • 两条都不成立 → return NGX_DECLINED(src/http/ngx_http_request.c:1722)。

坑:hc->free 里的块是上一次请求留下来的。
这就是为什么 nginx 的空闲连接内存占用跟
「历史上出现过的最大请求头」有关 —— 一块 8k 的备用块被大请求用过,
之后会一直挂在 hc->free 上,直到连接关闭。

9.4.4 搬移:为什么指针也要改

拿到新块之后,光把数据拷过去还不够 ——
解析器已经把位置记在 r->request_start、r->uri_start 这些指针里了。
所以 nginx 搬完数据还要重定位所有指针:

// src/http/ngx_http_request.c:1744-1755
    if (r->header_in->pos - old > b->end - b->start) {
        ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0,
                      "too large header to copy");
        return NGX_ERROR;
    }

    new = b->start;

    ngx_memcpy(new, old, r->header_in->pos - old);

    b->pos = new + (r->header_in->pos - old);
    b->last = new + (r->header_in->pos - old);

然后是一长串指针修正(src/http/ngx_http_request.c:1757 起):

// src/http/ngx_http_request.c:1757-1766
    if (request_line) {
        r->request_start = new;

        if (r->request_end) {
            r->request_end = new + (r->request_end - old);
        }

        if (r->method_end) {
            r->method_end = new + (r->method_end - old);
        }

请求头路径下改的指针更多:header_name_start、header_name_end、
header_start、header_end、lowcase_header ……
这是 ngx_http_alloc_large_header_buffer() 里最长的一段代码。

坑:r->state == 0 是个特例 —— 意思是「上一行刚解完」。
这时候不需要搬移,直接把 r->header_in 换成新块就行
(src/http/ngx_http_request.c:1730-1739)。
只有「行还没解完」才需要重定位。

另一个坑:请求行的情况下,如果 r->state == 0,
函数会清空缓冲区重来(src/http/ngx_http_request.c:1669-1676),
因为请求行是一次性产物 —— 长度超了就是超了,重扫一遍也是白搭。

9.4.5 拒绝之后

NGX_DECLINED 往上抛,两条路径分别处理:

场景 状态码 位置
请求行太长 414 URI Too Long src/http/ngx_http_request.c:1266
请求头太大 400 + lingering_close src/http/ngx_http_request.c:1444

请求头那条还会把头的前 300 字节打进错误日志
(src/http/ngx_http_request.c:1463),
方便你事后看出是谁发来的。

9.5 请求体:chunked 怎么解

请求体不是解析器扫出来的,是读出来的。
入口是 ngx_http_read_client_request_body()(src/http/ngx_http_request_body.c:32)。

9.5.1 先看预读的部分

// src/http/ngx_http_request_body.c:32-49
ngx_http_read_client_request_body(ngx_http_request_t *r,
    ngx_http_client_body_handler_pt post_handler)
{
    size_t                     preread;
    ssize_t                    size;
    ngx_int_t                  rc;
    ngx_buf_t                 *b;
    ngx_chain_t                out;
    ngx_http_request_body_t   *rb;
    ngx_http_core_loc_conf_t  *clcf;

    r->main->count++;

    if (r != r->main || r->request_body || r->discard_body) {
        r->request_body_no_buffering = 0;
        post_handler(r);
        return NGX_OK;
    }

关键一点:读请求头的时候可能已经顺手把请求体的一部分读进来了
(TCP 段里请求头和请求体是连着的)。
所以第一件事是把「预读」的那部分先处理掉
(src/http/ngx_http_request_body.c:102 起,
preread = r->header_in->last - r->header_in->pos)。

9.5.2 两种长度来源

头部 走哪条路
Content-Length: N 按 N 读,读够 N 为止
Transfer-Encoding: chunked 边读边解 chunk 边界

两者同时出现就是请求走私,nginx 直接拒
(src/http/ngx_http_request.c:2068):

// src/http/ngx_http_request.c:2055-2086
    if (r->headers_in.transfer_encoding) {
        if (r->http_version < NGX_HTTP_VERSION_11) {
            ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                          "client sent HTTP/1.0 request with "
                          "\"Transfer-Encoding\" header");
            ngx_http_finalize_request(r, NGX_HTTP_BAD_REQUEST);
            return NGX_ERROR;
        }

        if (r->headers_in.transfer_encoding->value.len == 7
            && ngx_strncasecmp(r->headers_in.transfer_encoding->value.data,
                               (u_char *) "chunked", 7) == 0)
        {
            if (r->headers_in.content_length) {
                ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                              "client sent \"Content-Length\" and "
                              "\"Transfer-Encoding\" headers "
                              "at the same time");
                ngx_http_finalize_request(r, NGX_HTTP_BAD_REQUEST);
                return NGX_ERROR;
            }

            r->headers_in.chunked = 1;

        } else {
            ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
                          "client sent unknown \"Transfer-Encoding\": \"%V\"",
                          &r->headers_in.transfer_encoding->value);
            ngx_http_finalize_request(r, NGX_HTTP_NOT_IMPLEMENTED);
            return NGX_ERROR;
        }
    }

注意:只有 chunked 这一个值被接受,别的 Transfer-Encoding
(比如 gzip)直接 501 Not Implemented。

9.5.3 chunked 的状态机

ngx_http_parse_chunked()(src/http/ngx_http_parse.c:2204)是又一台
逐字节状态机:

// src/http/ngx_http_parse.c:2203-2228
ngx_int_t
ngx_http_parse_chunked(ngx_http_request_t *r, ngx_buf_t *b,
    ngx_http_chunked_t *ctx, ngx_uint_t keep_trailers)
{
    u_char     *pos, ch, c;
    ngx_int_t   rc;
    enum {
        sw_chunk_start = 0,
        sw_chunk_size,
        sw_chunk_extension,
        sw_chunk_extension_almost_done,
        sw_chunk_data,
        sw_after_data,
        sw_after_data_almost_done,
        sw_last_chunk_extension,
        sw_last_chunk_extension_almost_done,
        sw_trailer,
        sw_trailer_almost_done,
        sw_trailer_header,
        sw_trailer_header_almost_done
    } state;

    state = ctx->state;

    if (state == sw_chunk_data && ctx->size == 0) {
        state = sw_after_data;

和请求行/请求头一样,状态存在 ctx->state 里,
所以可以跨 TCP 包续解。

chunk 尺寸是十六进制的(src/http/ngx_http_parse.c:2262 起),
带溢出保护:

// src/http/ngx_http_parse.c:2259-2262
        case sw_chunk_size:
            if (ctx->size > NGX_MAX_OFF_T_VALUE / 16) {
                goto invalid;
            }

尺寸为 0 表示这是最后一个 chunk(进入 sw_last_chunk_extension),
后面可以跟 trailer 头,直到一个空行。

9.5.4 解出来的数据往哪去

ngx_http_parse_chunked() 返回 NGX_OK 表示「一个 chunk 的头解完了,
接下来 ctx->size 字节是数据」。真正剥数据的是过滤器
(src/http/ngx_http_request_body.c:876):

// src/http/ngx_http_request_body.c:876-894
            rc = ngx_http_parse_chunked(r, b, rb->chunked, 0);

            if (rc == NGX_OK) {

                /* a chunk has been parsed successfully */

                size = b->last - b->pos;

                if ((off_t) size > rb->chunked->size) {
                    b->pos += (size_t) rb->chunked->size;
                    rb->chunked->size = 0;

                } else {
                    rb->chunked->size -= size;
                    b->pos = b->last;
                }

                continue;
            }

也就是说:chunk 的边界被就地剥掉,
b->pos 往前推,缓冲里剩下的就是纯净的请求体数据。
下游(proxy、fastcgi 的入参)永远看不到 chunk 头。

坑:chunked 的请求体没有 Content-Length,
所以 proxy_pass 到后端时 nginx 要自己重新加 chunked 帧
(r->headers_in.chunked 会一路带到上游模块)。
如果中间有 CDN 或者 WAF 改写,chunked 很容易被改坏 ——
这是「chunked 请求偶发 400」这类工单的高频原因。

9.6 keepalive 是怎么判断的

keepalive 有两个层面的判断。

9.6.1 协议层:这次请求要不要复用连接

先看 Connection 头怎么改标志位。处理器是
ngx_http_process_connection()(src/http/ngx_http_request.c:1919):

// src/http/ngx_http_request.c:1919-1934
ngx_http_process_connection(ngx_http_request_t *r, ngx_table_elt_t *h,
    ngx_uint_t offset)
{
    if (ngx_http_process_header_line(r, h, offset) != NGX_OK) {
        return NGX_ERROR;
    }

    if (ngx_strcasestrn(h->value.data, "close", 5 - 1)) {
        r->headers_in.connection_type = NGX_HTTP_CONNECTION_CLOSE;

    } else if (ngx_strcasestrn(h->value.data, "keep-alive", 10 - 1)) {
        r->headers_in.connection_type = NGX_HTTP_CONNECTION_KEEP_ALIVE;
    }

    return NGX_OK;
}

关键在 connection_type 的初值是 0 ——
表示「客户端没发 Connection 头」。
这时该怎么决定,由版本号说了算。

真正的裁决点在 ngx_http_handler() 里
(src/http/ngx_http_core_module.c:857):

// src/http/ngx_http_core_module.c:856-870
        if (r->method != NGX_HTTP_CONNECT) {
            switch (r->headers_in.connection_type) {
            case 0:
                r->keepalive = (r->http_version > NGX_HTTP_VERSION_10);
                break;

            case NGX_HTTP_CONNECTION_CLOSE:
                r->keepalive = 0;
                break;

            case NGX_HTTP_CONNECTION_KEEP_ALIVE:
                r->keepalive = 1;
                break;
            }
        }

三个分支合起来就是 HTTP 的完整语义:

connection_type 来源 r->keepalive
0 客户端没发 Connection 头 按版本号:HTTP/1.1 及以上复用,HTTP/1.0 不复用
NGX_HTTP_CONNECTION_CLOSE 发了 Connection: close 0
NGX_HTTP_CONNECTION_KEEP_ALIVE 发了 Connection: keep-alive 1

r->http_version 是请求行解析器算出来的
(src/http/ngx_http_parse.c:859:
r->http_version = r->http_major * 1000 + r->http_minor;),
所以「HTTP/1.1 默认复用」这句话在 nginx 里就是上面那个
r->http_version > NGX_HTTP_VERSION_10 的比较。

坑:HTTP/1.0 客户端想复用连接,必须显式发
Connection: keep-alive
;反过来 HTTP/1.1 客户端不发 Connection 头
就是默认复用。很多「HTTP/1.0 下 keepalive 不生效」的排查,
根子都在这个 case 0 分支上。

另外,ngx_http_process_request_header() 里还有一段
(src/http/ngx_http_request.c:2088):

// src/http/ngx_http_request.c:2088-2094
    if (r->headers_in.connection_type == NGX_HTTP_CONNECTION_KEEP_ALIVE) {
        if (r->headers_in.keep_alive) {
            r->headers_in.keep_alive_n =
                            ngx_atotm(r->headers_in.keep_alive->value.data,
                                      r->headers_in.keep_alive->value.len);
        }
    }

它想读的是 Keep-Alive 头里的超时秒数。
但这里有个真实的历史遗留:nginx 用的 ngx_atotm()
(src/core/ngx_string.c:1107)要求整个字符串都是数字才返回数值,
一旦遇到非数字字符就返回 NGX_ERROR(-1)。
而标准的 Keep-Alive: timeout=5, max=100 一上来就是个字母 t,
ngx_atotm() 必然失败 —— 于是 keep_alive_n 保持初值 -1。

更要命的是,keep_alive_n 这个字段全树只有这三处出现
(声明 src/http/ngx_http_request.h:247、
初始化 src/http/ngx_http_request.c:657、
赋值 src/http/ngx_http_request.c:2090),
没有任何地方读它。

坑:也就是说,nginx 不支持 Keep-Alive: timeout=N 这个协商。
超时时间只有 keepalive_timeout 指令说了算
(见 9.6.2),客户端在 Keep-Alive 头里写的超时值被静默忽略。
这是 HTTP/1.1 规范里的一个「 SHOULD 但大家都不做」的条款,
nginx 选择了直接不实现。

9.6.2 配置层:这次请求能不能复用连接

真正的决策点在 ngx_http_finalize_connection() 里
(src/http/ngx_http_request.c:3047):

// src/http/ngx_http_request.c:3047-3061
    if (r->keepalive
        && clcf->keepalive_min_timeout > 0)
    {
        ngx_http_set_keepalive(r);
        return;
    }

    if (!ngx_terminate
         && !ngx_exiting
         && r->keepalive
         && clcf->keepalive_timeout > 0)
    {
        ngx_http_set_keepalive(r);
        return;
    }

三个条件:

条件 含义
r->keepalive 协议层同意复用(由 Connection 头 / 版本号决定)
clcf->keepalive_timeout > 0 配置层允许(keepalive_timeout 0; 就是禁用)
!ngx_terminate && !ngx_exiting 不是正在关停

keepalive_min_timeout 那条是「优雅退出时先不立刻断」的分支 ——
worker 收到退出信号后,给在途请求一点时间收尾。

9.6.3 复用之后

ngx_http_set_keepalive()(src/http/ngx_http_request.c:3352)
做三件事:

  1. 回收大缓冲 —— 把 hc->busy 里的备用块挪回 hc->free。
  2. 检查有没有流水线请求 —— 如果 b->pos < b->last,
    说明缓冲区里还有下一个请求(HTTP pipelining),
    直接起一个新的 ngx_http_create_request() 处理
    (src/http/ngx_http_request.c:3435)。
  3. 把 rev->handler 换成 ngx_http_keepalive_handler
    (src/http/ngx_http_request.c:3521),等下一个请求。

9.7 小结

  • 一个请求从字节到 ngx_http_request_t 填满,走五步:
    嗅探 → 请求行 → 请求头 → 请求头后处理 → 请求体。
  • 三台字节状态机(ngx_http_parse_request_line、
    ngx_http_parse_header_line、ngx_http_parse_chunked)
    都是无状态的,状态存在 r 里,所以能跨 TCP 包续解。
    nginx 处理分包没有第二套机制。
  • 请求头满了:先看这一行本身是否超限(超了就 NGX_DECLINED),
    再看有没有空闲的备用块(hc->free 或新分配)。
    拿到新块后要搬移数据并重定位所有解析指针。
  • chunked 由 ngx_http_parse_chunked() 解边界,
    解出来的数据是就地剥掉帧头的,下游看不到 chunk 结构。
    Content-Length 和 Transfer-Encoding 同时出现直接 400。
  • keepalive 两层判断:协议层(Connection 头 / HTTP 版本)
    决定「要不要」,配置层(keepalive_timeout)决定「能不能」。

下一篇讲 HTTP/2 与 HTTP/3:多路复用怎么在 nginx 里落地、
QUIC 怎么被接住,以及为什么 worker_connections 在 HTTP/2 下要重新算。

参考

  • 源码树:/work/ai/cwork/nginx(nginx 1.31.11,HEAD e76b6746c)
  • RFC 9112:HTTP/1.1 Message Syntax and HTTP/1.1 Semantics
  • RFC 7230 §3.3.3:Transfer-Encoding 与 chunked 的互斥规则
  • nginx 官方文档:http_core_module.html 的
    client_header_buffer_size / large_client_header_buffers / keepalive_timeout

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