Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
n_http_req.c
Go to the documentation of this file.
1/*
2 * Nilorea Library
3 * Copyright (C) 2005-2026 Castagnier Mickael
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 * implied. See the License for the specific language governing
15 * permissions and limitations under the License.
16 *
17 * SPDX-License-Identifier: Apache-2.0
18 */
19
27#include "nilorea/n_http_req.h"
28
29#include <string.h>
30
31static int lc(int c) {
32 return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c;
33}
34
35/* Case-insensitive compare of an \p n-byte field name against a lowercase,
36 * NUL-terminated literal. */
37static int name_eq(const char* s, size_t n, const char* lit) {
38 size_t i;
39 for (i = 0; i < n; i++)
40 if (lit[i] == '\0' || lc((unsigned char)s[i]) != lit[i])
41 return 0;
42 return lit[n] == '\0';
43}
44
45/* Case-insensitive compare of two \p n-byte names, either case on both sides. */
46static int name_ieq(const char* a, const char* b, size_t n) {
47 size_t i;
48 for (i = 0; i < n; i++)
49 if (lc((unsigned char)a[i]) != lc((unsigned char)b[i]))
50 return 0;
51 return 1;
52}
53
54/* A field-name must be a non-empty RFC 9110 token: letters, digits and
55 * !#$%&'*+-.^_`|~ only. Controls, whitespace and separators are refused, so
56 * "Content-Length " with a trailing space is rejected, not silently ignored,
57 * a request-smuggling vector against a downstream proxy. */
58static int name_token_ok(const char* s, size_t n) {
59 size_t i;
60 if (n == 0)
61 return 0;
62 for (i = 0; i < n; i++) {
63 unsigned char c = (unsigned char)s[i];
64 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
65 continue;
66 if (!strchr("!#$%&'*+-.^_`|~", c) || c == '\0')
67 return 0;
68 }
69 return 1;
70}
71
72/* A field-value may hold visible ASCII, spaces, tabs and obs-text (0x80-0xff),
73 * never a control byte: a bare CR, LF or NUL inside a value is how a request
74 * is split or a header injected further down the chain. */
75static int value_ok(const char* s, size_t n) {
76 size_t i;
77 for (i = 0; i < n; i++) {
78 unsigned char c = (unsigned char)s[i];
79 if ((c < 0x20 && c != '\t') || c == 0x7f)
80 return 0;
81 }
82 return 1;
83}
84
85/* Parse a bounded non-negative decimal [s, s+n) into *out. Returns 1 on a clean
86 * parse within max, else 0 (empty / non-digit / over cap).
87 */
88static int parse_body_len(const char* s, size_t n, long long max, long long* out) {
89 unsigned long long v = 0;
90 size_t i;
91 if (n == 0)
92 return 0;
93 for (i = 0; i < n; i++) {
94 if (s[i] < '0' || s[i] > '9')
95 return 0;
96 v = v * 10u + (unsigned)(s[i] - '0');
97 if (v > (unsigned long long)max)
98 return 0;
99 }
100 *out = (long long)v;
101 return 1;
102}
103
104/* A valid byte in an origin-form request target: printable ASCII, no space, no
105 * '#' (a fragment must never reach the server). */
106static int target_ok(unsigned char c) {
107 return c > 0x20 && c < 0x7f && c != '#';
108}
109
110n_http_req_status n_http_request_parse_ex(const char* buf, size_t len, const n_http_req_limits* limits, n_http_request* out) {
111 size_t scan, i, sl, p, tstart, tend, line_start, nheaders = 0, nhost = 0;
112 int have_clen = 0;
113
114 if (!buf || !out || !limits)
115 return N_HTTP_REQ_ERROR;
116 memset(out, 0, sizeof(*out));
117 if (limits->methods == 0 || limits->body_max < 0 ||
119 return N_HTTP_REQ_ERROR;
120
121 /* locate the end of the head (CRLFCRLF) within the cap */
122 scan = len < N_HTTP_REQ_HEAD_MAX ? len : (size_t)N_HTTP_REQ_HEAD_MAX;
123 /* nothing shorter than the CRLFCRLF terminator itself can hold a head: the
124 * loop below cannot run, head_len stays 0, and since scan < 4 implies
125 * len < N_HTTP_REQ_HEAD_MAX the head_len test reports INCOMPLETE.
126 * The older cppcheck used by CI folds the ternary assignment above down to
127 * a single value of 0 and then calls this walk dead code, a valueflow
128 * false positive: scan follows the caller's len, unknown here. Spelling
129 * the bound as an explicit "if (scan < 4)" guard only moves the same
130 * diagnostic onto that guard, hence the inline suppression. */
131 // cppcheck-suppress knownConditionTrueFalse ; scan is caller-controlled, the walk is reachable
132 for (i = 0; i + 3 < scan; i++)
133 if (buf[i] == '\r' && buf[i + 1] == '\n' && buf[i + 2] == '\r' &&
134 buf[i + 3] == '\n') {
135 out->head_len = i + 4;
136 break;
137 }
138 if (out->head_len == 0)
141
142 /* Request line: METHOD SP target SP HTTP/1.x CRLF */
143 sl = 0;
144 while (sl + 1 < out->head_len && !(buf[sl] == '\r' && buf[sl + 1] == '\n'))
145 sl++;
146 if (sl >= 4 && memcmp(buf, "GET ", 4) == 0) {
147 out->method = N_HTTP_REQ_GET;
148 p = 4;
149 } else if (sl >= 5 && memcmp(buf, "POST ", 5) == 0) {
150 out->method = N_HTTP_REQ_POST;
151 p = 5;
152 } else if (sl >= 5 && memcmp(buf, "HEAD ", 5) == 0) {
153 out->method = N_HTTP_REQ_HEAD;
154 p = 5;
155 } else {
156 return N_HTTP_REQ_ERROR;
157 }
158 if (!(limits->methods & N_HTTP_REQ_METHOD_BIT(out->method)))
159 return N_HTTP_REQ_ERROR;
160 /* origin-form target, from p to the next space */
161 tstart = p;
162 while (p < sl && buf[p] != ' ') {
163 if (!target_ok((unsigned char)buf[p]))
164 return N_HTTP_REQ_ERROR;
165 p++;
166 }
167 tend = p;
168 if (tend == tstart || buf[tstart] != '/' ||
169 tend - tstart > N_HTTP_REQ_PATH_MAX)
170 return N_HTTP_REQ_ERROR;
171 /* exactly one SP, then the version filling the rest of the line */
172 if (p >= sl || buf[p] != ' ')
173 return N_HTTP_REQ_ERROR;
174 p++;
175 if (sl - p != 8 || memcmp(buf + p, "HTTP/1.", 7) != 0 ||
176 (buf[p + 7] != '0' && buf[p + 7] != '1'))
177 return N_HTTP_REQ_ERROR;
178 out->version_minor = buf[p + 7] - '0';
179 memcpy(out->path, buf + tstart, tend - tstart);
180 out->path[tend - tstart] = '\0';
181
182 /* Header lines up to the blank line */
183 line_start = sl + 2;
184 while (line_start + 1 < out->head_len) {
185 size_t le = line_start, colon, vs, vlen, nlen;
186 const char *name, *val;
187 while (le + 1 < out->head_len &&
188 !(buf[le] == '\r' && buf[le + 1] == '\n'))
189 le++;
190 if (le == line_start)
191 break; /* blank line: end of headers */
192 if (++nheaders > N_HTTP_REQ_HEADERS_MAX)
193 return N_HTTP_REQ_ERROR;
194 colon = line_start;
195 while (colon < le && buf[colon] != ':')
196 colon++;
197 if (colon >= le)
198 return N_HTTP_REQ_ERROR; /* header without a colon */
199 name = buf + line_start;
200 nlen = colon - line_start;
201 if (!name_token_ok(name, nlen))
202 return N_HTTP_REQ_ERROR;
203 vs = colon + 1;
204 while (vs < le && (buf[vs] == ' ' || buf[vs] == '\t'))
205 vs++;
206 val = buf + vs;
207 vlen = le - vs;
208 while (vlen > 0 && (val[vlen - 1] == ' ' || val[vlen - 1] == '\t'))
209 vlen--;
210 if (!value_ok(val, vlen))
211 return N_HTTP_REQ_ERROR;
212 out->headers[out->nb_headers].name_off = line_start;
213 out->headers[out->nb_headers].name_len = nlen;
214 out->headers[out->nb_headers].value_off = vs;
215 out->headers[out->nb_headers].value_len = vlen;
216 out->nb_headers++;
217 if (name_eq(name, nlen, "host"))
218 nhost++;
219 if (name_eq(name, nlen, "transfer-encoding"))
220 return N_HTTP_REQ_ERROR; /* no chunked, smuggling defense */
221 if (name_eq(name, nlen, "content-length")) {
222 long long cl;
223 if (have_clen) /* duplicate Content-Length, smuggling */
224 return N_HTTP_REQ_ERROR;
225 if (!parse_body_len(val, vlen, limits->body_max, &cl))
226 return N_HTTP_REQ_ERROR;
227 out->content_length = cl;
228 have_clen = 1;
229 } else if (name_eq(name, nlen, "authorization")) {
230 /* capture the credential; refuse rather than truncate an over-long
231 * one (a truncated bearer token must never be treated as valid) */
232 if (out->authorization[0] != '\0' || vlen > N_HTTP_REQ_AUTH_MAX)
233 return N_HTTP_REQ_ERROR;
234 memcpy(out->authorization, val, vlen);
235 out->authorization[vlen] = '\0';
236 }
237 line_start = le + 2;
238 }
239 if (limits->require_host &&
240 (nhost > 1 || (nhost == 0 && out->version_minor == 1)))
241 return N_HTTP_REQ_ERROR;
242 return N_HTTP_REQ_OK;
243}
244
245n_http_req_status n_http_request_parse(const char* buf, size_t len, n_http_request* out) {
246 n_http_req_limits limits;
248 limits.body_max = (long long)N_HTTP_REQ_BODY_MAX;
249 limits.require_host = 0;
250 return n_http_request_parse_ex(buf, len, &limits, out);
251}
252
253const char* n_http_request_header(const n_http_request* req, const char* buf, const char* name, size_t* value_len) {
254 size_t i, n;
255 if (value_len)
256 *value_len = 0;
257 if (!req || !buf || !name)
258 return NULL;
259 n = strlen(name);
260 for (i = 0; i < req->nb_headers && i < N_HTTP_REQ_HEADERS_MAX; i++) {
261 const n_http_req_header* h = &req->headers[i];
262 if (h->name_len == n && name_ieq(buf + h->name_off, name, n)) {
263 if (value_len)
264 *value_len = h->value_len;
265 return buf + h->value_off;
266 }
267 }
268 return NULL;
269}
270
271size_t n_http_request_header_count(const n_http_request* req, const char* buf, const char* name) {
272 size_t i, n, count = 0;
273 if (!req || !buf || !name)
274 return 0;
275 n = strlen(name);
276 for (i = 0; i < req->nb_headers && i < N_HTTP_REQ_HEADERS_MAX; i++) {
277 const n_http_req_header* h = &req->headers[i];
278 if (h->name_len == n && name_ieq(buf + h->name_off, name, n))
279 count++;
280 }
281 return count;
282}
static int h(void *ctx, const N_ROUTE_MATCH *m)
a handler that does nothing (the test only routes)
int require_host
non-zero: an HTTP/1.1 request must carry exactly one Host header and an HTTP/1.0 one at most one (RFC...
Definition n_http_req.h:105
long long body_max
largest accepted Content-Length, 0 to N_HTTP_REQ_BODY_LIMIT_MAX
Definition n_http_req.h:102
char authorization[256u+1]
Definition n_http_req.h:122
unsigned methods
accepted methods, an OR of N_HTTP_REQ_METHOD_BIT(); any other method is an error
Definition n_http_req.h:100
char path[2048u+1]
Definition n_http_req.h:119
size_t nb_headers
Definition n_http_req.h:124
long long content_length
Definition n_http_req.h:120
n_http_req_method method
Definition n_http_req.h:118
n_http_req_header headers[64u]
Definition n_http_req.h:125
#define N_HTTP_REQ_METHOD_BIT(m)
Bit of a method in n_http_req_limits.methods.
Definition n_http_req.h:84
n_http_req_status n_http_request_parse_ex(const char *buf, size_t len, const n_http_req_limits *limits, n_http_request *out)
parse an HTTP/1.1 request head with caller-chosen limits
Definition n_http_req.c:110
#define N_HTTP_REQ_HEAD_MAX
Largest request head (request line + headers, through CRLFCRLF) accepted.
Definition n_http_req.h:63
n_http_req_status
Result of n_http_request_parse.
Definition n_http_req.h:130
const char * n_http_request_header(const n_http_request *req, const char *buf, const char *name, size_t *value_len)
find a header of a parsed request
Definition n_http_req.c:253
n_http_req_status n_http_request_parse(const char *buf, size_t len, n_http_request *out)
parse an HTTP/1.1 request head from [buf, buf+len)
Definition n_http_req.c:245
size_t n_http_request_header_count(const n_http_request *req, const char *buf, const char *name)
count the headers of a parsed request that carry a name
Definition n_http_req.c:271
#define N_HTTP_REQ_BODY_LIMIT_MAX
Highest body cap n_http_request_parse_ex() accepts (1 GiB).
Definition n_http_req.h:72
#define N_HTTP_REQ_AUTH_MAX
Longest captured Authorization header value.
Definition n_http_req.h:74
#define N_HTTP_REQ_BODY_MAX
Maximum declared Content-Length (body size), in bytes, for n_http_request_parse().
Definition n_http_req.h:70
#define N_HTTP_REQ_HEADERS_MAX
Maximum number of header lines.
Definition n_http_req.h:67
#define N_HTTP_REQ_PATH_MAX
Longest origin-form request target ('/'-prefixed, query included).
Definition n_http_req.h:65
@ N_HTTP_REQ_INCOMPLETE
no CRLFCRLF yet, still under the cap
Definition n_http_req.h:132
@ N_HTTP_REQ_ERROR
malformed / oversized / unsupported
Definition n_http_req.h:133
@ N_HTTP_REQ_OK
a complete, valid head was parsed
Definition n_http_req.h:131
@ N_HTTP_REQ_POST
Definition n_http_req.h:79
@ N_HTTP_REQ_GET
Definition n_http_req.h:78
@ N_HTTP_REQ_HEAD
Definition n_http_req.h:80
One header line, as offsets into the parsed buffer: the name is [name_off, name_off + name_len),...
Definition n_http_req.h:89
Limits for n_http_request_parse_ex().
Definition n_http_req.h:97
A parsed request head.
Definition n_http_req.h:117
static int value_ok(const char *s, size_t n)
Definition n_http_req.c:75
static int target_ok(unsigned char c)
Definition n_http_req.c:106
static int name_eq(const char *s, size_t n, const char *lit)
Definition n_http_req.c:37
static int lc(int c)
Definition n_http_req.c:31
static int name_token_ok(const char *s, size_t n)
Definition n_http_req.c:58
static int parse_body_len(const char *s, size_t n, long long max, long long *out)
Definition n_http_req.c:88
static int name_ieq(const char *a, const char *b, size_t n)
Definition n_http_req.c:46
Pure, strict, bounded parser for an HTTP/1.1 request head.
static uint64_t le(const unsigned char *p, int n)
read a little endian unsigned value
Definition n_pth.c:233