Line data Source code
1 : #define _GNU_SOURCE
2 : #include "fd_http_server_private.h"
3 :
4 : #include "../../third_party/picohttpparser/picohttpparser.h"
5 : #include "../../ballet/sha1/fd_sha1.h"
6 : #include "../../ballet/base64/fd_base64.h"
7 : #include "../../util/net/fd_ip4.h"
8 : #include "fd_http.h"
9 :
10 : #include <stdarg.h>
11 : #include <stdio.h>
12 : #include <errno.h>
13 : #include <unistd.h>
14 : #include <poll.h>
15 : #include <stdlib.h>
16 : #include <strings.h>
17 : #include <sys/socket.h>
18 : #include <sys/epoll.h>
19 : #include <netinet/in.h>
20 : #include <netinet/tcp.h>
21 :
22 0 : #define FD_HTTP_ZSTD_COMPRESSION_LEVEL 3
23 : /* levels 4-15 are compiled out of libfd_zstd (third_party/zstd/Local.mk) */
24 : FD_STATIC_ASSERT( FD_HTTP_ZSTD_COMPRESSION_LEVEL<=3 || FD_HTTP_ZSTD_COMPRESSION_LEVEL>=16, zstd_level );
25 : #define ZSTD_STATIC_LINKING_ONLY
26 : #include <zstd.h>
27 :
28 : #define POOL_NAME ws_conn_pool
29 0 : #define POOL_T struct fd_http_server_ws_connection
30 : #define POOL_IDX_T ushort
31 0 : #define POOL_NEXT parent
32 : #include "../../util/tmpl/fd_pool.c"
33 :
34 : #define POOL_NAME conn_pool
35 0 : #define POOL_T struct fd_http_server_connection
36 : #define POOL_IDX_T ushort
37 0 : #define POOL_NEXT parent
38 : #include "../../util/tmpl/fd_pool.c"
39 :
40 : #define TREAP_NAME ws_conn_treap
41 : #define TREAP_T struct fd_http_server_ws_connection
42 : #define TREAP_QUERY_T void * /* We don't use query ... */
43 : #define TREAP_CMP(q,e) (__extension__({ (void)(q); (void)(e); -1; })) /* which means we don't need to give a real
44 : implementation to cmp either */
45 0 : #define TREAP_IDX_T ushort
46 : #define TREAP_OPTIMIZE_ITERATION 1
47 0 : #define TREAP_LT(e0,e1) ((e0)->send_frames[ (e0)->send_frame_idx ].off<(e1)->send_frames[ (e1)->send_frame_idx ].off)
48 :
49 : #include "../../util/tmpl/fd_treap.c"
50 :
51 : #define TREAP_NAME conn_treap
52 : #define TREAP_T struct fd_http_server_connection
53 : #define TREAP_QUERY_T void * /* We don't use query ... */
54 : #define TREAP_CMP(q,e) (__extension__({ (void)(q); (void)(e); -1; })) /* which means we don't need to give a real
55 : implementation to cmp either */
56 0 : #define TREAP_IDX_T ushort
57 : #define TREAP_OPTIMIZE_ITERATION 1
58 0 : #define TREAP_LT(e0,e1) ((e0)->response._body_off<(e1)->response._body_off)
59 :
60 : #include "../../util/tmpl/fd_treap.c"
61 :
62 : #define FD_HTTP_SERVER_DEBUG 0
63 :
64 : FD_FN_CONST char const *
65 0 : fd_http_server_connection_close_reason_str( int reason ) {
66 0 : switch( reason ) {
67 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_OK: return "OK-Connection was closed normally";
68 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED: return "EVICTED-Connection was evicted to make room for a new one";
69 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_TOO_SLOW: return "TOO_SLOW-Client was too slow and did not read the response in time";
70 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_EXPECTED_EOF: return "EXPECTED_EOF-Client continued to send data when we expected no more";
71 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET: return "PEER_RESET-Connection was reset by peer";
72 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_LARGE_REQUEST: return "LARGE_REQUEST-Request body was too large";
73 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST: return "BAD_REQUEST-Request was malformed";
74 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_MISSING_CONTENT_LENGTH_HEADER: return "MISSING_CONTENT_LENGTH_HEADER-Missing Content-Length header field";
75 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_UNKNOWN_METHOD: return "UNKNOWN_METHOD-Request method was not recognized";
76 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_PATH_TOO_LONG: return "PATH_TOO_LONG-Request path was too long";
77 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_KEY: return "WS_BAD_KEY-Malformed Sec-WebSocket-Key header field";
78 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_UNEXPECTED_VERSION: return "WS_UNEXPECTED_VERSION-Unexpected Sec-Websocket-Version field";
79 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_KEY_HEADER: return "WS_MISSING_KEY_HEADER-Missing Sec-WebSocket-Key header field";
80 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_VERSION_HEADER: return "WS_MISSING_VERSION_HEADER-Missing Sec-WebSocket-Version header field";
81 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_MASK: return "WS_BAD_MASK-Got frame from client without mask flag set";
82 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_UNKNOWN_OPCODE: return "WS_UNKNOWN_OPCODE-Unknown opcode in websocket frame";
83 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_OVERSIZE_FRAME: return "WS_OVERSIZE_FRAME-Websocket frame was too large";
84 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CLIENT_TOO_SLOW: return "WS_CLIENT_TOO_SLOW-Client was too slow to keep up with sender";
85 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_UPGRADE: return "WS_MISSING_UPGRADE-Missing Upgrade header field";
86 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_EXPECTED_CONT_OPCODE: return "WS_EXPECTED_CONT_OPCODE-Expected continuation opcode in websocket frame";
87 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_EXPECTED_TEXT_OPCODE: return "WS_EXPECTED_TEXT_OPCODE-Expected text opcode in websocket frame";
88 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CONTROL_FRAME_TOO_LARGE: return "WS_CONTROL_FRAME_TOO_LARGE-Websocket control frame was too large";
89 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_UNSUPPORTED_TRANSFER_ENCODING: return "UNSUPPORTED_TRANSFER_ENCODING-Transfer-Encoding is not supported";
90 0 : default: break;
91 0 : }
92 :
93 0 : return "unknown";
94 0 : }
95 :
96 : FD_FN_CONST char const *
97 0 : fd_http_server_method_str( uchar method ) {
98 0 : switch( method ) {
99 0 : case FD_HTTP_SERVER_METHOD_GET: return "GET";
100 0 : case FD_HTTP_SERVER_METHOD_POST: return "POST";
101 0 : case FD_HTTP_SERVER_METHOD_PUT: return "PUT";
102 0 : case FD_HTTP_SERVER_METHOD_HEAD: return "HEAD";
103 0 : default: break;
104 0 : }
105 :
106 0 : return "unknown";
107 0 : }
108 :
109 : FD_FN_CONST ulong
110 0 : fd_http_server_align( void ) {
111 0 : return FD_HTTP_SERVER_ALIGN;
112 0 : }
113 :
114 : FD_FN_CONST ulong
115 0 : fd_http_server_footprint( fd_http_server_params_t params ) {
116 0 : ulong l = FD_LAYOUT_INIT;
117 0 : l = FD_LAYOUT_APPEND( l, FD_HTTP_SERVER_ALIGN, sizeof( fd_http_server_t ) );
118 0 : l = FD_LAYOUT_APPEND( l, conn_pool_align(), conn_pool_footprint( params.max_connection_cnt ) );
119 0 : l = FD_LAYOUT_APPEND( l, ws_conn_pool_align(), ws_conn_pool_footprint( params.max_ws_connection_cnt ) );
120 0 : l = FD_LAYOUT_APPEND( l, conn_treap_align(), conn_treap_footprint( params.max_connection_cnt ) );
121 0 : l = FD_LAYOUT_APPEND( l, ws_conn_treap_align(), ws_conn_treap_footprint( params.max_ws_connection_cnt ) );
122 0 : l = FD_LAYOUT_APPEND( l, alignof( struct pollfd ), (params.max_connection_cnt+params.max_ws_connection_cnt+1UL)*sizeof( struct pollfd ) );
123 0 : l = FD_LAYOUT_APPEND( l, 1UL, params.max_request_len*params.max_connection_cnt );
124 0 : l = FD_LAYOUT_APPEND( l, 1UL, params.max_ws_recv_frame_len*params.max_ws_connection_cnt );
125 0 : l = FD_LAYOUT_APPEND( l, alignof( struct fd_http_server_ws_frame ), params.max_ws_send_frame_cnt*params.max_ws_connection_cnt*sizeof( struct fd_http_server_ws_frame ) );
126 0 : l = FD_LAYOUT_APPEND( l, 1UL, params.outgoing_buffer_sz );
127 0 : l = FD_LAYOUT_APPEND( l, 16UL, ZSTD_estimateCCtxSize( FD_HTTP_ZSTD_COMPRESSION_LEVEL ) );
128 0 : return FD_LAYOUT_FINI( l, fd_http_server_align() );
129 0 : }
130 :
131 : void *
132 : fd_http_server_new( void * shmem,
133 : fd_http_server_params_t params,
134 : fd_http_server_callbacks_t callbacks,
135 0 : void * callback_ctx ) {
136 0 : if( FD_UNLIKELY( !shmem ) ) {
137 0 : FD_LOG_WARNING(( "NULL shmem" ));
138 0 : return NULL;
139 0 : }
140 :
141 0 : if( FD_UNLIKELY( params.send_buffer_sz>(ulong)INT_MAX ) ) {
142 0 : FD_LOG_WARNING(( "oversize send_buffer_sz" ));
143 0 : return NULL;
144 0 : }
145 :
146 0 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)shmem, fd_http_server_align() ) ) ) {
147 0 : FD_LOG_WARNING(( "misaligned shmem" ));
148 0 : return NULL;
149 0 : }
150 :
151 0 : if( FD_UNLIKELY( params.max_ws_connection_cnt && params.max_ws_recv_frame_len<params.max_request_len ) ) {
152 0 : FD_LOG_WARNING(( "max_ws_recv_frame_len<max_request_len" ));
153 0 : return NULL;
154 0 : }
155 :
156 0 : FD_SCRATCH_ALLOC_INIT( l, shmem );
157 0 : fd_http_server_t * http = FD_SCRATCH_ALLOC_APPEND( l, FD_HTTP_SERVER_ALIGN, sizeof(fd_http_server_t) );
158 0 : void * conn_pool = FD_SCRATCH_ALLOC_APPEND( l, conn_pool_align(), conn_pool_footprint( params.max_connection_cnt ) );
159 0 : void * ws_conn_pool = FD_SCRATCH_ALLOC_APPEND( l, ws_conn_pool_align(), ws_conn_pool_footprint( params.max_ws_connection_cnt ) );
160 0 : http->conn_treap = FD_SCRATCH_ALLOC_APPEND( l, conn_treap_align(), conn_treap_footprint( params.max_connection_cnt ) );
161 0 : http->ws_conn_treap = FD_SCRATCH_ALLOC_APPEND( l, ws_conn_treap_align(), ws_conn_treap_footprint( params.max_ws_connection_cnt ) );
162 0 : http->pollfds = FD_SCRATCH_ALLOC_APPEND( l, alignof(struct pollfd), (params.max_connection_cnt+params.max_ws_connection_cnt+1UL)*sizeof( struct pollfd ) );
163 0 : char * _request_bytes = FD_SCRATCH_ALLOC_APPEND( l, 1UL, params.max_request_len*params.max_connection_cnt );
164 0 : uchar * _ws_recv_bytes = FD_SCRATCH_ALLOC_APPEND( l, 1UL, params.max_ws_recv_frame_len*params.max_ws_connection_cnt );
165 0 : struct fd_http_server_ws_frame * _ws_send_frames = FD_SCRATCH_ALLOC_APPEND( l, alignof(struct fd_http_server_ws_frame), params.max_ws_send_frame_cnt*params.max_ws_connection_cnt*sizeof(struct fd_http_server_ws_frame) );
166 0 : http->oring = FD_SCRATCH_ALLOC_APPEND( l, 1UL, params.outgoing_buffer_sz );
167 0 : uchar * _zstd_ctx = FD_SCRATCH_ALLOC_APPEND( l, 16UL, ZSTD_estimateCCtxSize( FD_HTTP_ZSTD_COMPRESSION_LEVEL ) );
168 0 : http->oring_sz = params.outgoing_buffer_sz;
169 0 : http->stage_err = 0;
170 0 : http->stage_off = 0UL;
171 0 : http->stage_len = 0UL;
172 0 : http->stage_comp_len = 0UL;
173 0 : http->stage_reserved_end = 0UL;
174 :
175 0 : http->callbacks = callbacks;
176 0 : http->callback_ctx = callback_ctx;
177 0 : http->evict_conn_id = 0UL;
178 0 : http->evict_ws_conn_id = 0UL;
179 0 : http->epoll_fd = -1;
180 0 : http->max_conns = params.max_connection_cnt;
181 0 : http->max_ws_conns = params.max_ws_connection_cnt;
182 0 : http->max_request_len = params.max_request_len;
183 0 : http->max_ws_recv_frame_len = params.max_ws_recv_frame_len;
184 0 : http->max_ws_send_frame_cnt = params.max_ws_send_frame_cnt;
185 0 : http->send_buffer_sz = params.send_buffer_sz;
186 0 : http->compress_websocket = params.compress_websocket;
187 :
188 0 : http->zstd_ctx = ZSTD_initStaticCCtx( _zstd_ctx, ZSTD_estimateCCtxSize( FD_HTTP_ZSTD_COMPRESSION_LEVEL ) );
189 0 : FD_TEST( http->zstd_ctx );
190 0 : ulong err = ZSTD_CCtx_setParameter( http->zstd_ctx, 100, FD_HTTP_ZSTD_COMPRESSION_LEVEL );
191 0 : if( FD_UNLIKELY( ZSTD_isError( err ) ) )
192 0 : FD_LOG_ERR(( "ZSTD_CCtx_setParameter failed (%s)", ZSTD_getErrorName( err ) ) );
193 :
194 0 : http->conns = conn_pool_join( conn_pool_new( conn_pool, params.max_connection_cnt ) );
195 0 : conn_treap_join( conn_treap_new( http->conn_treap, params.max_connection_cnt ) );
196 :
197 0 : http->ws_conns = ws_conn_pool_join( ws_conn_pool_new( ws_conn_pool, params.max_ws_connection_cnt ) );
198 0 : ws_conn_treap_join( ws_conn_treap_new( http->ws_conn_treap, params.max_ws_connection_cnt ) );
199 :
200 0 : for( ulong i=0UL; i<params.max_connection_cnt; i++ ) {
201 0 : http->pollfds[ i ].fd = -1;
202 0 : http->pollfds[ i ].events = POLLIN;
203 0 : http->conns[ i ] = (struct fd_http_server_connection){
204 0 : .request_bytes = _request_bytes+i*params.max_request_len,
205 0 : .parent = http->conns[ i ].parent,
206 0 : };
207 0 : }
208 :
209 0 : for( ulong i=0UL; i<params.max_ws_connection_cnt; i++ ) {
210 0 : http->pollfds[ params.max_connection_cnt+i ].fd = -1;
211 0 : http->pollfds[ params.max_connection_cnt+i ].events = POLLIN;
212 0 : http->ws_conns[ i ] = (struct fd_http_server_ws_connection){
213 0 : .recv_bytes = _ws_recv_bytes+i*params.max_ws_recv_frame_len,
214 0 : .send_frames = _ws_send_frames+i*params.max_ws_send_frame_cnt,
215 0 : .parent = http->ws_conns[ i ].parent,
216 0 : };
217 0 : }
218 0 : conn_treap_seed ( http->conns, params.max_connection_cnt, params.treap_seed );
219 0 : ws_conn_treap_seed( http->ws_conns, params.max_ws_connection_cnt, params.treap_seed );
220 :
221 0 : http->pollfds[ params.max_connection_cnt+params.max_ws_connection_cnt ].fd = -1;
222 0 : http->pollfds[ params.max_connection_cnt+params.max_ws_connection_cnt ].events = POLLIN;
223 :
224 0 : memset( &http->metrics, 0, sizeof( http->metrics ) );
225 :
226 0 : FD_COMPILER_MFENCE();
227 0 : FD_VOLATILE( http->magic ) = FD_HTTP_SERVER_MAGIC;
228 0 : FD_COMPILER_MFENCE();
229 :
230 0 : return (void *)http;
231 0 : }
232 :
233 : fd_http_server_t *
234 0 : fd_http_server_join( void * shhttp ) {
235 :
236 0 : if( FD_UNLIKELY( !shhttp ) ) {
237 0 : FD_LOG_WARNING(( "NULL shhttp" ));
238 0 : return NULL;
239 0 : }
240 :
241 0 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)shhttp, fd_http_server_align() ) ) ) {
242 0 : FD_LOG_WARNING(( "misaligned shhttp" ));
243 0 : return NULL;
244 0 : }
245 :
246 0 : fd_http_server_t * http = (fd_http_server_t *)shhttp;
247 :
248 0 : if( FD_UNLIKELY( http->magic!=FD_HTTP_SERVER_MAGIC ) ) {
249 0 : FD_LOG_WARNING(( "bad magic" ));
250 0 : return NULL;
251 0 : }
252 :
253 0 : return http;
254 0 : }
255 :
256 : void *
257 0 : fd_http_server_leave( fd_http_server_t * http ) {
258 :
259 0 : if( FD_UNLIKELY( !http ) ) {
260 0 : FD_LOG_WARNING(( "NULL http" ));
261 0 : return NULL;
262 0 : }
263 :
264 0 : return (void *)http;
265 0 : }
266 :
267 : void *
268 0 : fd_http_server_delete( void * shhttp ) {
269 :
270 0 : if( FD_UNLIKELY( !shhttp ) ) {
271 0 : FD_LOG_WARNING(( "NULL shhttp" ));
272 0 : return NULL;
273 0 : }
274 :
275 0 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)shhttp, fd_http_server_align() ) ) ) {
276 0 : FD_LOG_WARNING(( "misaligned shhttp" ));
277 0 : return NULL;
278 0 : }
279 :
280 0 : fd_http_server_t * http = (fd_http_server_t *)shhttp;
281 :
282 0 : if( FD_UNLIKELY( http->magic!=FD_HTTP_SERVER_MAGIC ) ) {
283 0 : FD_LOG_WARNING(( "bad magic" ));
284 0 : return NULL;
285 0 : }
286 :
287 0 : FD_COMPILER_MFENCE();
288 0 : FD_VOLATILE( http->magic ) = 0UL;
289 0 : FD_COMPILER_MFENCE();
290 :
291 0 : return (void *)http;
292 0 : }
293 :
294 : int
295 0 : fd_http_server_fd( fd_http_server_t * http ) {
296 0 : return http->socket_fd;
297 0 : }
298 :
299 : fd_http_server_t *
300 : fd_http_server_listen( fd_http_server_t * http,
301 : int epoll_fd,
302 : uint address,
303 0 : ushort port ) {
304 0 : fd_ip6_addr_t addr6 = {0};
305 0 : fd_ip6_addr_ip4_mapped( addr6.addr, address );
306 0 : return fd_http_server_listen6( http, epoll_fd, &addr6, port );
307 0 : }
308 :
309 : fd_http_server_t *
310 : fd_http_server_listen6( fd_http_server_t * http,
311 : int epoll_fd,
312 : fd_ip6_addr_t const * address,
313 0 : ushort port ) {
314 0 : FD_TEST( -1!=epoll_fd );
315 0 : http->epoll_fd = epoll_fd;
316 :
317 : /* An IPv4 address is served by an AF_INET socket, anything else by a
318 : dual stack AF_INET6 socket */
319 0 : int ip4 = fd_ip6_addr_is_ip4_mapped( address->addr ) && !address->scope_id;
320 :
321 0 : int sockfd = socket( ip4 ? AF_INET : AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, 0 );
322 0 : if( FD_UNLIKELY( -1==sockfd ) ) FD_LOG_ERR(( "socket failed (%i-%s)", errno, strerror( errno ) ));
323 :
324 0 : int optval = 1;
325 0 : if( FD_UNLIKELY( -1==setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof( optval ) ) ) )
326 0 : FD_LOG_ERR(( "setsockopt failed (%i-%s)", errno, strerror( errno ) ));
327 :
328 : /* Pipelines responses: without this Nagle holds each sub-MSS tail
329 : for an RTT waiting on the prior segment's ACK */
330 0 : if( FD_UNLIKELY( -1==setsockopt( sockfd, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof( optval ) ) ) )
331 0 : FD_LOG_ERR(( "setsockopt(TCP_NODELAY) failed (%i-%s)", errno, strerror( errno ) ));
332 :
333 0 : if( FD_UNLIKELY( http->send_buffer_sz ) ) {
334 0 : int sndbuf = (int)http->send_buffer_sz;
335 0 : if( FD_UNLIKELY( -1==setsockopt( sockfd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof( sndbuf ) ) ) )
336 0 : FD_LOG_ERR(( "setsockopt(SO_SNDBUF) failed (%i-%s)", errno, strerror( errno ) ));
337 0 : }
338 :
339 0 : union {
340 0 : struct sockaddr_in ip4;
341 0 : struct sockaddr_in6 ip6;
342 0 : } addr = {0};
343 0 : ulong addr_sz;
344 :
345 0 : if( ip4 ) {
346 0 : addr.ip4 = (struct sockaddr_in){
347 0 : .sin_family = AF_INET,
348 0 : .sin_port = fd_ushort_bswap( port ),
349 0 : .sin_addr.s_addr = fd_ip6_addr_to_ip4( address->addr ),
350 0 : };
351 0 : addr_sz = sizeof(struct sockaddr_in);
352 0 : } else {
353 : /* Accept IPv4 clients too (as IPv4-mapped peers) if the socket is
354 : bound to the wildcard address */
355 0 : int v6only = 0;
356 0 : if( FD_UNLIKELY( -1==setsockopt( sockfd, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof( v6only ) ) ) )
357 0 : FD_LOG_ERR(( "setsockopt(IPV6_V6ONLY) failed (%i-%s)", errno, strerror( errno ) ));
358 :
359 0 : addr.ip6 = (struct sockaddr_in6){
360 0 : .sin6_family = AF_INET6,
361 0 : .sin6_port = fd_ushort_bswap( port ),
362 0 : .sin6_scope_id = address->scope_id,
363 0 : };
364 0 : memcpy( addr.ip6.sin6_addr.s6_addr, address->addr, 16UL );
365 0 : addr_sz = sizeof(struct sockaddr_in6);
366 0 : }
367 :
368 0 : if( FD_UNLIKELY( -1==bind( sockfd, fd_type_pun( &addr ), (uint)addr_sz ) ) ) {
369 0 : char addr_cstr[ FD_IP6_ADDR_CSTR_MAX ];
370 0 : FD_LOG_ERR(( "bind(%i,%s:%u) failed (%i-%s)",
371 0 : sockfd, fd_ip6_addr_cstr( addr_cstr, address ), port,
372 0 : errno, fd_io_strerror( errno ) ));
373 0 : }
374 0 : if( FD_UNLIKELY( -1==listen( sockfd, (int)http->max_conns ) ) ) FD_LOG_ERR(( "listen failed (%i-%s)", errno, fd_io_strerror( errno ) ));
375 :
376 0 : http->socket_fd = sockfd;
377 0 : http->pollfds[ http->max_conns+http->max_ws_conns ].fd = http->socket_fd;
378 0 : struct epoll_event ev = { .events = EPOLLIN, .data.u64 = http->max_conns+http->max_ws_conns };
379 0 : if( FD_UNLIKELY( -1==epoll_ctl( http->epoll_fd, EPOLL_CTL_ADD, sockfd, &ev ) ) ) FD_LOG_ERR(( "epoll_ctl(ADD) failed (%i-%s)", errno, fd_io_strerror( errno ) ));
380 :
381 0 : return http;
382 0 : }
383 :
384 : int
385 : fd_http_server_etag_matches( char const * if_none_match,
386 0 : char const * etag ) {
387 0 : ulong etag_len = strlen( etag );
388 0 : char const * p = if_none_match;
389 0 : while( *p==' ' || *p=='\t' ) p++;
390 0 : if( *p=='*' ) {
391 0 : p++;
392 0 : while( *p==' ' || *p=='\t' ) p++;
393 0 : return !*p;
394 0 : }
395 0 : int matched = 0;
396 0 : while( *p ) {
397 0 : while( *p==' ' || *p=='\t' || *p==',' ) p++;
398 0 : if( !*p ) break;
399 0 : if( p[ 0 ]=='W' && p[ 1 ]=='/' ) p += 2;
400 0 : if( FD_UNLIKELY( *p!='"' ) ) return 0;
401 0 : char const * end = strchr( p+1, '"' );
402 0 : if( FD_UNLIKELY( !end ) ) return 0;
403 0 : ulong len = (ulong)(end-p)+1UL;
404 0 : if( len==etag_len && !memcmp( p, etag, len ) ) matched = 1;
405 0 : p = end+1;
406 0 : while( *p==' ' || *p=='\t' ) p++;
407 0 : if( FD_UNLIKELY( *p && *p!=',' ) ) return 0;
408 0 : }
409 0 : return matched;
410 0 : }
411 :
412 : int
413 : fd_http_server_accept_encoding_q( char const * accept_encoding,
414 0 : char const * coding ) {
415 0 : ulong coding_len = strlen( coding );
416 0 : char const * p = accept_encoding;
417 0 : while( *p ) {
418 0 : while( *p==' ' || *p=='\t' || *p==',' ) p++;
419 0 : if( !*p ) break;
420 0 : char const * tok = p;
421 0 : while( *p && *p!=',' && *p!=';' && *p!=' ' && *p!='\t' ) p++;
422 0 : ulong tok_len = (ulong)(p-tok);
423 0 : char const * end = strchr( p, ',' );
424 0 : if( !end ) end = p+strlen( p );
425 0 : if( tok_len==coding_len && !strncasecmp( tok, coding, coding_len ) ) {
426 0 : char const * q = p;
427 0 : while( q<end ) { /* ;name=value parameters */
428 0 : if( *q++!=';' ) continue;
429 0 : while( q<end && (*q==' ' || *q=='\t') ) q++;
430 0 : if( end-q<2L || (*q!='q' && *q!='Q') || q[ 1 ]!='=' ) continue;
431 0 : q += 2;
432 : /* qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3"0" ] ) */
433 0 : int weight = 0;
434 0 : if( q<end && *q=='1' ) { weight = 1000; q++; }
435 0 : else if( q<end && *q=='0' ) q++;
436 0 : else return 0;
437 0 : if( q<end && *q=='.' ) for( int scale=100; ++q<end && *q>='0' && *q<='9' && scale; scale/=10 ) weight += (*q-'0')*scale;
438 0 : return fd_int_min( weight, 1000 );
439 0 : }
440 0 : return 1000;
441 0 : }
442 0 : p = end;
443 0 : }
444 0 : return 0;
445 0 : }
446 :
447 : static void
448 : close_conn( fd_http_server_t * http,
449 : ulong conn_idx,
450 0 : int reason ) {
451 0 : FD_TEST( http->pollfds[ conn_idx ].fd!=-1 );
452 : #if FD_HTTP_SERVER_DEBUG
453 : FD_LOG_NOTICE(( "Closing connection %lu (fd=%d) (%d-%s)", conn_idx, http->pollfds[ conn_idx ].fd, reason, fd_http_server_connection_close_reason_str( reason ) ));
454 : #endif
455 :
456 0 : if( FD_UNLIKELY( -1==close( http->pollfds[ conn_idx ].fd ) ) ) FD_LOG_ERR(( "close failed (%i-%s)", errno, strerror( errno ) ));
457 :
458 0 : http->pollfds[ conn_idx ].fd = -1;
459 0 : http->pollfds[ conn_idx ].events = POLLIN;
460 0 : if( FD_LIKELY( conn_idx<http->max_conns ) ) {
461 0 : if( FD_LIKELY( http->callbacks.close ) ) http->callbacks.close( conn_idx, reason, http->callback_ctx );
462 0 : } else {
463 0 : if( FD_LIKELY( http->callbacks.ws_close ) ) http->callbacks.ws_close( conn_idx-http->max_conns, reason, http->callback_ctx );
464 0 : }
465 :
466 0 : if( FD_UNLIKELY( conn_idx<http->max_conns ) ) {
467 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
468 0 : if( FD_LIKELY( (conn->state==FD_HTTP_SERVER_CONNECTION_STATE_WRITING_HEADER || conn->state==FD_HTTP_SERVER_CONNECTION_STATE_WRITING_BODY)
469 0 : && !conn->response.static_body && conn->response._body_len ) ) {
470 0 : conn_treap_ele_remove( http->conn_treap, conn, http->conns );
471 0 : }
472 0 : conn_pool_ele_release( http->conns, conn );
473 0 : } else {
474 0 : struct fd_http_server_ws_connection * ws_conn = &http->ws_conns[ conn_idx-http->max_conns ];
475 0 : if( FD_LIKELY( ws_conn->send_frame_cnt ) ) ws_conn_treap_ele_remove( http->ws_conn_treap, ws_conn, http->ws_conns );
476 0 : ws_conn_pool_ele_release( http->ws_conns, ws_conn );
477 0 : }
478 :
479 0 : if( FD_LIKELY( conn_idx<http->max_conns ) ) http->metrics.connection_cnt--;
480 0 : else http->metrics.ws_connection_cnt--;
481 0 : }
482 :
483 : static void
484 : epoll_conn_add( fd_http_server_t * http,
485 0 : ulong conn_idx ) {
486 0 : struct epoll_event ev = { .events = EPOLLIN, .data.u64 = conn_idx };
487 0 : if( FD_UNLIKELY( -1==epoll_ctl( http->epoll_fd, EPOLL_CTL_ADD, http->pollfds[ conn_idx ].fd, &ev ) ) )
488 0 : FD_LOG_ERR(( "epoll_ctl(ADD) failed (%i-%s)", errno, fd_io_strerror( errno ) ));
489 0 : http->pollfds[ conn_idx ].events = POLLIN;
490 0 : }
491 :
492 : static void
493 : epoll_conn_arm( fd_http_server_t * http,
494 : ulong conn_idx,
495 0 : short events ) {
496 0 : if( FD_UNLIKELY( -1==http->pollfds[ conn_idx ].fd ) ) return;
497 0 : if( FD_LIKELY( http->pollfds[ conn_idx ].events==events ) ) return;
498 0 : struct epoll_event ev = {
499 0 : .events = ((events & POLLIN) ? EPOLLIN : 0U) | ((events & POLLOUT) ? EPOLLOUT : 0U),
500 0 : .data.u64 = conn_idx,
501 0 : };
502 0 : if( FD_UNLIKELY( -1==epoll_ctl( http->epoll_fd, EPOLL_CTL_MOD, http->pollfds[ conn_idx ].fd, &ev ) ) )
503 0 : FD_LOG_ERR(( "epoll_ctl(MOD) failed (%i-%s)", errno, fd_io_strerror( errno ) ));
504 0 : http->pollfds[ conn_idx ].events = events;
505 0 : }
506 :
507 : static void
508 : epoll_conn_move( fd_http_server_t * http,
509 0 : ulong conn_idx ) {
510 0 : struct epoll_event ev = { .events = EPOLLIN, .data.u64 = conn_idx };
511 0 : if( FD_UNLIKELY( -1==epoll_ctl( http->epoll_fd, EPOLL_CTL_MOD, http->pollfds[ conn_idx ].fd, &ev ) ) )
512 0 : FD_LOG_ERR(( "epoll_ctl(MOD) failed (%i-%s)", errno, fd_io_strerror( errno ) ));
513 0 : http->pollfds[ conn_idx ].events = POLLIN;
514 0 : }
515 :
516 : static void
517 : epoll_update_out( fd_http_server_t * http,
518 0 : ulong conn_idx ) {
519 0 : if( FD_UNLIKELY( conn_idx>=http->max_conns+http->max_ws_conns ) ) return;
520 0 : if( FD_UNLIKELY( -1==http->pollfds[ conn_idx ].fd ) ) return;
521 :
522 0 : short events;
523 0 : if( FD_LIKELY( conn_idx<http->max_conns ) ) {
524 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
525 0 : if( FD_LIKELY( conn->state==FD_HTTP_SERVER_CONNECTION_STATE_READING ) ) events = POLLIN;
526 : /* While a response is being written, readable bytes are pipelined
527 : requests that cannot be serviced yet, except during a websocket
528 : upgrade, whose reads must keep surfacing an early close. */
529 0 : else events = (short)(POLLOUT | (conn->response.upgrade_websocket ? POLLIN : 0));
530 0 : } else {
531 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ conn_idx-http->max_conns ];
532 0 : int pending = conn->send_frame_cnt || conn->pong_state!=FD_HTTP_SERVER_PONG_STATE_NONE;
533 0 : events = (short)(pending ? (POLLIN|POLLOUT) : POLLIN);
534 0 : }
535 0 : epoll_conn_arm( http, conn_idx, events );
536 0 : }
537 :
538 : void
539 : fd_http_server_close( fd_http_server_t * http,
540 : ulong conn_id,
541 0 : int reason ) {
542 0 : close_conn( http, conn_id, reason );
543 0 : }
544 :
545 : void
546 : fd_http_server_ws_close( fd_http_server_t * http,
547 : ulong ws_conn_id,
548 0 : int reason ) {
549 0 : close_conn( http, http->max_conns+ws_conn_id, reason );
550 0 : }
551 :
552 : /* These are the expected network errors which just mean the connection
553 : should be closed. Any errors from an accept(2), read(2), or send(2)
554 : that are not expected here will be considered fatal and terminate the
555 : server. */
556 :
557 : static inline int
558 0 : is_expected_network_error( int err ) {
559 0 : return
560 0 : err==ENETDOWN ||
561 0 : err==EPROTO ||
562 0 : err==ENOPROTOOPT ||
563 0 : err==EHOSTDOWN ||
564 0 : err==ENONET ||
565 0 : err==EHOSTUNREACH ||
566 0 : err==EOPNOTSUPP ||
567 0 : err==ENETUNREACH ||
568 0 : err==ETIMEDOUT ||
569 0 : err==ENETRESET ||
570 0 : err==ECONNABORTED ||
571 0 : err==ECONNREFUSED || /* ICMP port unreachable */
572 0 : err==EACCES || /* ICMPv6 admin prohibited */
573 0 : err==ECONNRESET ||
574 0 : err==EPIPE ||
575 0 : err==EPERM || /* iptables */
576 0 : err==ENOMEM; /* net stack OOM */
577 0 : }
578 :
579 : static void
580 0 : accept_conns( fd_http_server_t * http ) {
581 0 : for(;;) {
582 0 : int fd = accept4( http->socket_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC );
583 :
584 0 : if( FD_UNLIKELY( -1==fd ) ) {
585 0 : if( FD_LIKELY( EAGAIN==errno ) ) break;
586 0 : else if( FD_LIKELY( is_expected_network_error( errno ) ) ) continue;
587 0 : else FD_LOG_ERR(( "accept failed (%i-%s)", errno, strerror( errno ) ));
588 0 : }
589 :
590 0 : if( FD_UNLIKELY( !conn_pool_free( http->conns ) ) ) {
591 0 : conn_treap_fwd_iter_t it = conn_treap_fwd_iter_init( http->conn_treap, http->conns );
592 0 : if( FD_LIKELY( !conn_treap_fwd_iter_done( it ) ) ) {
593 0 : ulong conn_id = conn_treap_fwd_iter_idx( it );
594 0 : close_conn( http, conn_id, FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
595 0 : } else {
596 : /* If nobody is slow to read, just evict round robin */
597 0 : close_conn( http, http->evict_conn_id, FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
598 0 : http->evict_conn_id = (http->evict_conn_id+1UL) % http->max_conns;
599 0 : }
600 0 : }
601 :
602 0 : ulong conn_id = conn_pool_idx_acquire( http->conns );
603 :
604 0 : http->pollfds[ conn_id ].fd = fd;
605 0 : http->pollfds[ conn_id ].events = POLLIN;
606 0 : epoll_conn_add( http, conn_id );
607 0 : http->conns[ conn_id ].state = FD_HTTP_SERVER_CONNECTION_STATE_READING;
608 0 : http->conns[ conn_id ].request_bytes_read = 0UL;
609 0 : http->conns[ conn_id ].request_bytes_off = 0UL;
610 0 : http->conns[ conn_id ].request_expected_len = 0UL;
611 0 : http->conns[ conn_id ].response_bytes_written = 0UL;
612 :
613 0 : if( FD_UNLIKELY( http->callbacks.open ) ) {
614 0 : http->callbacks.open( conn_id, fd, http->callback_ctx );
615 0 : }
616 :
617 0 : http->metrics.connection_cnt++;
618 : #if FD_HTTP_SERVER_DEBUG
619 : FD_LOG_NOTICE(( "Accepted connection %lu (fd=%d)", conn_id, fd ));
620 : #endif
621 0 : }
622 0 : }
623 :
624 : /* last_len is the request length at the previous parse that returned
625 : incomplete, or 0: picohttpparser then only scans the new bytes for
626 : the end of the headers (its slowloris countermeasure). */
627 :
628 : static void
629 : parse_conn_http( fd_http_server_t * http,
630 : ulong conn_idx,
631 0 : ulong last_len ) {
632 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
633 :
634 0 : char const * method;
635 0 : ulong method_len;
636 0 : char const * path;
637 0 : ulong path_len;
638 0 : int minor_version;
639 0 : struct phr_header headers[ 32 ];
640 0 : ulong num_headers = 32UL;
641 0 : int result = phr_parse_request( conn->request_bytes+conn->request_bytes_off,
642 0 : conn->request_bytes_read-conn->request_bytes_off,
643 0 : &method, &method_len,
644 0 : &path, &path_len,
645 0 : &minor_version,
646 0 : headers, &num_headers,
647 0 : last_len );
648 0 : if( FD_UNLIKELY( -2==result ) ) return; /* Request still partial, wait for more data */
649 0 : else if( FD_UNLIKELY( -1==result ) ) {
650 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
651 0 : return;
652 0 : }
653 :
654 0 : FD_TEST( result>0 && (ulong)result<=conn->request_bytes_read-conn->request_bytes_off );
655 :
656 0 : uchar method_enum = UCHAR_MAX;
657 0 : if( FD_LIKELY( method_len==3UL && !strncmp( method, "GET", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_GET;
658 0 : else if( FD_LIKELY( method_len==4UL && !strncmp( method, "POST", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_POST;
659 0 : else if( FD_LIKELY( method_len==7UL && !strncmp( method, "OPTIONS", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_OPTIONS;
660 0 : else if( FD_LIKELY( method_len==3UL && !strncmp( method, "PUT", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_PUT;
661 0 : else if( FD_LIKELY( method_len==4UL && !strncmp( method, "HEAD", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_HEAD;
662 :
663 0 : if( FD_UNLIKELY( method_enum==UCHAR_MAX ) ) {
664 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_UNKNOWN_METHOD );
665 0 : return;
666 0 : }
667 :
668 : /* RFC 7230 s3.3.3 */
669 0 : for( ulong i=0UL; i<num_headers; i++ ) {
670 0 : if( FD_UNLIKELY( headers[ i ].name_len==17UL && !strncasecmp( headers[ i ].name, "Transfer-Encoding", 17UL ) ) ) {
671 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_UNSUPPORTED_TRANSFER_ENCODING );
672 0 : return;
673 0 : }
674 0 : }
675 :
676 0 : ulong content_len = 0UL;
677 0 : int found = 0;
678 0 : for( ulong i=0UL; i<num_headers; i++ ) {
679 0 : if( FD_LIKELY( headers[ i ].name_len==14UL && !strncasecmp( headers[ i ].name, "Content-Length", 14UL ) ) ) {
680 0 : ulong this_content_len = 0UL;
681 0 : int parse_err = fd_http_parse_content_len( headers[ i ].value, (ulong)headers[ i ].value_len, &this_content_len );
682 0 : if( FD_UNLIKELY( parse_err ) ) {
683 0 : close_conn( http, conn_idx, fd_int_if( parse_err==FD_HTTP_PARSE_CONTENT_LEN_OVERFLOW, FD_HTTP_SERVER_CONNECTION_CLOSE_LARGE_REQUEST, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST ) );
684 0 : return;
685 0 : }
686 0 : if( FD_UNLIKELY( found && this_content_len!=content_len ) ) {
687 : /* RFC 7230 s3.3.3 rule 4: reject if duplicate Content-Length
688 : values differ */
689 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
690 0 : return;
691 0 : }
692 0 : content_len = this_content_len;
693 0 : found = 1;
694 0 : }
695 0 : }
696 :
697 0 : if( FD_UNLIKELY( !found && (method_enum==FD_HTTP_SERVER_METHOD_POST || method_enum==FD_HTTP_SERVER_METHOD_PUT) ) ) {
698 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_MISSING_CONTENT_LENGTH_HEADER );
699 0 : return;
700 0 : }
701 :
702 0 : ulong total_len = (ulong)result+content_len;
703 :
704 0 : if( FD_UNLIKELY( total_len<content_len || total_len>http->max_request_len ) ) { /* Overflow */
705 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_LARGE_REQUEST );
706 0 : return;
707 0 : }
708 :
709 :
710 0 : if( FD_UNLIKELY( conn->request_bytes_read-conn->request_bytes_off<(ulong)result+content_len ) ) {
711 0 : conn->request_expected_len = (ulong)result+content_len; /* body pending, no need to reparse until it is all here */
712 0 : return;
713 0 : }
714 :
715 0 : char content_type_nul_terminated[ 128 ] = {0};
716 0 : char accept_encoding_nul_terminated[ 128 ] = {0};
717 0 : ulong accept_encoding_len = 0UL;
718 0 : for( ulong i=0UL; i<num_headers; i++ ) {
719 0 : if( FD_LIKELY( headers[ i ].name_len==12UL && !strncasecmp( headers[ i ].name, "Content-Type", 12UL ) ) ) {
720 0 : if( FD_UNLIKELY( headers[ i ].value_len>(sizeof(content_type_nul_terminated)-1UL) ) ) {
721 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
722 0 : return;
723 0 : }
724 0 : memcpy( content_type_nul_terminated, headers[ i ].value, headers[ i ].value_len );
725 0 : content_type_nul_terminated[ headers[ i ].value_len ] = '\0';
726 0 : } else if( FD_LIKELY( headers[ i ].name_len==15UL && !strncasecmp( headers[ i ].name, "Accept-Encoding", 15UL ) ) ) {
727 : /* repeated list fields combine (RFC 9110 s5.3) */
728 0 : ulong sep_len = accept_encoding_len ? 2UL : 0UL;
729 0 : if( FD_UNLIKELY( accept_encoding_len+sep_len+headers[ i ].value_len>sizeof(accept_encoding_nul_terminated)-1UL ) ) {
730 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
731 0 : return;
732 0 : }
733 0 : if( FD_LIKELY( sep_len ) ) { memcpy( accept_encoding_nul_terminated+accept_encoding_len, ", ", 2UL ); accept_encoding_len += 2UL; }
734 0 : memcpy( accept_encoding_nul_terminated+accept_encoding_len, headers[ i ].value, headers[ i ].value_len );
735 0 : accept_encoding_len += headers[ i ].value_len;
736 0 : }
737 0 : }
738 :
739 0 : char if_none_match_nul_terminated[ 128 ] = {0};
740 0 : ulong if_none_match_len = 0UL;
741 0 : for( ulong i=0UL; i<num_headers; i++ ) {
742 0 : if( FD_UNLIKELY( headers[ i ].name_len==13UL && !strncasecmp( headers[ i ].name, "If-None-Match", 13UL ) ) ) {
743 0 : ulong sep_len = if_none_match_len ? 2UL : 0UL;
744 0 : if( FD_UNLIKELY( if_none_match_len+sep_len+headers[ i ].value_len>sizeof(if_none_match_nul_terminated)-1UL ) ) {
745 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
746 0 : return;
747 0 : }
748 0 : if( FD_LIKELY( sep_len ) ) { memcpy( if_none_match_nul_terminated+if_none_match_len, ", ", 2UL ); if_none_match_len += 2UL; }
749 0 : memcpy( if_none_match_nul_terminated+if_none_match_len, headers[ i ].value, headers[ i ].value_len );
750 0 : if_none_match_len += headers[ i ].value_len;
751 0 : }
752 0 : }
753 :
754 0 : char path_nul_terminated[ 128 ] = {0};
755 0 : if( FD_UNLIKELY( path_len>(sizeof( path_nul_terminated )-1UL) ) ) {
756 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PATH_TOO_LONG );
757 0 : return;
758 0 : }
759 0 : memcpy( path_nul_terminated, path, path_len );
760 :
761 0 : char const * upgrade_key = NULL;
762 0 : for( ulong i=0UL; i<num_headers; i++ ) {
763 0 : if( FD_LIKELY( headers[ i ].name_len==7UL && !strncasecmp( headers[ i ].name, "Upgrade", 7UL ) && headers[ i ].value_len==9UL ) ) {
764 0 : upgrade_key = headers[ i ].value;
765 0 : break;
766 0 : }
767 0 : }
768 :
769 0 : conn->upgrade_websocket = 0;
770 0 : int compress_websocket = 0;
771 0 : if( FD_UNLIKELY( upgrade_key && !strncasecmp( upgrade_key, "websocket", 9UL ) ) ) {
772 0 : conn->request_bytes_len = conn->request_bytes_off+(ulong)result;
773 0 : conn->upgrade_websocket = 1;
774 :
775 0 : for( ulong i=0UL; i<num_headers; i++ ) {
776 0 : if( FD_LIKELY( headers[ i ].name_len==22UL && !strncasecmp( headers[ i ].name, "Sec-WebSocket-Protocol", 22UL ) &&
777 0 : headers[ i ].value_len==13UL && !strncmp( headers[ i ].value, "compress-zstd", 13UL ) ) ) {
778 0 : compress_websocket = 1;
779 0 : }
780 0 : }
781 :
782 0 : char const * sec_websocket_key = NULL;
783 0 : for( ulong i=0UL; i<num_headers; i++ ) {
784 0 : if( FD_LIKELY( headers[ i ].name_len==17UL && !strncasecmp( headers[ i ].name, "Sec-WebSocket-Key", 17UL ) ) ) {
785 0 : sec_websocket_key = headers[ i ].value;
786 0 : if( FD_UNLIKELY( headers[ i ].value_len!=24 ) ) {
787 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_KEY );
788 0 : return;
789 0 : }
790 : /* RFC 6455 s4.2.1: Sec-WebSocket-Key must base64-decode to
791 : exactly 16 bytes. fd_base64_decode also validates the
792 : alphabet and padding rules. */
793 0 : uchar decoded_key[ FD_BASE64_DEC_SZ( 24UL ) ];
794 0 : if( FD_UNLIKELY( 16L!=fd_base64_decode( decoded_key, sec_websocket_key, 24UL ) ) ) {
795 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_KEY );
796 0 : return;
797 0 : }
798 0 : break;
799 0 : }
800 0 : }
801 :
802 0 : char const * sec_websocket_version = NULL;
803 0 : for( ulong i=0UL; i<num_headers; i++ ) {
804 0 : if( FD_LIKELY( headers[ i ].name_len==21UL && !strncasecmp( headers[ i ].name, "Sec-Websocket-Version", 21UL ) ) ) {
805 0 : sec_websocket_version = headers[ i ].value;
806 0 : if( FD_UNLIKELY( headers[ i ].value_len!=2 || strncmp( sec_websocket_version, "13", 2UL ) ) ) {
807 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_UNEXPECTED_VERSION );
808 0 : return;
809 0 : }
810 0 : break;
811 0 : }
812 0 : }
813 :
814 0 : if( FD_UNLIKELY( !sec_websocket_key ) ) {
815 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_KEY_HEADER );
816 0 : return;
817 0 : }
818 :
819 0 : if( FD_UNLIKELY( !sec_websocket_version ) ) {
820 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_VERSION_HEADER );
821 0 : return;
822 0 : }
823 :
824 0 : conn->sec_websocket_key = sec_websocket_key;
825 :
826 : /* RFC 6455 s4.2.2: the client must not send WebSocket frames until
827 : after it receives the 101 response. */
828 0 : if( FD_UNLIKELY( conn->request_bytes_read>conn->request_bytes_len ) ) {
829 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
830 0 : return;
831 0 : }
832 0 : }
833 :
834 0 : int connection_close = 0;
835 0 : for( ulong i=0UL; i<num_headers; i++ ) {
836 0 : if( FD_UNLIKELY( headers[ i ].name_len==10UL && !strncasecmp( headers[ i ].name, "Connection", 10UL ) ) ) {
837 0 : char const * value = headers[ i ].value;
838 0 : ulong j = 0UL;
839 0 : while( j<headers[ i ].value_len ) {
840 0 : while( j<headers[ i ].value_len && (value[ j ]==',' || value[ j ]==' ' || value[ j ]=='\t') ) j++;
841 0 : ulong k = j;
842 0 : while( k<headers[ i ].value_len && value[ k ]!=',' && value[ k ]!=' ' && value[ k ]!='\t' ) k++;
843 0 : if( FD_UNLIKELY( k-j==5UL && !strncasecmp( value+j, "close", 5UL ) ) ) { connection_close = 1; break; }
844 0 : j = k;
845 0 : }
846 0 : }
847 0 : }
848 :
849 0 : conn->keep_alive = minor_version==1 && !connection_close && !conn->upgrade_websocket;
850 0 : conn->is_head_request = method_enum==FD_HTTP_SERVER_METHOD_HEAD;
851 0 : conn->request_consumed = conn->request_bytes_off+(ulong)result+content_len;
852 0 : conn->request_expected_len = 0UL;
853 :
854 0 : fd_http_server_request_t request = {
855 0 : .connection_id = conn_idx,
856 :
857 0 : .method = method_enum,
858 0 : .path = path_nul_terminated,
859 0 : .path_raw = path,
860 0 : .path_len = path_len,
861 :
862 0 : .ctx = http->callback_ctx,
863 :
864 0 : .headers.content_type = content_type_nul_terminated,
865 0 : .headers.accept_encoding = accept_encoding_nul_terminated,
866 0 : .headers.if_none_match = if_none_match_nul_terminated,
867 0 : .headers.compress_websocket = compress_websocket,
868 0 : .headers.upgrade_websocket = conn->upgrade_websocket,
869 0 : };
870 :
871 0 : switch( method_enum ) {
872 0 : case FD_HTTP_SERVER_METHOD_POST:
873 0 : case FD_HTTP_SERVER_METHOD_PUT: {
874 0 : request.post.body = (uchar*)conn->request_bytes+conn->request_bytes_off+result;
875 0 : request.post.body_len = content_len;
876 0 : } break;
877 0 : default: break;
878 0 : }
879 :
880 0 : fd_http_server_response_t response = http->callbacks.request( &request );
881 0 : if( FD_UNLIKELY( http->pollfds[ conn_idx ].fd==-1 ) ) return; /* Connection was closed by callback */
882 0 : conn->response = response;
883 0 : conn->state = FD_HTTP_SERVER_CONNECTION_STATE_WRITING_HEADER;
884 :
885 0 : switch( conn->response.status ) {
886 0 : case 200: case 204: case 400: break;
887 0 : default:
888 0 : conn->response.static_body_len = 0UL;
889 0 : conn->response._body_len = 0UL;
890 0 : break;
891 0 : }
892 :
893 : #if FD_HTTP_SERVER_DEBUG
894 : FD_LOG_NOTICE(( "Received %s request \"%s\" from %lu (fd=%d) response code %lu", fd_http_server_method_str( method_enum ), path_nul_terminated, conn_idx, http->pollfds[ conn_idx ].fd, conn->response.status ));
895 : #endif
896 :
897 0 : if( FD_LIKELY( !conn->response.static_body && conn->response._body_len ) ) conn_treap_ele_insert( http->conn_treap, conn, http->conns );
898 0 : }
899 :
900 : static void
901 : read_conn_http( fd_http_server_t * http,
902 0 : ulong conn_idx ) {
903 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
904 :
905 0 : if( FD_UNLIKELY( conn->state!=FD_HTTP_SERVER_CONNECTION_STATE_READING ) ) {
906 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_EXPECTED_EOF );
907 0 : return;
908 0 : }
909 :
910 0 : if( FD_UNLIKELY( conn->request_bytes_off ) ) {
911 0 : memmove( conn->request_bytes, conn->request_bytes+conn->request_bytes_off, conn->request_bytes_read-conn->request_bytes_off );
912 0 : conn->request_bytes_read -= conn->request_bytes_off;
913 0 : conn->request_bytes_off = 0UL;
914 0 : }
915 :
916 0 : long sz = read( http->pollfds[ conn_idx ].fd, conn->request_bytes+conn->request_bytes_read, http->max_request_len-conn->request_bytes_read );
917 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data to read, continue. */
918 0 : else if( FD_UNLIKELY( !sz || (-1==sz && is_expected_network_error( errno ) ) ) ) {
919 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
920 0 : return;
921 0 : }
922 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "read failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
923 :
924 : /* New data was read... process it */
925 0 : http->metrics.bytes_read += (ulong)sz;
926 0 : conn->request_bytes_read += (ulong)sz;
927 :
928 : /* Once the headers parsed, a non-zero last_len would make
929 : picohttpparser scan the body for their terminator and never finish */
930 0 : if( conn->request_expected_len ) {
931 0 : if( conn->request_bytes_read<conn->request_expected_len ) return;
932 0 : parse_conn_http( http, conn_idx, 0UL );
933 0 : } else {
934 0 : parse_conn_http( http, conn_idx, conn->request_bytes_read-(ulong)sz );
935 0 : }
936 :
937 : /* A full buffer may hold multiple valid pipelined requests, so it is
938 : only oversized if parsing left it full and still incomplete */
939 0 : if( FD_UNLIKELY( http->pollfds[ conn_idx ].fd!=-1 &&
940 0 : conn->state==FD_HTTP_SERVER_CONNECTION_STATE_READING &&
941 0 : conn->request_bytes_read==http->max_request_len ) ) {
942 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_LARGE_REQUEST );
943 0 : }
944 0 : }
945 :
946 : static void
947 : read_conn_ws( fd_http_server_t * http,
948 0 : ulong conn_idx ) {
949 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ conn_idx-http->max_conns ];
950 :
951 0 : long sz = read( http->pollfds[ conn_idx ].fd, conn->recv_bytes+conn->recv_bytes_parsed+conn->recv_bytes_read, http->max_ws_recv_frame_len-conn->recv_bytes_parsed-conn->recv_bytes_read );
952 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data to read, continue. */
953 0 : else if( FD_UNLIKELY( !sz || (-1==sz && is_expected_network_error( errno ) ) ) ) {
954 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
955 0 : return;
956 0 : }
957 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "read failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
958 :
959 : /* New data was read... process it */
960 0 : conn->recv_bytes_read += (ulong)sz;
961 0 : http->metrics.bytes_read += (ulong)sz;
962 0 : again:
963 0 : if( FD_UNLIKELY( conn->recv_bytes_read<2UL ) ) return; /* Need at least 2 bytes to determine frame length */
964 :
965 0 : int is_mask_set = conn->recv_bytes[ conn->recv_bytes_parsed+1UL ] & 0x80;
966 0 : if( FD_UNLIKELY( !is_mask_set ) ) {
967 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_MASK );
968 0 : return;
969 0 : }
970 :
971 0 : int opcode = conn->recv_bytes[ conn->recv_bytes_parsed ] & 0x0F;
972 0 : if( FD_UNLIKELY( opcode!=0x0 && opcode!=0x1 && opcode!=0x2 && opcode!=0x8 && opcode!=0x9 && opcode!=0xA ) ) {
973 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_UNKNOWN_OPCODE );
974 0 : return;
975 0 : }
976 :
977 0 : ulong payload_len = conn->recv_bytes[ conn->recv_bytes_parsed+1UL ] & 0x7F;
978 0 : if( FD_UNLIKELY( (payload_len==126 || payload_len==127) && (opcode==0x8 || opcode==0x9 || opcode==0xA) ) ) {
979 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CONTROL_FRAME_TOO_LARGE );
980 0 : return;
981 0 : }
982 :
983 0 : ulong len_bytes;
984 0 : if( FD_LIKELY( payload_len<126UL ) ) {
985 0 : len_bytes = 1UL;
986 0 : } else if( FD_LIKELY( payload_len==126 ) ) {
987 0 : if( FD_UNLIKELY( conn->recv_bytes_read<4UL ) ) return; /* Need at least 4 bytes to determine frame length */
988 0 : payload_len = ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+2UL ]<<8UL) | (ulong)conn->recv_bytes[ conn->recv_bytes_parsed+3UL ];
989 0 : len_bytes = 3UL;
990 0 : } else if( FD_LIKELY( payload_len==127 ) ) {
991 0 : if( FD_UNLIKELY( conn->recv_bytes_read<10UL ) ) return; /* Need at least 10 bytes to determine frame length */
992 0 : payload_len = ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+2UL ]<<56UL) | ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+3UL ]<<48UL) | ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+4UL ]<<40UL) | ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+5UL ]<<32UL) |
993 0 : ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+6UL ]<<24UL) | ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+7UL ]<<16UL) | ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+8UL ]<<8UL ) | (ulong)conn->recv_bytes[ conn->recv_bytes_parsed+9UL ];
994 0 : len_bytes = 9UL;
995 0 : } else {
996 0 : FD_LOG_ERR(( "unexpected payload_len %lu", payload_len )); /* Silence clang sanitizer, not possible */
997 0 : }
998 :
999 0 : ulong header_len = 1UL+len_bytes+4UL;
1000 0 : ulong frame_len = header_len+payload_len;
1001 0 : if( FD_UNLIKELY( frame_len<header_len ) ) { /* Overflow */
1002 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_OVERSIZE_FRAME );
1003 0 : return;
1004 0 : }
1005 :
1006 0 : if( FD_UNLIKELY( conn->recv_bytes_parsed+frame_len+1UL>http->max_ws_recv_frame_len ) ) {
1007 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_OVERSIZE_FRAME );
1008 0 : return;
1009 0 : }
1010 :
1011 0 : if( FD_UNLIKELY( conn->recv_bytes_read<frame_len ) ) return; /* Need more data to read the full frame */
1012 :
1013 : /* Data frame, process it */
1014 :
1015 0 : int is_fin_set = conn->recv_bytes[ conn->recv_bytes_parsed+0UL ] & 0x80;
1016 :
1017 0 : uchar * mask = conn->recv_bytes+conn->recv_bytes_parsed+1UL+len_bytes;
1018 0 : uchar mask_copy[ 4 ] = { mask[ 0 ], mask[ 1 ], mask[ 2 ], mask[ 3 ] }; /* Bytes will be overwritten by the memmove below */
1019 :
1020 0 : uchar * payload = conn->recv_bytes+conn->recv_bytes_parsed+header_len;
1021 0 : for( ulong i=0UL; i<payload_len; i++ ) conn->recv_bytes[ conn->recv_bytes_parsed+i ] = payload[ i ] ^ mask_copy[ i % 4 ];
1022 :
1023 0 : http->metrics.frames_read++;
1024 :
1025 : /* Frame is complete, process it */
1026 :
1027 0 : if( FD_UNLIKELY( opcode==0x8 ) ) {
1028 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
1029 0 : return;
1030 0 : } else if( FD_UNLIKELY( opcode==0x9 ) ) {
1031 : /* Ping frame, queue pong unless we are already sending one */
1032 0 : uchar * trailing_data = conn->recv_bytes+conn->recv_bytes_parsed+frame_len;
1033 0 : ulong trailing_data_len = conn->recv_bytes_read-frame_len;
1034 0 : if( FD_LIKELY( conn->pong_state==FD_HTTP_SERVER_PONG_STATE_NONE ) ) {
1035 0 : conn->pong_state = FD_HTTP_SERVER_PONG_STATE_WAITING;
1036 0 : conn->pong_data_len = payload_len;
1037 0 : FD_TEST( payload_len<=125UL );
1038 0 : memcpy( conn->pong_data, conn->recv_bytes+conn->recv_bytes_parsed, payload_len );
1039 0 : }
1040 0 : conn->recv_bytes_read = trailing_data_len;
1041 0 : if( FD_UNLIKELY( trailing_data_len ) ) {
1042 0 : memmove( conn->recv_bytes+conn->recv_bytes_parsed, trailing_data, trailing_data_len );
1043 0 : goto again; /* Might be another frame in the buffer to process */
1044 0 : }
1045 0 : return;
1046 0 : } else if( FD_UNLIKELY( opcode==0xA ) ) {
1047 : /* Pong frame, ignore */
1048 0 : uchar * trailing_data = conn->recv_bytes+conn->recv_bytes_parsed+frame_len;
1049 0 : ulong trailing_data_len = conn->recv_bytes_read-frame_len;
1050 0 : conn->recv_bytes_read = trailing_data_len;
1051 0 : if( FD_UNLIKELY( trailing_data_len ) ) {
1052 0 : memmove( conn->recv_bytes+conn->recv_bytes_parsed, trailing_data, trailing_data_len );
1053 0 : goto again; /* Might be another frame in the buffer to process */
1054 0 : }
1055 0 : return;
1056 0 : }
1057 :
1058 0 : if( FD_UNLIKELY( conn->recv_started_msg ) ) {
1059 0 : if( FD_UNLIKELY( opcode!=0x0 ) ) {
1060 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_EXPECTED_CONT_OPCODE );
1061 0 : return;
1062 0 : }
1063 0 : } else {
1064 0 : if( FD_UNLIKELY( opcode!=0x1 && opcode!=0x2 ) ) {
1065 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_EXPECTED_TEXT_OPCODE );
1066 0 : return;
1067 0 : }
1068 0 : }
1069 :
1070 : /* Check if this is a complete message */
1071 :
1072 0 : if( FD_UNLIKELY( !is_fin_set ) ) {
1073 0 : uchar * trailing_data = conn->recv_bytes+conn->recv_bytes_parsed+frame_len;
1074 0 : ulong trailing_data_len = conn->recv_bytes_read-frame_len;
1075 0 : conn->recv_started_msg = 1;
1076 0 : conn->recv_bytes_parsed += payload_len;
1077 0 : conn->recv_bytes_read = trailing_data_len;
1078 0 : if( FD_UNLIKELY( trailing_data_len ) ) {
1079 0 : memmove( conn->recv_bytes+conn->recv_bytes_parsed, trailing_data, trailing_data_len );
1080 0 : goto again; /* Might be another frame in the buffer to process */
1081 0 : }
1082 0 : return; /* Not a complete message yet */
1083 0 : }
1084 :
1085 : /* Complete message, process it */
1086 :
1087 0 : uchar * trailing_data = conn->recv_bytes+conn->recv_bytes_parsed+frame_len;
1088 0 : ulong trailing_data_len = conn->recv_bytes_read-frame_len;
1089 :
1090 0 : conn->recv_bytes_parsed += payload_len;
1091 0 : conn->recv_bytes_read -= frame_len;
1092 :
1093 0 : uchar tmp = conn->recv_bytes[ conn->recv_bytes_parsed ];
1094 0 : conn->recv_bytes[ conn->recv_bytes_parsed ] = 0; /* NUL terminate */
1095 0 : http->callbacks.ws_message( conn_idx-http->max_conns, conn->recv_bytes, conn->recv_bytes_parsed, http->callback_ctx );
1096 0 : if( FD_UNLIKELY( -1==http->pollfds[ conn_idx ].fd ) ) return; /* Connection was closed by callback */
1097 0 : conn->recv_bytes[ conn->recv_bytes_parsed ] = tmp;
1098 :
1099 0 : conn->recv_started_msg = 0;
1100 0 : conn->recv_bytes_parsed = 0UL;
1101 0 : if( FD_UNLIKELY( trailing_data_len ) ) {
1102 0 : memmove( conn->recv_bytes, trailing_data, trailing_data_len );
1103 0 : goto again; /* Might be another message in the buffer to process */
1104 0 : }
1105 0 : }
1106 :
1107 : static void
1108 : read_conn( fd_http_server_t * http,
1109 0 : ulong conn_idx ) {
1110 0 : if( FD_LIKELY( conn_idx<http->max_conns ) ) read_conn_http( http, conn_idx );
1111 0 : else read_conn_ws( http, conn_idx );
1112 0 : }
1113 :
1114 : static void
1115 : write_conn_http( fd_http_server_t * http,
1116 0 : ulong conn_idx ) {
1117 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
1118 :
1119 0 : char header_buf[ 2048 ];
1120 :
1121 0 : uchar const * response;
1122 0 : ulong response_len;
1123 0 : switch( conn->state ) {
1124 0 : case FD_HTTP_SERVER_CONNECTION_STATE_READING:
1125 0 : return; /* No data staged for write yet. */
1126 0 : case FD_HTTP_SERVER_CONNECTION_STATE_WRITING_HEADER:
1127 0 : switch( conn->response.status ) {
1128 0 : case 200:
1129 0 : if( FD_UNLIKELY( conn->response.upgrade_websocket ) ) {
1130 0 : if( FD_UNLIKELY( !conn->upgrade_websocket ) ) {
1131 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_UPGRADE );
1132 0 : return;
1133 0 : }
1134 :
1135 0 : uchar sec_websocket_key[ 60 ];
1136 0 : fd_memcpy( sec_websocket_key, conn->sec_websocket_key, 24 );
1137 0 : fd_memcpy( sec_websocket_key+24, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", 36 );
1138 :
1139 0 : uchar sec_websocket_accept[ 20 ];
1140 0 : fd_sha1_hash( sec_websocket_key, 60, sec_websocket_accept );
1141 0 : char sec_websocket_accept_base64[ FD_BASE64_ENC_SZ( 20 ) ];
1142 0 : ulong encoded_len = fd_base64_encode( sec_websocket_accept_base64, sec_websocket_accept, 20 );
1143 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %.*s\r\n", (int)encoded_len, sec_websocket_accept_base64 ) );
1144 0 : } else {
1145 0 : ulong body_len = conn->response.static_body ? conn->response.static_body_len : conn->response._body_len;
1146 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\n", body_len ) );
1147 0 : }
1148 0 : break;
1149 0 : case 204: {
1150 0 : ulong body_len = conn->response.static_body ? conn->response.static_body_len : conn->response._body_len;
1151 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 204 No Content\r\nContent-Length: %lu\r\n", body_len ) );
1152 0 : break;
1153 0 : }
1154 0 : case 302:
1155 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 302 Found\r\nContent-Length: 0\r\n" ) );
1156 0 : break;
1157 0 : case 304:
1158 : /* RFC 9110 s15.4.5: no body, no Content-Length */
1159 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 304 Not Modified\r\n" ) );
1160 0 : break;
1161 0 : case 400: {
1162 0 : ulong body_len = conn->response.static_body ? conn->response.static_body_len : conn->response._body_len;
1163 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 400 Bad Request\r\nContent-Length: %lu\r\n", body_len ) );
1164 0 : break;
1165 0 : }
1166 0 : case 403:
1167 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n" ) );
1168 0 : break;
1169 0 : case 404:
1170 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n" ) );
1171 0 : break;
1172 0 : case 405:
1173 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n" ) );
1174 0 : break;
1175 0 : case 500:
1176 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n" ) );
1177 0 : break;
1178 0 : case 501:
1179 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 501 Not Implemented\r\nContent-Length: 0\r\n" ) );
1180 0 : break;
1181 0 : default:
1182 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n" ) );
1183 0 : break;
1184 0 : }
1185 :
1186 0 : if( FD_LIKELY( conn->response.compress_websocket ) ) {
1187 0 : ulong compress_websocket_len;
1188 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &compress_websocket_len, "Sec-WebSocket-Protocol: compress-zstd\r\n" ) );
1189 0 : response_len += compress_websocket_len;
1190 0 : }
1191 0 : if( FD_LIKELY( conn->response.content_type ) ) {
1192 0 : ulong content_type_len;
1193 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &content_type_len, "Content-Type: %s\r\n", conn->response.content_type ) );
1194 0 : response_len += content_type_len;
1195 0 : }
1196 0 : if( FD_LIKELY( conn->response.cache_control ) ) {
1197 0 : ulong cache_control_len;
1198 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &cache_control_len, "Cache-Control: %s\r\n", conn->response.cache_control ) );
1199 0 : response_len += cache_control_len;
1200 0 : }
1201 0 : if( FD_LIKELY( conn->response.link ) ) {
1202 0 : ulong link_len;
1203 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &link_len, "Link: %s\r\n", conn->response.link ) );
1204 0 : response_len += link_len;
1205 0 : }
1206 0 : if( FD_LIKELY( conn->response.content_encoding ) ) {
1207 0 : ulong content_encoding_len;
1208 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &content_encoding_len, "Content-Encoding: %s\r\n", conn->response.content_encoding ) );
1209 0 : response_len += content_encoding_len;
1210 0 : }
1211 0 : if( FD_LIKELY( conn->response.vary ) ) {
1212 0 : ulong vary_len;
1213 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &vary_len, "Vary: %s\r\n", conn->response.vary ) );
1214 0 : response_len += vary_len;
1215 0 : }
1216 0 : if( FD_LIKELY( conn->response.location[ 0 ] ) ) {
1217 0 : ulong location_len;
1218 0 : FD_TEST( conn->response.location_len[0]<=(ulong)INT_MAX );
1219 0 : FD_TEST( conn->response.location_len[1]<=(ulong)INT_MAX );
1220 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &location_len,
1221 0 : "Location: %.*s%.*s\r\n",
1222 0 : (int)conn->response.location_len[0],
1223 0 : conn->response.location[0],
1224 0 : (int)conn->response.location_len[1],
1225 0 : conn->response.location[1] ? conn->response.location[1] : "" ) );
1226 0 : response_len += location_len;
1227 0 : }
1228 0 : if( FD_LIKELY( conn->response.access_control_allow_origin ) ) {
1229 0 : ulong access_control_allow_origin_len;
1230 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &access_control_allow_origin_len, "Access-Control-Allow-Origin: %s\r\n", conn->response.access_control_allow_origin ) );
1231 0 : response_len += access_control_allow_origin_len;
1232 0 : }
1233 0 : if( FD_LIKELY( conn->response.access_control_allow_methods ) ) {
1234 0 : ulong access_control_allow_methods_len;
1235 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &access_control_allow_methods_len, "Access-Control-Allow-Methods: %s\r\n", conn->response.access_control_allow_methods ) );
1236 0 : response_len += access_control_allow_methods_len;
1237 0 : }
1238 0 : if( FD_LIKELY( conn->response.access_control_allow_headers ) ) {
1239 0 : ulong access_control_allow_headers_len;
1240 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &access_control_allow_headers_len, "Access-Control-Allow-Headers: %s\r\n", conn->response.access_control_allow_headers ) );
1241 0 : response_len += access_control_allow_headers_len;
1242 0 : }
1243 0 : if( FD_LIKELY( !conn->response.upgrade_websocket ) ) {
1244 0 : ulong connection_len;
1245 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &connection_len, "Connection: %s\r\n", conn->keep_alive ? "keep-alive" : "close" ) );
1246 0 : response_len += connection_len;
1247 0 : }
1248 0 : if( FD_LIKELY( conn->response.etag ) ) {
1249 0 : ulong etag_len;
1250 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &etag_len, "ETag: %s\r\n", conn->response.etag ) );
1251 0 : response_len += etag_len;
1252 0 : }
1253 0 : if( FD_LIKELY( conn->response.access_control_max_age ) ) {
1254 0 : ulong access_control_max_age_len;
1255 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, &access_control_max_age_len, "Access-Control-Max-Age: %lu\r\n", conn->response.access_control_max_age ) );
1256 0 : response_len += access_control_max_age_len;
1257 0 : }
1258 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, NULL, "\r\n" ) );
1259 0 : response_len += 2UL;
1260 :
1261 0 : response = (uchar const *)header_buf;
1262 0 : break;
1263 0 : case FD_HTTP_SERVER_CONNECTION_STATE_WRITING_BODY:
1264 0 : if( FD_UNLIKELY( conn->is_head_request ) ) {
1265 0 : response = http->oring;
1266 0 : response_len = 0UL;
1267 0 : } else if( FD_UNLIKELY( conn->response.static_body ) ) {
1268 0 : response = conn->response.static_body;
1269 0 : response_len = conn->response.static_body_len;
1270 0 : } else {
1271 0 : response = http->oring+(conn->response._body_off%http->oring_sz);
1272 0 : response_len = conn->response._body_len;
1273 0 : }
1274 0 : break;
1275 0 : default:
1276 0 : FD_LOG_ERR(( "invalid server state (%d)", conn->state ));
1277 0 : }
1278 :
1279 0 : long sz = send( http->pollfds[ conn_idx ].fd, response+conn->response_bytes_written, response_len-conn->response_bytes_written, MSG_NOSIGNAL );
1280 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data was written, continue. */
1281 0 : if( FD_UNLIKELY( -1==sz && is_expected_network_error( errno ) ) ) {
1282 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
1283 0 : return;
1284 0 : }
1285 0 : if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "write failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
1286 :
1287 0 : http->metrics.bytes_written += (ulong)sz;
1288 0 : conn->response_bytes_written += (ulong)sz;
1289 0 : if( FD_UNLIKELY( conn->response_bytes_written==response_len ) ) {
1290 0 : switch( conn->state ) {
1291 0 : case FD_HTTP_SERVER_CONNECTION_STATE_WRITING_HEADER:
1292 0 : if( FD_UNLIKELY( conn->response.upgrade_websocket ) ) {
1293 0 : if( FD_UNLIKELY( !conn->upgrade_websocket ) ) {
1294 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_UPGRADE );
1295 0 : return;
1296 0 : }
1297 :
1298 0 : int fd = http->pollfds[ conn_idx ].fd;
1299 0 : http->pollfds[ conn_idx ].fd = -1;
1300 0 : http->pollfds[ conn_idx ].events = POLLIN;
1301 :
1302 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
1303 :
1304 0 : int ws_compress = conn->response.compress_websocket;
1305 0 : ulong req_bytes_read = conn->request_bytes_read;
1306 0 : ulong req_bytes_len = conn->request_bytes_len;
1307 :
1308 0 : if( FD_LIKELY( !conn->response.static_body && conn->response._body_len ) ) conn_treap_ele_remove( http->conn_treap, conn, http->conns );
1309 0 : conn_pool_ele_release( http->conns, conn );
1310 :
1311 0 : if( FD_UNLIKELY( !ws_conn_pool_free( http->ws_conns ) ) ) {
1312 0 : ws_conn_treap_rev_iter_t it = ws_conn_treap_rev_iter_init( http->ws_conn_treap, http->ws_conns );
1313 0 : if( FD_LIKELY( !ws_conn_treap_rev_iter_done( it ) ) ) {
1314 0 : ulong ws_conn_id = ws_conn_treap_rev_iter_idx( it );
1315 0 : close_conn( http, http->max_conns+ws_conn_id, FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
1316 0 : } else {
1317 0 : close_conn( http, http->max_conns+http->evict_ws_conn_id, FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
1318 0 : http->evict_ws_conn_id = (http->evict_ws_conn_id+1UL) % http->max_ws_conns;
1319 0 : }
1320 0 : }
1321 :
1322 0 : ulong ws_conn_id = ws_conn_pool_idx_acquire( http->ws_conns );
1323 0 : http->pollfds[ http->max_conns+ws_conn_id ].fd = fd;
1324 0 : http->pollfds[ http->max_conns+ws_conn_id ].events = POLLIN;
1325 0 : epoll_conn_move( http, http->max_conns+ws_conn_id );
1326 :
1327 0 : http->ws_conns[ ws_conn_id ].pong_state = FD_HTTP_SERVER_PONG_STATE_NONE;
1328 0 : http->ws_conns[ ws_conn_id ].send_frame_cnt = 0UL;
1329 0 : http->ws_conns[ ws_conn_id ].send_frame_state = FD_HTTP_SERVER_SEND_FRAME_STATE_HEADER;
1330 0 : http->ws_conns[ ws_conn_id ].send_frame_idx = 0UL;
1331 0 : http->ws_conns[ ws_conn_id ].recv_started_msg = 0;
1332 0 : http->ws_conns[ ws_conn_id ].recv_bytes_parsed = 0UL;
1333 0 : http->ws_conns[ ws_conn_id ].recv_bytes_read = 0UL;
1334 0 : http->ws_conns[ ws_conn_id ].send_frame_bytes_written = 0UL;
1335 0 : http->ws_conns[ ws_conn_id ].compress_websocket = ws_compress;
1336 :
1337 0 : http->metrics.connection_cnt--;
1338 0 : http->metrics.ws_connection_cnt++;
1339 :
1340 : /* Trailing data after the HTTP request was already rejected
1341 : in read_conn_http, so req_bytes_read==req_bytes_len. */
1342 0 : FD_TEST( req_bytes_read==req_bytes_len );
1343 :
1344 : #if FD_HTTP_SERVER_DEBUG
1345 : FD_LOG_WARNING(( "Upgraded connection %lu (fd=%d) to websocket connection %lu", conn_idx, fd, ws_conn_id ));
1346 : #endif
1347 :
1348 0 : if( FD_LIKELY( http->callbacks.ws_open ) ) http->callbacks.ws_open( ws_conn_id, http->callback_ctx );
1349 0 : } else {
1350 0 : conn->state = FD_HTTP_SERVER_CONNECTION_STATE_WRITING_BODY;
1351 0 : conn->response_bytes_written = 0UL;
1352 0 : write_conn_http( http, conn_idx );
1353 0 : }
1354 0 : break;
1355 0 : case FD_HTTP_SERVER_CONNECTION_STATE_WRITING_BODY:
1356 0 : if( FD_LIKELY( conn->keep_alive ) ) {
1357 0 : if( FD_LIKELY( !conn->response.static_body && conn->response._body_len ) ) conn_treap_ele_remove( http->conn_treap, conn, http->conns );
1358 0 : ulong remaining = conn->request_bytes_read-conn->request_consumed;
1359 0 : conn->state = FD_HTTP_SERVER_CONNECTION_STATE_READING;
1360 0 : conn->request_bytes_off = conn->request_consumed;
1361 0 : conn->response_bytes_written = 0UL;
1362 0 : if( FD_UNLIKELY( remaining ) ) parse_conn_http( http, conn_idx, 0UL );
1363 0 : } else {
1364 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_OK );
1365 0 : }
1366 0 : break;
1367 0 : }
1368 0 : }
1369 0 : }
1370 :
1371 : static int
1372 : maybe_write_pong( fd_http_server_t * http,
1373 0 : ulong conn_idx ) {
1374 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ conn_idx-http->max_conns ];
1375 :
1376 : /* No need to pong if ....
1377 :
1378 : Client has not sent a ping */
1379 0 : if( FD_LIKELY( conn->pong_state==FD_HTTP_SERVER_PONG_STATE_NONE ) ) return 0;
1380 : /* We are in the middle of writing a data frame */
1381 0 : if( FD_LIKELY( conn->send_frame_cnt && (conn->send_frame_state==FD_HTTP_SERVER_SEND_FRAME_STATE_DATA || conn->send_frame_bytes_written ) ) ) return 0;
1382 :
1383 : /* Otherwise, we need to pong */
1384 0 : if( FD_LIKELY( conn->pong_state==FD_HTTP_SERVER_PONG_STATE_WAITING ) ) {
1385 0 : conn->pong_state = FD_HTTP_SERVER_PONG_STATE_WRITING;
1386 0 : conn->pong_bytes_written = 0UL;
1387 0 : }
1388 :
1389 0 : uchar frame[ 2UL+125UL ];
1390 0 : frame[ 0 ] = 0x80 | 0x0A; /* FIN, 0xA for pong. */
1391 0 : frame[ 1 ] = (uchar)conn->pong_data_len;
1392 0 : fd_memcpy( frame+2UL, conn->pong_data, conn->pong_data_len );
1393 :
1394 0 : long sz = send( http->pollfds[ conn_idx ].fd, frame+conn->pong_bytes_written, 2UL+conn->pong_data_len-conn->pong_bytes_written, MSG_NOSIGNAL );
1395 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return 1; /* No data was written, continue. */
1396 0 : else if( FD_UNLIKELY( -1==sz && is_expected_network_error( errno ) ) ) {
1397 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
1398 0 : return 1;
1399 0 : }
1400 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "write failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
1401 :
1402 0 : http->metrics.bytes_written += (ulong)sz;
1403 0 : conn->pong_bytes_written += (ulong)sz;
1404 0 : if( FD_UNLIKELY( conn->pong_bytes_written==2UL+conn->pong_data_len ) ) {
1405 0 : conn->pong_state = FD_HTTP_SERVER_PONG_STATE_NONE;
1406 0 : return 0;
1407 0 : }
1408 :
1409 0 : return 1;
1410 0 : }
1411 :
1412 : static void
1413 : write_conn_ws( fd_http_server_t * http,
1414 0 : ulong conn_idx ) {
1415 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ conn_idx-http->max_conns ];
1416 :
1417 0 : if( FD_UNLIKELY( maybe_write_pong( http, conn_idx ) ) ) return;
1418 0 : if( FD_UNLIKELY( !conn->send_frame_cnt ) ) {
1419 0 : return;
1420 0 : }
1421 :
1422 0 : struct iovec iovecs[ 512UL*2UL ];
1423 0 : uchar headers[ 512UL ][ 10UL ];
1424 :
1425 0 : ulong batch_cnt = fd_ulong_min( conn->send_frame_cnt, 512UL );
1426 0 : ulong out_idx = 0UL;
1427 0 : for( ulong i=0UL; i<batch_cnt; i++ ) {
1428 0 : fd_http_server_ws_frame_t * frame = &conn->send_frames[ (conn->send_frame_idx+i) % http->max_ws_send_frame_cnt ];
1429 0 : if( FD_UNLIKELY( i || conn->send_frame_state==FD_HTTP_SERVER_SEND_FRAME_STATE_HEADER ) ) {
1430 0 : ulong header_len;
1431 0 : headers[ i ][ 0 ] = 0x80 | fd_uchar_if(frame->compressed, 0x02, 0x01); /* FIN, 0x1 for text, 0x2 for binary */
1432 0 : ulong frame_len = frame->len;
1433 0 : if( FD_LIKELY( frame_len<126UL ) ) {
1434 0 : headers[ i ][ 1 ] = (uchar)frame_len;
1435 0 : header_len = 2UL;
1436 0 : } else if( FD_LIKELY( frame_len<65536UL ) ) {
1437 0 : headers[ i ][ 1 ] = 126;
1438 0 : headers[ i ][ 2 ] = (uchar)(frame_len>>8);
1439 0 : headers[ i ][ 3 ] = (uchar)(frame_len);
1440 0 : header_len = 4UL;
1441 0 : } else {
1442 0 : headers[ i ][ 1 ] = 127;
1443 0 : headers[ i ][ 2 ] = (uchar)(frame_len>>56);
1444 0 : headers[ i ][ 3 ] = (uchar)(frame_len>>48);
1445 0 : headers[ i ][ 4 ] = (uchar)(frame_len>>40);
1446 0 : headers[ i ][ 5 ] = (uchar)(frame_len>>32);
1447 0 : headers[ i ][ 6 ] = (uchar)(frame_len>>24);
1448 0 : headers[ i ][ 7 ] = (uchar)(frame_len>>16);
1449 0 : headers[ i ][ 8 ] = (uchar)(frame_len>>8);
1450 0 : headers[ i ][ 9 ] = (uchar)(frame_len);
1451 0 : header_len = 10UL;
1452 0 : }
1453 :
1454 0 : ulong header_bytes_written = fd_ulong_if( i==0UL, conn->send_frame_bytes_written, 0UL );
1455 :
1456 0 : iovecs[ out_idx ].iov_base = headers[ i ]+header_bytes_written;
1457 0 : iovecs[ out_idx ].iov_len = header_len-header_bytes_written;
1458 0 : out_idx++;
1459 0 : }
1460 :
1461 0 : ulong data_bytes_written = fd_ulong_if( i==0UL && conn->send_frame_state==FD_HTTP_SERVER_SEND_FRAME_STATE_DATA, conn->send_frame_bytes_written, 0UL );
1462 0 : iovecs[ out_idx ].iov_base = http->oring+(frame->off%http->oring_sz)+data_bytes_written;
1463 0 : iovecs[ out_idx ].iov_len = frame->len-data_bytes_written;
1464 0 : out_idx++;
1465 0 : }
1466 :
1467 0 : struct msghdr msg = {0};
1468 0 : msg.msg_iov = iovecs;
1469 0 : msg.msg_iovlen = (__typeof__(msg.msg_iovlen))out_idx;
1470 :
1471 0 : long sz = sendmsg( http->pollfds[ conn_idx ].fd, &msg, MSG_NOSIGNAL );
1472 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data was written, continue. */
1473 0 : else if( FD_UNLIKELY( -1==sz && is_expected_network_error( errno ) ) ) {
1474 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
1475 0 : return;
1476 0 : }
1477 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "write failed (%i-%s)", errno, fd_io_strerror( errno ) )); /* Unexpected programmer error, abort */
1478 :
1479 0 : ulong sent = (ulong)sz;
1480 0 : http->metrics.bytes_written += sent;
1481 :
1482 0 : for( ulong i=0UL; i<out_idx; i++ ) {
1483 0 : ulong iov_len = iovecs[ i ].iov_len;
1484 0 : if( FD_LIKELY( sent>=iov_len ) ) {
1485 0 : conn->send_frame_bytes_written = 0UL;
1486 :
1487 0 : if( FD_LIKELY( conn->send_frame_state==FD_HTTP_SERVER_SEND_FRAME_STATE_DATA ) ) {
1488 0 : conn->send_frame_state = FD_HTTP_SERVER_SEND_FRAME_STATE_HEADER;
1489 0 : conn->send_frame_idx = (conn->send_frame_idx+1UL) % http->max_ws_send_frame_cnt;
1490 0 : conn->send_frame_cnt--;
1491 :
1492 0 : ws_conn_treap_ele_remove( http->ws_conn_treap, conn, http->ws_conns );
1493 0 : if( FD_LIKELY( conn->send_frame_cnt ) ) ws_conn_treap_ele_insert( http->ws_conn_treap, conn, http->ws_conns );
1494 :
1495 0 : http->metrics.frames_written++;
1496 0 : } else {
1497 0 : conn->send_frame_state = FD_HTTP_SERVER_SEND_FRAME_STATE_DATA;
1498 0 : }
1499 :
1500 0 : sent -= iov_len;
1501 0 : } else {
1502 0 : conn->send_frame_bytes_written += sent;
1503 0 : break;
1504 0 : }
1505 0 : }
1506 :
1507 0 : }
1508 :
1509 : static void
1510 : write_conn( fd_http_server_t * http,
1511 0 : ulong conn_idx ) {
1512 0 : if( FD_LIKELY( conn_idx<http->max_conns ) ) write_conn_http( http, conn_idx );
1513 0 : else write_conn_ws( http, conn_idx );
1514 0 : }
1515 :
1516 : int
1517 : fd_http_server_epoll_poll( fd_http_server_t * http,
1518 0 : ulong conn_max ) {
1519 0 : FD_TEST( -1!=http->epoll_fd );
1520 :
1521 0 : struct epoll_event evs[ 64 ];
1522 0 : int max_events = (int)fd_ulong_min( fd_ulong_max( conn_max, 1UL ), 64UL );
1523 0 : int nfds = epoll_pwait( http->epoll_fd, evs, max_events, 0, NULL );
1524 0 : if( FD_UNLIKELY( -1==nfds ) ) {
1525 0 : if( FD_LIKELY( errno==EINTR ) ) return 0;
1526 0 : FD_LOG_ERR(( "epoll_pwait failed (%i-%s)", errno, fd_io_strerror( errno ) ));
1527 0 : }
1528 0 : if( FD_LIKELY( !nfds ) ) return 0;
1529 :
1530 0 : ulong listener_idx = http->max_conns+http->max_ws_conns;
1531 0 : for( int i=0; i<nfds; i++ ) {
1532 0 : ulong conn_idx = evs[ i ].data.u64;
1533 0 : if( FD_UNLIKELY( conn_idx==listener_idx ) ) {
1534 0 : accept_conns( http );
1535 0 : continue;
1536 0 : }
1537 0 : if( FD_UNLIKELY( -1==http->pollfds[ conn_idx ].fd ) ) continue;
1538 0 : uint ev = evs[ i ].events;
1539 0 : int http_writing = conn_idx<http->max_conns && http->conns[ conn_idx ].state!=FD_HTTP_SERVER_CONNECTION_STATE_READING;
1540 0 : if( FD_LIKELY( (ev & EPOLLIN) || ((ev & (EPOLLHUP|EPOLLERR)) && !http_writing) ) ) read_conn( http, conn_idx );
1541 0 : if( FD_UNLIKELY( -1==http->pollfds[ conn_idx ].fd ) ) continue;
1542 0 : http_writing = conn_idx<http->max_conns && http->conns[ conn_idx ].state!=FD_HTTP_SERVER_CONNECTION_STATE_READING;
1543 0 : if( FD_LIKELY( (ev & EPOLLOUT) || http_writing ) ) write_conn( http, conn_idx );
1544 0 : epoll_update_out( http, conn_idx );
1545 0 : }
1546 :
1547 0 : return 1;
1548 0 : }
1549 :
1550 : static void
1551 : fd_http_server_evict_until( fd_http_server_t * http,
1552 0 : ulong off ) {
1553 0 : conn_treap_fwd_iter_t next;
1554 0 : for( conn_treap_fwd_iter_t it=conn_treap_fwd_iter_init( http->conn_treap, http->conns ); !conn_treap_fwd_iter_done( it ); it=next ) {
1555 0 : next = conn_treap_fwd_iter_next( it, http->conns );
1556 0 : struct fd_http_server_connection * conn = conn_treap_fwd_iter_ele( it, http->conns );
1557 :
1558 0 : if( FD_UNLIKELY( conn->response._body_off<off ) ) {
1559 0 : close_conn( http, conn_treap_fwd_iter_idx( it ), FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
1560 0 : } else {
1561 0 : break;
1562 0 : }
1563 0 : }
1564 :
1565 0 : ws_conn_treap_fwd_iter_t ws_next;
1566 0 : for( ws_conn_treap_fwd_iter_t it=ws_conn_treap_fwd_iter_init( http->ws_conn_treap, http->ws_conns ); !ws_conn_treap_fwd_iter_done( it ); it=ws_next ) {
1567 0 : ws_next = ws_conn_treap_fwd_iter_next( it, http->ws_conns );
1568 0 : struct fd_http_server_ws_connection * conn = ws_conn_treap_fwd_iter_ele( it, http->ws_conns );
1569 :
1570 0 : if( FD_UNLIKELY( conn->send_frames[ conn->send_frame_idx ].off<off ) ) {
1571 0 : close_conn( http, ws_conn_treap_fwd_iter_idx( it )+http->max_conns, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CLIENT_TOO_SLOW );
1572 0 : } else {
1573 0 : break;
1574 0 : }
1575 0 : }
1576 0 : }
1577 :
1578 : static void
1579 : fd_http_server_reserve( fd_http_server_t * http,
1580 0 : ulong len ) {
1581 : /* fd_http_server_reserve should not be called after
1582 : fd_http_ws_compress_maybe */
1583 0 : FD_TEST( http->stage_comp_len == 0 );
1584 :
1585 0 : ulong remaining = http->oring_sz-((http->stage_off%http->oring_sz)+http->stage_len);
1586 0 : if( FD_UNLIKELY( len>remaining ) ) {
1587 : /* Appending the format string into the hcache would go past the end
1588 : of the buffer... two cases, */
1589 0 : if( FD_UNLIKELY( http->stage_len+len>http->oring_sz ) ) {
1590 : /* Case 1: The snap is going to be larger than the entire buffer,
1591 : there's no way to fit it even if we evict everything
1592 : else. Mark the hcache as errored and exit. */
1593 :
1594 0 : FD_LOG_WARNING(( "tried to reserve %lu bytes for an outgoing message which exceeds the entire data size", http->stage_len+len ));
1595 0 : FD_LOG_HEXDUMP_WARNING(( "start of message", http->oring+(http->stage_off%http->oring_sz), fd_ulong_min( 500UL, http->oring_sz-(http->stage_off%http->oring_sz) ) ));
1596 0 : FD_LOG_HEXDUMP_WARNING(( "start of buffer", http->oring, fd_ulong_min( 500UL, http->oring_sz ) ));
1597 0 : http->stage_err = 1;
1598 0 : return;
1599 0 : } else {
1600 : /* Case 2: The snap can fit if we relocate it to the start of the
1601 : buffer and evict whatever was there. We also evict the
1602 : rest of the buffer behind where the snap was to
1603 : preserve the invariant that snaps are always evicted in
1604 : circular order. */
1605 :
1606 0 : ulong stage_end = http->stage_off+remaining+2UL*http->stage_len+len;
1607 0 : ulong clamp = fd_ulong_if( stage_end>=http->oring_sz, stage_end-http->oring_sz, 0UL );
1608 0 : fd_http_server_evict_until( http, clamp );
1609 0 : memmove( http->oring, http->oring+(http->stage_off%http->oring_sz), http->stage_len );
1610 0 : http->stage_off += http->stage_len+remaining;
1611 0 : http->stage_reserved_end = fd_ulong_max( http->stage_reserved_end, stage_end );
1612 0 : }
1613 0 : } else {
1614 : /* The snap can fit in the buffer, we just need to evict whatever
1615 : was there before, unless an earlier reserve already did: a
1616 : message is staged field by field and each field reserves. */
1617 0 : ulong stage_end = http->stage_off+http->stage_len+len;
1618 0 : if( FD_LIKELY( stage_end<=http->stage_reserved_end ) ) return;
1619 :
1620 0 : ulong clamp = fd_ulong_if( stage_end>=http->oring_sz, stage_end-http->oring_sz, 0UL );
1621 0 : fd_http_server_evict_until( http, clamp );
1622 0 : http->stage_reserved_end = stage_end;
1623 0 : }
1624 0 : }
1625 :
1626 : static int
1627 0 : fd_http_ws_compress_maybe( fd_http_server_t * http ) {
1628 : /* we don't compress if the message is small, or if compression is
1629 : disabled in the config */
1630 0 : if( FD_LIKELY( !http->compress_websocket || http->stage_len <= 200 || http->stage_err ) ) return 0;
1631 :
1632 0 : ulong worst_case_compressed_sz = ZSTD_compressBound( http->stage_len );
1633 0 : fd_http_server_reserve( http, worst_case_compressed_sz );
1634 :
1635 0 : if( FD_UNLIKELY( http->stage_err ) ) return 0;
1636 :
1637 0 : ulong compressed_sz = ZSTD_compress2( http->zstd_ctx, http->oring+(http->stage_off%http->oring_sz)+http->stage_len, worst_case_compressed_sz, http->oring+(http->stage_off%http->oring_sz), http->stage_len );
1638 0 : if( FD_UNLIKELY( ZSTD_isError( compressed_sz ) ) ) {
1639 0 : FD_LOG_WARNING(( "ZSTD_compress2 failed (%s)", ZSTD_getErrorName( compressed_sz ) ) );
1640 0 : http->stage_err = 1;
1641 0 : return 0;
1642 0 : }
1643 0 : FD_TEST( compressed_sz <= worst_case_compressed_sz );
1644 :
1645 0 : http->stage_comp_len = compressed_sz;
1646 :
1647 0 : return 1;
1648 0 : }
1649 :
1650 : uchar *
1651 : fd_http_server_append_start( fd_http_server_t * http,
1652 0 : ulong len ) {
1653 0 : fd_http_server_reserve( http, len );
1654 0 : if( FD_UNLIKELY( http->stage_err ) ) return NULL;
1655 0 : return http->oring+(http->stage_off%http->oring_sz)+http->stage_len;
1656 0 : }
1657 :
1658 : void
1659 : fd_http_server_append_end( fd_http_server_t * http,
1660 0 : ulong len ) {
1661 0 : http->stage_len += len;
1662 0 : }
1663 :
1664 : static inline int
1665 0 : ws_frame_oversz( fd_http_server_t const * http ) {
1666 0 : if( FD_LIKELY( http->stage_len<=UINT_MAX && http->stage_comp_len<=UINT_MAX ) ) return 0;
1667 0 : FD_LOG_WARNING(( "outgoing websocket message exceeds the maximum frame size (len=%lu comp_len=%lu)", http->stage_len, http->stage_comp_len ));
1668 0 : return 1;
1669 0 : }
1670 :
1671 : int
1672 : fd_http_server_ws_send( fd_http_server_t * http,
1673 0 : ulong ws_conn_id ) {
1674 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ ws_conn_id ];
1675 0 : int compressed = conn->compress_websocket;
1676 0 : if( FD_LIKELY( compressed ) ) compressed = fd_http_ws_compress_maybe( http );
1677 :
1678 : /* It is possible that ws_conn_id has already been closed by
1679 : fd_http_server_reserve during staging. If the staging buffer is
1680 : full, the incoming frame is added to the beginning of the buffer,
1681 : and any connections that were previously using that allotted space
1682 : are closed. There is a small chance that ws_conn_id is one of
1683 : those connections, and has therefore already been closed. */
1684 0 : if( FD_LIKELY( http->pollfds[ http->max_conns+ws_conn_id ].fd==-1 ) ) {
1685 0 : http->stage_err = 0;
1686 0 : http->stage_len = 0;
1687 0 : http->stage_reserved_end = 0UL;
1688 0 : http->stage_comp_len = 0;
1689 0 : return 0;
1690 0 : }
1691 :
1692 0 : if( FD_UNLIKELY( http->stage_err || ws_frame_oversz( http ) ) ) {
1693 0 : http->stage_err = 0;
1694 0 : http->stage_len = 0;
1695 0 : http->stage_reserved_end = 0UL;
1696 0 : http->stage_comp_len = 0;
1697 0 : return -1;
1698 0 : }
1699 :
1700 0 : if( FD_UNLIKELY( conn->send_frame_cnt==http->max_ws_send_frame_cnt ) ) {
1701 0 : close_conn( http, ws_conn_id+http->max_conns, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CLIENT_TOO_SLOW );
1702 0 : http->stage_len = 0;
1703 0 : http->stage_reserved_end = 0UL;
1704 0 : http->stage_comp_len = 0;
1705 0 : return 0;
1706 0 : }
1707 :
1708 : /* A frame is compressed only if the connection is configured to do
1709 : so, and if the compression step wasn't skipped (i.e. stage_len>200) */
1710 0 : fd_http_server_ws_frame_t frame = {
1711 0 : .off = fd_ulong_if(compressed, http->stage_off+http->stage_len, http->stage_off),
1712 0 : .len = (uint)fd_ulong_if(compressed, http->stage_comp_len, http->stage_len),
1713 0 : .compressed = compressed,
1714 0 : };
1715 :
1716 0 : conn->send_frames[ (conn->send_frame_idx+conn->send_frame_cnt) % http->max_ws_send_frame_cnt ] = frame;
1717 0 : conn->send_frame_cnt++;
1718 :
1719 0 : if( FD_LIKELY( conn->send_frame_cnt==1UL ) ) {
1720 0 : ws_conn_treap_ele_insert( http->ws_conn_treap, conn, http->ws_conns );
1721 0 : }
1722 0 : epoll_update_out( http, http->max_conns+ws_conn_id );
1723 :
1724 0 : http->stage_off += http->stage_len+http->stage_comp_len;
1725 0 : http->stage_len = 0;
1726 0 : http->stage_reserved_end = 0UL;
1727 0 : http->stage_comp_len = 0;
1728 :
1729 0 : return 0;
1730 0 : }
1731 :
1732 : int
1733 0 : fd_http_server_ws_broadcast( fd_http_server_t * http ) {
1734 0 : int compressed = fd_http_ws_compress_maybe( http );
1735 :
1736 0 : if( FD_UNLIKELY( http->stage_err || ws_frame_oversz( http ) ) ) {
1737 0 : http->stage_err = 0;
1738 0 : http->stage_len = 0;
1739 0 : http->stage_reserved_end = 0UL;
1740 0 : http->stage_comp_len = 0;
1741 0 : return -1;
1742 0 : }
1743 :
1744 0 : for( ulong i=0UL; i<http->max_ws_conns; i++ ) {
1745 0 : if( FD_LIKELY( http->pollfds[ http->max_conns+i ].fd==-1 ) ) continue;
1746 :
1747 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ i ];
1748 0 : if( FD_UNLIKELY( conn->send_frame_cnt==http->max_ws_send_frame_cnt ) ) {
1749 0 : close_conn( http, i+http->max_conns, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CLIENT_TOO_SLOW );
1750 0 : continue;
1751 0 : }
1752 :
1753 0 : fd_http_server_ws_frame_t frame = {
1754 0 : .off = fd_ulong_if(conn->compress_websocket && compressed, http->stage_off+http->stage_len, http->stage_off),
1755 0 : .len = (uint)fd_ulong_if(conn->compress_websocket && compressed, http->stage_comp_len, http->stage_len),
1756 0 : .compressed = conn->compress_websocket && compressed,
1757 0 : };
1758 :
1759 0 : conn->send_frames[ (conn->send_frame_idx+conn->send_frame_cnt) % http->max_ws_send_frame_cnt ] = frame;
1760 0 : conn->send_frame_cnt++;
1761 :
1762 0 : if( FD_LIKELY( conn->send_frame_cnt==1UL ) ) {
1763 0 : ws_conn_treap_ele_insert( http->ws_conn_treap, conn, http->ws_conns );
1764 0 : }
1765 0 : epoll_update_out( http, http->max_conns+i );
1766 0 : }
1767 :
1768 0 : http->stage_off += http->stage_len+http->stage_comp_len;
1769 0 : http->stage_len = 0;
1770 0 : http->stage_reserved_end = 0UL;
1771 0 : http->stage_comp_len = 0;
1772 :
1773 0 : return 0;
1774 0 : }
1775 :
1776 : void
1777 : fd_http_server_stage_trunc( fd_http_server_t * http,
1778 0 : ulong len ) {
1779 0 : http->stage_comp_len = 0;
1780 0 : http->stage_len = len;
1781 0 : }
1782 :
1783 : ulong
1784 0 : fd_http_server_stage_len( fd_http_server_t * http ) {
1785 0 : return http->stage_len;
1786 0 : }
1787 :
1788 : void
1789 : fd_http_server_printf( fd_http_server_t * http,
1790 : char const * fmt,
1791 0 : ... ) {
1792 0 : if( FD_UNLIKELY( http->stage_err ) ) return;
1793 :
1794 : /* Speculatively reserve enough for the common case and print
1795 : directly into the ring, re-sizing exactly only on overflow. */
1796 0 : ulong spec_sz = fd_ulong_min( 1024UL, http->oring_sz-http->stage_len );
1797 0 : fd_http_server_reserve( http, spec_sz );
1798 0 : if( FD_UNLIKELY( http->stage_err ) ) return;
1799 :
1800 0 : va_list ap;
1801 0 : va_start( ap, fmt );
1802 0 : ulong printed_len = (ulong)vsnprintf( (char *)http->oring+(http->stage_off%http->oring_sz)+http->stage_len,
1803 0 : spec_sz,
1804 0 : fmt,
1805 0 : ap );
1806 0 : va_end( ap );
1807 :
1808 0 : if( FD_UNLIKELY( printed_len+1UL>spec_sz ) ) {
1809 0 : fd_http_server_reserve( http, printed_len+1UL );
1810 0 : if( FD_UNLIKELY( http->stage_err ) ) return;
1811 :
1812 0 : va_start( ap, fmt );
1813 0 : vsnprintf( (char *)http->oring+(http->stage_off%http->oring_sz)+http->stage_len,
1814 0 : INT_MAX, /* We already proved it's going to fit above */
1815 0 : fmt,
1816 0 : ap );
1817 0 : va_end( ap );
1818 0 : }
1819 :
1820 0 : http->stage_len += printed_len;
1821 0 : }
1822 :
1823 : void
1824 : fd_http_server_memcpy( fd_http_server_t * http,
1825 : uchar const * data,
1826 0 : ulong data_len ) {
1827 0 : fd_http_server_reserve( http, data_len );
1828 0 : if( FD_UNLIKELY( http->stage_err ) ) return;
1829 :
1830 0 : fd_memcpy( (char *)http->oring+(http->stage_off%http->oring_sz)+http->stage_len,
1831 0 : data,
1832 0 : data_len );
1833 0 : http->stage_len += data_len;
1834 0 : }
1835 :
1836 : void
1837 0 : fd_http_server_unstage( fd_http_server_t * http ) {
1838 0 : http->stage_err = 0;
1839 0 : http->stage_len = 0UL;
1840 0 : http->stage_reserved_end = 0UL;
1841 0 : http->stage_comp_len = 0UL;
1842 0 : }
1843 :
1844 : int
1845 : fd_http_server_stage_body( fd_http_server_t * http,
1846 0 : fd_http_server_response_t * response ) {
1847 0 : if( FD_UNLIKELY( http->stage_err ) ) {
1848 0 : http->stage_err = 0;
1849 0 : http->stage_len = 0UL;
1850 0 : http->stage_reserved_end = 0UL;
1851 0 : http->stage_comp_len = 0UL;
1852 0 : return -1;
1853 0 : }
1854 :
1855 0 : response->_body_off = http->stage_off;
1856 0 : response->_body_len = http->stage_len;
1857 0 : http->stage_off += http->stage_len;
1858 0 : http->stage_len = 0;
1859 0 : http->stage_reserved_end = 0UL;
1860 0 : return 0;
1861 0 : }
|