Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #pragma once
26 :
27 : #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 202311L
28 : #include <stdbool.h>
29 : #endif
30 : #include <stddef.h>
31 :
32 : #include "chashmap.h"
33 :
34 : // The types chttpclient and chttpserver share. chttpclient.h and chttpserver.h
35 : // include this header for you; include it yourself only when you use these
36 : // types without either of them.
37 : //
38 : // Everything from here to the matching pop is the public ABI and the shared
39 : // library exports it. The library builds with -fvisibility=hidden, so anything
40 : // outside these blocks stays internal.
41 : #pragma GCC visibility push(default)
42 :
43 : // The HTTP methods the library knows.
44 : typedef enum chttp_method {
45 : CHTTP_GET = 0,
46 : CHTTP_POST,
47 : CHTTP_PUT,
48 : CHTTP_DELETE,
49 : CHTTP_PATCH,
50 : CHTTP_HEAD,
51 : CHTTP_OPTIONS,
52 : // A wildcard for registering a server handler: It matches all seven methods
53 : // above. It's never the method of a real request, so chttpsvr_req_method()
54 : // never gives it back. A client request refuses it (chttp_request_create()
55 : // gives NULL, chttp_perform() gives ccol_invalid_args), as any value
56 : // outside the seven. A method chttpserver doesn't know (TRACE, CONNECT, a
57 : // WebDAV or custom verb) gets 501 before routing, so even a CHTTP_ANY handler
58 : // never sees it.
59 : CHTTP_ANY
60 : } chttp_method;
61 :
62 : // Gives the uppercase name of method m, which the client puts on the request
63 : // line and both modules use in log lines. CHTTP_ANY gives "ANY" and a value
64 : // outside the enum gives "UNKNOWN".
65 1723 : static inline const char *chttp_method_str(chttp_method m) {
66 1723 : switch (m) {
67 4 : case CHTTP_GET:
68 4 : return "GET";
69 207 : case CHTTP_POST:
70 207 : return "POST";
71 12 : case CHTTP_PUT:
72 12 : return "PUT";
73 9 : case CHTTP_DELETE:
74 9 : return "DELETE";
75 10 : case CHTTP_PATCH:
76 10 : return "PATCH";
77 12 : case CHTTP_HEAD:
78 12 : return "HEAD";
79 3 : case CHTTP_OPTIONS:
80 3 : return "OPTIONS";
81 1 : case CHTTP_ANY:
82 1 : return "ANY";
83 1 : default:
84 1 : return "UNKNOWN";
85 : }
86 : }
87 :
88 : // HTTP status codes, named so handlers and callers needn't write bare numbers.
89 : //
90 : // 1xx: Informational
91 : #define CHTTP_STATUS_CONTINUE 100
92 : #define CHTTP_STATUS_SWITCHING_PROTOCOLS 101
93 :
94 : // 2xx: Success
95 : #define CHTTP_STATUS_OK 200
96 : #define CHTTP_STATUS_CREATED 201
97 : #define CHTTP_STATUS_ACCEPTED 202
98 : #define CHTTP_STATUS_NO_CONTENT 204
99 : #define CHTTP_STATUS_PARTIAL_CONTENT 206
100 :
101 : // 3xx: Redirection
102 : #define CHTTP_STATUS_MOVED_PERMANENTLY 301
103 : #define CHTTP_STATUS_FOUND 302
104 : #define CHTTP_STATUS_NOT_MODIFIED 304
105 : #define CHTTP_STATUS_TEMPORARY_REDIRECT 307
106 : #define CHTTP_STATUS_PERMANENT_REDIRECT 308
107 :
108 : // 4xx: Client errors
109 : #define CHTTP_STATUS_BAD_REQUEST 400
110 : #define CHTTP_STATUS_UNAUTHORIZED 401
111 : #define CHTTP_STATUS_FORBIDDEN 403
112 : #define CHTTP_STATUS_NOT_FOUND 404
113 : #define CHTTP_STATUS_METHOD_NOT_ALLOWED 405
114 : #define CHTTP_STATUS_NOT_ACCEPTABLE 406
115 : #define CHTTP_STATUS_REQUEST_TIMEOUT 408
116 : #define CHTTP_STATUS_CONFLICT 409
117 : #define CHTTP_STATUS_GONE 410
118 : #define CHTTP_STATUS_PAYLOAD_TOO_LARGE 413
119 : #define CHTTP_STATUS_UNSUPPORTED_MEDIA 415
120 : #define CHTTP_STATUS_UNPROCESSABLE 422
121 : #define CHTTP_STATUS_TOO_MANY_REQUESTS 429
122 :
123 : // 5xx: Server errors
124 : #define CHTTP_STATUS_INTERNAL_ERROR 500
125 : #define CHTTP_STATUS_NOT_IMPLEMENTED 501
126 : #define CHTTP_STATUS_BAD_GATEWAY 502
127 : #define CHTTP_STATUS_SERVICE_UNAVAILABLE 503
128 : #define CHTTP_STATUS_GATEWAY_TIMEOUT 504
129 : #define CHTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED 505
130 :
131 : // The TLS settings of chttpclient and chttpserver; each one ignores the fields
132 : // that aren't for it. A struct of all zeros is the strict configuration, and
133 : // that's why each relaxation is named for what turning it on gives up. So
134 : // {0}, {.ca_bundle_path = p} and {.cert_path = c, .key_path = k} all verify:
135 : // a client checks the server's chain and hostname, and a server with a
136 : // ca_bundle_path requires a client certificate that verifies against it.
137 : //
138 : // cert_path, key_path and ca_bundle_path must each name a regular file of at
139 : // most 16 MB; a directory, FIFO or device is refused as a load failure before
140 : // anything is read.
141 : //
142 : // A ca_bundle_path holds one or more PEM CA certificates and may hold CRLs
143 : // beside them (a file with CRLs only is refused). With a CRL in the bundle,
144 : // revocation is checked for the whole chain the peer presents, as nginx
145 : // ssl_crl does: Each certificate below the anchor needs a CRL of its issuer,
146 : // and a revoked certificate, a missing CRL or an expired CRL fails the
147 : // handshake. Without a CRL nothing is checked for revocation. The bundle is
148 : // read when the configuration is applied, so a renewed CRL takes effect at the
149 : // server's next chttpsvr_start() or the client's next chttpcli_set_tls().
150 : typedef struct chttp_tls_config {
151 : // The server certificate and key, or the client's for mutual TLS (NULL for
152 : // none), and a CA bundle (NULL for the system trust store).
153 : const char *cert_path;
154 : const char *key_path;
155 : const char *ca_bundle_path;
156 : // Client only. False verifies the server's chain, against ca_bundle_path when
157 : // it's set and the system store otherwise. True accepts any certificate from
158 : // any peer, so whoever can intercept the connection can read and change it;
159 : // it's for tests against throwaway servers, never for production. True also
160 : // turns off the hostname check: A hostname matched against an unverified
161 : // certificate proves nothing, so there's no way to ask for the hostname check
162 : // without the chain check. chttpcli_set_tls() refuses true together with a
163 : // ca_bundle_path (ccol_invalid_args).
164 : bool insecure_skip_verify;
165 : // Client only. False matches the request's hostname or IP literal against the
166 : // certificate. True keeps the chain check and drops only that match, for
167 : // example to reach a host by an address its certificate doesn't name. Any
168 : // peer with any certificate from the trusted CAs is then accepted, so pin the
169 : // narrowest ca_bundle_path you can. No effect when insecure_skip_verify is
170 : // true.
171 : bool insecure_skip_hostname_check;
172 : // Server only, and only beside ca_bundle_path. False enforces mutual TLS: A
173 : // client with no certificate, or one that doesn't verify, fails the
174 : // handshake. True only asks for one: A certificate that's presented must
175 : // verify, but a client without one is accepted, and a handler tells the cases
176 : // apart with chttpsvr_req_peer_cert_verified(). chttpclient ignores it.
177 : bool client_cert_optional;
178 : } chttp_tls_config;
179 :
180 : // The default TLS settings: chttp_tls_config tls = CHTTP_TLS_DEFAULT;. It's
181 : // the same as a zeroed struct; the name lets you say you want the defaults on
182 : // purpose.
183 : #define CHTTP_TLS_DEFAULT \
184 : ((chttp_tls_config){.cert_path = NULL, \
185 : .key_path = NULL, \
186 : .ca_bundle_path = NULL, \
187 : .insecure_skip_verify = false, \
188 : .insecure_skip_hostname_check = false, \
189 : .client_cert_optional = false})
190 :
191 : // A request body for the client API. It doesn't own data;
192 : // chttp_request_create_mp() copies the bytes, so you may free the source once
193 : // that call returns.
194 : typedef struct chttp_request_body {
195 : // The body bytes (NULL for none) and their length, and the Content-Type to
196 : // send when content_type isn't NULL (the caller owns the string).
197 : const void *data;
198 : size_t len;
199 : const char *content_type;
200 : } chttp_request_body;
201 :
202 : // A request body that holds nothing and sets no Content-Type, for client
203 : // requests that send no body.
204 : #define CHTTP_NO_BODY \
205 : ((chttp_request_body){.data = NULL, .len = 0, .content_type = NULL})
206 :
207 : // Builds a chttp_request_body compound literal from data d, length n and
208 : // content type ct (NULL sends no Content-Type), so a body can be passed inline
209 : // to the client calls. The request copies the bytes, so d may be freed once
210 : // the request is created. Each argument is evaluated once.
211 : #define CHTTP_BODY(d, n, ct) \
212 : ((chttp_request_body){.data = (d), .len = (n), .content_type = (ct)})
213 :
214 : // Builds a request body of n bytes at d with Content-Type application/json,
215 : // for the client calls. The request copies the bytes, so d may be freed once
216 : // the request is created. Each argument is evaluated once.
217 : #define CHTTP_JSON_BODY(d, n) CHTTP_BODY((d), (n), "application/json")
218 :
219 : // Builds a request body of n bytes at d with Content-Type text/plain, for the
220 : // client calls. The request copies the bytes, so d may be freed once the
221 : // request is created. Each argument is evaluated once.
222 : #define CHTTP_TEXT_BODY(d, n) CHTTP_BODY((d), (n), "text/plain")
223 :
224 : // Builds a request body of n bytes at d with Content-Type
225 : // application/x-www-form-urlencoded (an HTML form), for the client calls. The
226 : // request copies the bytes, so d may be freed once the request is created.
227 : // Each argument is evaluated once.
228 : #define CHTTP_FORM_BODY(d, n) \
229 : CHTTP_BODY((d), (n), "application/x-www-form-urlencoded")
230 :
231 : // Base64 and Basic auth.
232 :
233 : // Encodes len bytes of data as RFC 4648 base64 ('+' and '/', '=' padding), the
234 : // variant HTTP and Basic auth use, for callers that build header values. mp
235 : // is your allocator or NULL. data may be NULL only when len is 0. It gives a
236 : // new NUL-terminated string, with its length (without the NUL) in *out_len
237 : // when out_len isn't NULL, or NULL when the allocation fails, data is NULL
238 : // with len > 0, or the encoded size would overflow size_t. The caller frees
239 : // the string with the free function of mp (free() when mp is NULL).
240 : char *chttp_base64_encode_mp(ccol_memmgmt_procs *mp, const void *data,
241 : size_t len, size_t *out_len);
242 :
243 : // Encodes len bytes of data as RFC 4648 base64 ('+' and '/', '=' padding), the
244 : // variant HTTP and Basic auth use. data may be NULL only when len is 0. Gives a
245 : // new NUL-terminated string that the caller frees with free(), with its length
246 : // (without the NUL) in *out_len when out_len isn't NULL, or NULL when the
247 : // allocation fails, data is NULL with len > 0, or the encoded size would
248 : // overflow size_t.
249 65804 : static inline __attribute__((always_inline)) char *chttp_base64_encode(
250 : const void *data, size_t len, size_t *out_len) {
251 65804 : return chttp_base64_encode_mp(NULL, data, len, out_len);
252 : }
253 :
254 : // Decodes the NUL-terminated RFC 4648 base64 string b64_input (not NULL), for
255 : // callers that read encoded header values such as Basic credentials. Its
256 : // length must be a multiple of 4 and '=' may only be the last one or two
257 : // characters. The unused bits of a padded final group must be zero (RFC 4648
258 : // section 3.5), so each byte string has one encoding: "QQ==" gives "A" and
259 : // "QR==" is malformed. A bad character, misplaced padding, nonzero padding
260 : // bits or a wrong length is refused. mp is your allocator or NULL. It gives a
261 : // new buffer, or NULL when the input is malformed or the allocation fails. The
262 : // buffer ends with a NUL for convenience, but the data may hold NULs of its
263 : // own, so take the size from *out_len (out_len may be NULL), never from
264 : // strlen(). The caller frees the buffer with the free function of mp (free()
265 : // when mp is NULL).
266 : void *chttp_base64_decode_mp(ccol_memmgmt_procs *mp, const char *b64_input,
267 : size_t *out_len);
268 :
269 : // Decodes the NUL-terminated RFC 4648 base64 string b64_input (not NULL). Its
270 : // length must be a multiple of 4, '=' may only be the last one or two
271 : // characters, and the unused bits of a padded final group must be zero, so
272 : // "QQ==" gives "A" and "QR==" is refused. Gives a new buffer that the caller
273 : // frees with free(), or NULL when the input is malformed or the allocation
274 : // fails. The buffer ends with a NUL, but the data may hold NULs of its own, so
275 : // take the size from *out_len (out_len may be NULL), never from strlen().
276 266273 : static inline __attribute__((always_inline)) void *chttp_base64_decode(
277 : const char *b64_input, size_t *out_len) {
278 266273 : return chttp_base64_decode_mp(NULL, b64_input, out_len);
279 : }
280 :
281 : // Builds the RFC 7617 header value "Basic <base64(username:password)>",
282 : // without the "Authorization: " part, so a caller can authenticate a request
283 : // with chttp_request_set_header(req, "authorization", ...) or its chttpsvr
284 : // equivalent. Neither string may be NULL; both may be empty. The username
285 : // must not hold a colon: The recipient cuts at the first colon, so such a
286 : // user-id can't be sent unambiguously and is refused rather than turned into
287 : // another identity. The password may hold colons. A control byte (0x00 to
288 : // 0x1F, or 0x7F) in either is refused, as RFC 7617 section 2 requires; other
289 : // bytes, UTF-8 included, are encoded as they are. mp is your allocator or
290 : // NULL. It gives a new string that the caller frees with the free function of
291 : // mp (free() when mp is NULL), or NULL for a failed allocation or a refused
292 : // input.
293 : char *chttp_basic_auth_mp(ccol_memmgmt_procs *mp, const char *username,
294 : const char *password);
295 :
296 : // Builds the RFC 7617 header value "Basic <base64(username:password)>",
297 : // without the "Authorization: " part, for chttp_request_set_header(req,
298 : // "authorization", ...). Neither string may be NULL; both may be empty. A colon
299 : // in the username, or a control byte (0x00 to 0x1F, or 0x7F) in either, is
300 : // refused; the password may hold colons and UTF-8 is encoded as it is. Gives a
301 : // new string that the caller frees with free(), or NULL for a failed allocation
302 : // or a refused input.
303 25 : static inline __attribute__((always_inline)) char *chttp_basic_auth(
304 : const char *username, const char *password) {
305 19 : return chttp_basic_auth_mp(NULL, username, password);
306 : }
307 :
308 : #pragma GCC visibility pop
|