Line data Source code
1 : #define _GNU_SOURCE
2 : #include "fd_http_server_private.h"
3 :
4 : #include "picohttpparser.h"
5 : #include "../../ballet/sha1/fd_sha1.h"
6 : #include "../../ballet/base64/fd_base64.h"
7 : #include "../../util/net/fd_ip4.h"
8 :
9 : #include <stdarg.h>
10 : #include <stdio.h>
11 : #include <errno.h>
12 : #include <unistd.h>
13 : #include <poll.h>
14 : #include <stdlib.h>
15 : #include <strings.h>
16 : #include <sys/socket.h>
17 : #include <netinet/in.h>
18 :
19 : #if FD_HAS_ZSTD
20 12 : #define FD_HTTP_ZSTD_COMPRESSION_LEVEL 3
21 : #define ZSTD_STATIC_LINKING_ONLY
22 : #include <zstd.h>
23 : #endif
24 :
25 : #define POOL_NAME ws_conn_pool
26 12 : #define POOL_T struct fd_http_server_ws_connection
27 : #define POOL_IDX_T ushort
28 0 : #define POOL_NEXT parent
29 : #include "../../util/tmpl/fd_pool.c"
30 :
31 : #define POOL_NAME conn_pool
32 12 : #define POOL_T struct fd_http_server_connection
33 : #define POOL_IDX_T ushort
34 18 : #define POOL_NEXT parent
35 : #include "../../util/tmpl/fd_pool.c"
36 :
37 : #define TREAP_NAME ws_conn_treap
38 : #define TREAP_T struct fd_http_server_ws_connection
39 : #define TREAP_QUERY_T void * /* We don't use query ... */
40 : #define TREAP_CMP(q,e) (__extension__({ (void)(q); (void)(e); -1; })) /* which means we don't need to give a real
41 : implementation to cmp either */
42 0 : #define TREAP_IDX_T ushort
43 : #define TREAP_OPTIMIZE_ITERATION 1
44 0 : #define TREAP_LT(e0,e1) ((e0)->send_frames[ (e0)->send_frame_idx ].off<(e1)->send_frames[ (e1)->send_frame_idx ].off)
45 :
46 : #include "../../util/tmpl/fd_treap.c"
47 :
48 : #define TREAP_NAME conn_treap
49 : #define TREAP_T struct fd_http_server_connection
50 : #define TREAP_QUERY_T void * /* We don't use query ... */
51 : #define TREAP_CMP(q,e) (__extension__({ (void)(q); (void)(e); -1; })) /* which means we don't need to give a real
52 : implementation to cmp either */
53 0 : #define TREAP_IDX_T ushort
54 : #define TREAP_OPTIMIZE_ITERATION 1
55 0 : #define TREAP_LT(e0,e1) ((e0)->response._body_off<(e1)->response._body_off)
56 :
57 : #include "../../util/tmpl/fd_treap.c"
58 :
59 : #define FD_HTTP_SERVER_DEBUG 0
60 :
61 : FD_FN_CONST char const *
62 0 : fd_http_server_connection_close_reason_str( int reason ) {
63 0 : switch( reason ) {
64 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_OK: return "OK-Connection was closed normally";
65 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED: return "EVICTED-Connection was evicted to make room for a new one";
66 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_TOO_SLOW: return "TOO_SLOW-Client was too slow and did not read the reponse in time";
67 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_EXPECTED_EOF: return "EXPECTED_EOF-Client continued to send data when we expected no more";
68 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET: return "PEER_RESET-Connection was reset by peer";
69 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_LARGE_REQUEST: return "LARGE_REQUEST-Request body was too large";
70 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST: return "BAD_REQUEST-Request was malformed";
71 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_MISSING_CONENT_LENGTH_HEADER: return "MISSING_CONENT_LENGTH_HEADER-Missing Content-Length header field";
72 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_UNKNOWN_METHOD: return "UNKNOWN_METHOD-Request method was not recognized";
73 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_PATH_TOO_LONG: return "PATH_TOO_LONG-Request path was too long";
74 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_KEY: return "WS_BAD_KEY-Malformed Sec-WebSocket-Key header field";
75 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_UNEXPECTED_VERSION: return "WS_UNEXPECTED_VERSION-Unexpected Sec-Websocket-Version field";
76 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_KEY_HEADER: return "WS_MISSING_KEY_HEADER-Missing Sec-WebSocket-Key header field";
77 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_VERSION_HEADER: return "WS_MISSING_VERSION_HEADER-Missing Sec-WebSocket-Version header field";
78 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_MASK: return "WS_BAD_MASK-Got frame from client without mask flag set";
79 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_UNKNOWN_OPCODE: return "WS_UNKNOWN_OPCODE-Unknown opcode in websocket frame";
80 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_OVERSIZE_FRAME: return "WS_OVERSIZE_FRAME-Websocket frame was too large";
81 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";
82 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_UPGRADE: return "WS_MISSING_UPGRADE-Missing Upgrade header field";
83 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_EXPECTED_CONT_OPCODE: return "WS_EXPECTED_CONT_OPCODE-Expected continuation opcode in websocket frame";
84 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_EXPECTED_TEXT_OPCODE: return "WS_EXPECTED_TEXT_OPCODE-Expected text opcode in websocket frame";
85 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CONTROL_FRAME_TOO_LARGE: return "WS_CONTROL_FRAME_TOO_LARGE-Websocket control frame was too large";
86 0 : case FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CHANGED_OPCODE: return "FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CHANGED_OPCODE-Websocket frame type changed unexpectedly";
87 0 : default: break;
88 0 : }
89 :
90 0 : return "unknown";
91 0 : }
92 :
93 : FD_FN_CONST char const *
94 0 : fd_http_server_method_str( uchar method ) {
95 0 : switch( method ) {
96 0 : case FD_HTTP_SERVER_METHOD_GET: return "GET";
97 0 : case FD_HTTP_SERVER_METHOD_POST: return "POST";
98 0 : case FD_HTTP_SERVER_METHOD_PUT: return "PUT";
99 0 : default: break;
100 0 : }
101 :
102 0 : return "unknown";
103 0 : }
104 :
105 : FD_FN_CONST ulong
106 30 : fd_http_server_align( void ) {
107 30 : return FD_HTTP_SERVER_ALIGN;
108 30 : }
109 :
110 : FD_FN_CONST ulong
111 6 : fd_http_server_footprint( fd_http_server_params_t params ) {
112 6 : ulong l = FD_LAYOUT_INIT;
113 6 : l = FD_LAYOUT_APPEND( l, FD_HTTP_SERVER_ALIGN, sizeof( fd_http_server_t ) );
114 6 : l = FD_LAYOUT_APPEND( l, conn_pool_align(), conn_pool_footprint( params.max_connection_cnt ) );
115 6 : l = FD_LAYOUT_APPEND( l, ws_conn_pool_align(), ws_conn_pool_footprint( params.max_ws_connection_cnt ) );
116 6 : l = FD_LAYOUT_APPEND( l, conn_treap_align(), conn_treap_footprint( params.max_connection_cnt ) );
117 6 : l = FD_LAYOUT_APPEND( l, ws_conn_treap_align(), ws_conn_treap_footprint( params.max_ws_connection_cnt ) );
118 6 : l = FD_LAYOUT_APPEND( l, alignof( struct pollfd ), (params.max_connection_cnt+params.max_ws_connection_cnt+1UL)*sizeof( struct pollfd ) );
119 6 : l = FD_LAYOUT_APPEND( l, 1UL, params.max_request_len*params.max_connection_cnt );
120 6 : l = FD_LAYOUT_APPEND( l, 1UL, params.max_ws_recv_frame_len*params.max_ws_connection_cnt );
121 6 : 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 ) );
122 6 : l = FD_LAYOUT_APPEND( l, 1UL, params.outgoing_buffer_sz );
123 6 : #if FD_HAS_ZSTD
124 6 : l = FD_LAYOUT_APPEND( l, 16UL, ZSTD_estimateCCtxSize( FD_HTTP_ZSTD_COMPRESSION_LEVEL ) );
125 6 : #endif
126 6 : return FD_LAYOUT_FINI( l, fd_http_server_align() );
127 6 : }
128 :
129 : void *
130 : fd_http_server_new( void * shmem,
131 : fd_http_server_params_t params,
132 : fd_http_server_callbacks_t callbacks,
133 6 : void * callback_ctx ) {
134 6 : if( FD_UNLIKELY( !shmem ) ) {
135 0 : FD_LOG_WARNING(( "NULL shmem" ));
136 0 : return NULL;
137 0 : }
138 :
139 6 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)shmem, fd_http_server_align() ) ) ) {
140 0 : FD_LOG_WARNING(( "misaligned shmem" ));
141 0 : return NULL;
142 0 : }
143 :
144 6 : if( FD_UNLIKELY( params.max_ws_connection_cnt && params.max_ws_recv_frame_len<params.max_request_len ) ) {
145 0 : FD_LOG_WARNING(( "max_ws_recv_frame_len<max_request_len" ));
146 0 : return NULL;
147 0 : }
148 :
149 6 : FD_SCRATCH_ALLOC_INIT( l, shmem );
150 6 : fd_http_server_t * http = FD_SCRATCH_ALLOC_APPEND( l, FD_HTTP_SERVER_ALIGN, sizeof(fd_http_server_t) );
151 6 : void * conn_pool = FD_SCRATCH_ALLOC_APPEND( l, conn_pool_align(), conn_pool_footprint( params.max_connection_cnt ) );
152 6 : void * ws_conn_pool = FD_SCRATCH_ALLOC_APPEND( l, ws_conn_pool_align(), ws_conn_pool_footprint( params.max_ws_connection_cnt ) );
153 6 : http->conn_treap = FD_SCRATCH_ALLOC_APPEND( l, conn_treap_align(), conn_treap_footprint( params.max_connection_cnt ) );
154 6 : http->ws_conn_treap = FD_SCRATCH_ALLOC_APPEND( l, ws_conn_treap_align(), ws_conn_treap_footprint( params.max_ws_connection_cnt ) );
155 6 : http->pollfds = FD_SCRATCH_ALLOC_APPEND( l, alignof(struct pollfd), (params.max_connection_cnt+params.max_ws_connection_cnt+1UL)*sizeof( struct pollfd ) );
156 6 : char * _request_bytes = FD_SCRATCH_ALLOC_APPEND( l, 1UL, params.max_request_len*params.max_connection_cnt );
157 6 : uchar * _ws_recv_bytes = FD_SCRATCH_ALLOC_APPEND( l, 1UL, params.max_ws_recv_frame_len*params.max_ws_connection_cnt );
158 6 : 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) );
159 6 : http->oring = FD_SCRATCH_ALLOC_APPEND( l, 1UL, params.outgoing_buffer_sz );
160 0 : #if FD_HAS_ZSTD
161 6 : uchar * _zstd_ctx = FD_SCRATCH_ALLOC_APPEND( l, 16UL, ZSTD_estimateCCtxSize( FD_HTTP_ZSTD_COMPRESSION_LEVEL ) );
162 0 : #endif
163 0 : http->oring_sz = params.outgoing_buffer_sz;
164 6 : http->stage_err = 0;
165 6 : http->stage_off = 0UL;
166 6 : http->stage_len = 0UL;
167 6 : http->stage_comp_len = 0UL;
168 :
169 6 : http->callbacks = callbacks;
170 6 : http->callback_ctx = callback_ctx;
171 6 : http->evict_conn_id = 0UL;
172 6 : http->evict_ws_conn_id = 0UL;
173 6 : http->max_conns = params.max_connection_cnt;
174 6 : http->max_ws_conns = params.max_ws_connection_cnt;
175 6 : http->max_request_len = params.max_request_len;
176 6 : http->max_ws_recv_frame_len = params.max_ws_recv_frame_len;
177 6 : http->max_ws_send_frame_cnt = params.max_ws_send_frame_cnt;
178 6 : http->compress_websocket = params.compress_websocket;
179 :
180 6 : #if FD_HAS_ZSTD
181 6 : http->zstd_ctx = ZSTD_initStaticCCtx( _zstd_ctx, ZSTD_estimateCCtxSize( FD_HTTP_ZSTD_COMPRESSION_LEVEL ) );
182 6 : FD_TEST( http->zstd_ctx );
183 6 : ulong err = ZSTD_CCtx_setParameter( http->zstd_ctx, 100, FD_HTTP_ZSTD_COMPRESSION_LEVEL );
184 6 : if( FD_UNLIKELY( ZSTD_isError( err ) ) )
185 0 : FD_LOG_ERR(( "ZSTD_CCtx_setParameter failed (%s)", ZSTD_getErrorName( err ) ) );
186 6 : #endif
187 :
188 6 : http->conns = conn_pool_join( conn_pool_new( conn_pool, params.max_connection_cnt ) );
189 6 : conn_treap_join( conn_treap_new( http->conn_treap, params.max_connection_cnt ) );
190 6 : conn_treap_seed( http->conns, params.max_connection_cnt, 42UL );
191 :
192 6 : http->ws_conns = ws_conn_pool_join( ws_conn_pool_new( ws_conn_pool, params.max_ws_connection_cnt ) );
193 6 : ws_conn_treap_join( ws_conn_treap_new( http->ws_conn_treap, params.max_ws_connection_cnt ) );
194 6 : ws_conn_treap_seed( http->ws_conns, params.max_ws_connection_cnt, 42UL );
195 :
196 24 : for( ulong i=0UL; i<params.max_connection_cnt; i++ ) {
197 18 : http->pollfds[ i ].fd = -1;
198 18 : http->pollfds[ i ].events = POLLIN | POLLOUT;
199 18 : http->conns[ i ] = (struct fd_http_server_connection){
200 18 : .request_bytes = _request_bytes+i*params.max_request_len,
201 18 : .parent = http->conns[ i ].parent,
202 18 : };
203 18 : }
204 :
205 6 : for( ulong i=0UL; i<params.max_ws_connection_cnt; i++ ) {
206 0 : http->pollfds[ params.max_connection_cnt+i ].fd = -1;
207 0 : http->pollfds[ params.max_connection_cnt+i ].events = POLLIN | POLLOUT;
208 0 : http->ws_conns[ i ] = (struct fd_http_server_ws_connection){
209 0 : .recv_bytes = _ws_recv_bytes+i*params.max_ws_recv_frame_len,
210 0 : .send_frames = _ws_send_frames+i*params.max_ws_send_frame_cnt,
211 0 : .parent = http->ws_conns[ i ].parent,
212 0 : };
213 0 : }
214 :
215 6 : http->pollfds[ params.max_connection_cnt+params.max_ws_connection_cnt ].fd = -1;
216 6 : http->pollfds[ params.max_connection_cnt+params.max_ws_connection_cnt ].events = POLLIN | POLLOUT;
217 :
218 6 : FD_COMPILER_MFENCE();
219 6 : FD_VOLATILE( http->magic ) = FD_HTTP_SERVER_MAGIC;
220 6 : FD_COMPILER_MFENCE();
221 :
222 6 : return (void *)http;
223 6 : }
224 :
225 : fd_http_server_t *
226 6 : fd_http_server_join( void * shhttp ) {
227 :
228 6 : if( FD_UNLIKELY( !shhttp ) ) {
229 0 : FD_LOG_WARNING(( "NULL shhttp" ));
230 0 : return NULL;
231 0 : }
232 :
233 6 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)shhttp, fd_http_server_align() ) ) ) {
234 0 : FD_LOG_WARNING(( "misaligned shhttp" ));
235 0 : return NULL;
236 0 : }
237 :
238 6 : fd_http_server_t * http = (fd_http_server_t *)shhttp;
239 :
240 6 : if( FD_UNLIKELY( http->magic!=FD_HTTP_SERVER_MAGIC ) ) {
241 0 : FD_LOG_WARNING(( "bad magic" ));
242 0 : return NULL;
243 0 : }
244 :
245 6 : return http;
246 6 : }
247 :
248 : void *
249 3 : fd_http_server_leave( fd_http_server_t * http ) {
250 :
251 3 : if( FD_UNLIKELY( !http ) ) {
252 0 : FD_LOG_WARNING(( "NULL http" ));
253 0 : return NULL;
254 0 : }
255 :
256 3 : return (void *)http;
257 3 : }
258 :
259 : void *
260 3 : fd_http_server_delete( void * shhttp ) {
261 :
262 3 : if( FD_UNLIKELY( !shhttp ) ) {
263 0 : FD_LOG_WARNING(( "NULL shhttp" ));
264 0 : return NULL;
265 0 : }
266 :
267 3 : if( FD_UNLIKELY( !fd_ulong_is_aligned( (ulong)shhttp, fd_http_server_align() ) ) ) {
268 0 : FD_LOG_WARNING(( "misaligned shhttp" ));
269 0 : return NULL;
270 0 : }
271 :
272 3 : fd_http_server_t * http = (fd_http_server_t *)shhttp;
273 :
274 3 : if( FD_UNLIKELY( http->magic!=FD_HTTP_SERVER_MAGIC ) ) {
275 0 : FD_LOG_WARNING(( "bad magic" ));
276 0 : return NULL;
277 0 : }
278 :
279 3 : FD_COMPILER_MFENCE();
280 3 : FD_VOLATILE( http->magic ) = 0UL;
281 3 : FD_COMPILER_MFENCE();
282 :
283 3 : return (void *)http;
284 3 : }
285 :
286 : int
287 0 : fd_http_server_fd( fd_http_server_t * http ) {
288 0 : return http->socket_fd;
289 0 : }
290 :
291 : fd_http_server_t *
292 : fd_http_server_listen( fd_http_server_t * http,
293 : uint address,
294 0 : ushort port ) {
295 0 : int sockfd = socket( AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0 );
296 0 : if( FD_UNLIKELY( -1==sockfd ) ) FD_LOG_ERR(( "socket failed (%i-%s)", errno, strerror( errno ) ));
297 :
298 0 : int optval = 1;
299 0 : if( FD_UNLIKELY( -1==setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof( optval ) ) ) )
300 0 : FD_LOG_ERR(( "setsockopt failed (%i-%s)", errno, strerror( errno ) ));
301 :
302 0 : struct sockaddr_in addr = {
303 0 : .sin_family = AF_INET,
304 0 : .sin_port = fd_ushort_bswap( port ),
305 0 : .sin_addr.s_addr = address,
306 0 : };
307 :
308 0 : if( FD_UNLIKELY( -1==bind( sockfd, fd_type_pun( &addr ), sizeof( addr ) ) ) ) {
309 0 : FD_LOG_ERR(( "bind(%i,AF_INET," FD_IP4_ADDR_FMT ":%u) failed (%i-%s)",
310 0 : sockfd, FD_IP4_ADDR_FMT_ARGS( address ), port,
311 0 : errno, fd_io_strerror( errno ) ));
312 0 : }
313 0 : if( FD_UNLIKELY( -1==listen( sockfd, (int)http->max_conns ) ) ) FD_LOG_ERR(( "listen failed (%i-%s)", errno, fd_io_strerror( errno ) ));
314 :
315 0 : http->socket_fd = sockfd;
316 0 : http->pollfds[ http->max_conns+http->max_ws_conns ].fd = http->socket_fd;
317 :
318 0 : return http;
319 0 : }
320 :
321 : static void
322 : close_conn( fd_http_server_t * http,
323 : ulong conn_idx,
324 0 : int reason ) {
325 0 : FD_TEST( http->pollfds[ conn_idx ].fd!=-1 );
326 : #if FD_HTTP_SERVER_DEBUG
327 : 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 ) ));
328 : #endif
329 :
330 0 : if( FD_UNLIKELY( -1==close( http->pollfds[ conn_idx ].fd ) ) ) FD_LOG_ERR(( "close failed (%i-%s)", errno, strerror( errno ) ));
331 :
332 0 : http->pollfds[ conn_idx ].fd = -1;
333 0 : if( FD_LIKELY( conn_idx<http->max_conns ) ) {
334 0 : if( FD_LIKELY( http->callbacks.close ) ) http->callbacks.close( conn_idx, reason, http->callback_ctx );
335 0 : } else {
336 0 : if( FD_LIKELY( http->callbacks.ws_close ) ) http->callbacks.ws_close( conn_idx-http->max_conns, reason, http->callback_ctx );
337 0 : }
338 :
339 0 : if( FD_UNLIKELY( conn_idx<http->max_conns ) ) {
340 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
341 0 : if( FD_LIKELY( (conn->state==FD_HTTP_SERVER_CONNECTION_STATE_WRITING_HEADER || conn->state==FD_HTTP_SERVER_CONNECTION_STATE_WRITING_BODY)
342 0 : && !conn->response.static_body ) ) {
343 0 : conn_treap_ele_remove( http->conn_treap, conn, http->conns );
344 0 : }
345 0 : conn_pool_ele_release( http->conns, conn );
346 0 : } else {
347 0 : struct fd_http_server_ws_connection * ws_conn = &http->ws_conns[ conn_idx-http->max_conns ];
348 0 : if( FD_LIKELY( ws_conn->send_frame_cnt ) ) ws_conn_treap_ele_remove( http->ws_conn_treap, ws_conn, http->ws_conns );
349 0 : ws_conn_pool_ele_release( http->ws_conns, ws_conn );
350 0 : }
351 0 : }
352 :
353 : void
354 : fd_http_server_close( fd_http_server_t * http,
355 : ulong conn_id,
356 0 : int reason ) {
357 0 : close_conn( http, conn_id, reason );
358 0 : }
359 :
360 : void
361 : fd_http_server_ws_close( fd_http_server_t * http,
362 : ulong ws_conn_id,
363 0 : int reason ) {
364 0 : close_conn( http, http->max_conns+ws_conn_id, reason );
365 0 : }
366 :
367 : /* These are the expected network errors which just mean the connection
368 : should be closed. Any errors from an accept(2), read(2), or send(2)
369 : that are not expected here will be considered fatal and terminate the
370 : server. */
371 :
372 : static inline int
373 0 : is_expected_network_error( int err ) {
374 0 : return
375 0 : err==ENETDOWN ||
376 0 : err==EPROTO ||
377 0 : err==ENOPROTOOPT ||
378 0 : err==EHOSTDOWN ||
379 0 : err==ENONET ||
380 0 : err==EHOSTUNREACH ||
381 0 : err==EOPNOTSUPP ||
382 0 : err==ENETUNREACH ||
383 0 : err==ETIMEDOUT ||
384 0 : err==ENETRESET ||
385 0 : err==ECONNABORTED ||
386 0 : err==ECONNRESET ||
387 0 : err==EPIPE;
388 0 : }
389 :
390 : static void
391 0 : accept_conns( fd_http_server_t * http ) {
392 0 : for(;;) {
393 0 : int fd = accept4( http->socket_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC );
394 :
395 0 : if( FD_UNLIKELY( -1==fd ) ) {
396 0 : if( FD_LIKELY( EAGAIN==errno ) ) break;
397 0 : else if( FD_LIKELY( is_expected_network_error( errno ) ) ) continue;
398 0 : else FD_LOG_ERR(( "accept failed (%i-%s)", errno, strerror( errno ) ));
399 0 : }
400 :
401 0 : if( FD_UNLIKELY( !conn_pool_free( http->conns ) ) ) {
402 0 : conn_treap_rev_iter_t it = conn_treap_fwd_iter_init( http->conn_treap, http->conns );
403 0 : if( FD_LIKELY( !conn_treap_fwd_iter_done( it ) ) ) {
404 0 : ulong conn_id = conn_treap_fwd_iter_idx( it );
405 0 : close_conn( http, conn_id, FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
406 0 : } else {
407 : /* If nobody is slow to read, just evict round robin */
408 0 : close_conn( http, http->evict_conn_id, FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
409 0 : http->evict_conn_id = (http->evict_conn_id+1UL) % http->max_conns;
410 0 : }
411 0 : }
412 :
413 0 : ulong conn_id = conn_pool_idx_acquire( http->conns );
414 :
415 0 : http->pollfds[ conn_id ].fd = fd;
416 0 : http->conns[ conn_id ].state = FD_HTTP_SERVER_CONNECTION_STATE_READING;
417 0 : http->conns[ conn_id ].request_bytes_read = 0UL;
418 0 : http->conns[ conn_id ].response_bytes_written = 0UL;
419 :
420 0 : if( FD_UNLIKELY( http->callbacks.open ) ) {
421 0 : http->callbacks.open( conn_id, fd, http->callback_ctx );
422 0 : }
423 :
424 : #if FD_HTTP_SERVER_DEBUG
425 : FD_LOG_NOTICE(( "Accepted connection %lu (fd=%d)", conn_id, fd ));
426 : #endif
427 0 : }
428 0 : }
429 :
430 : static void
431 : read_conn_http( fd_http_server_t * http,
432 0 : ulong conn_idx ) {
433 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
434 :
435 0 : if( FD_UNLIKELY( conn->state!=FD_HTTP_SERVER_CONNECTION_STATE_READING ) ) {
436 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_EXPECTED_EOF );
437 0 : return;
438 0 : }
439 :
440 0 : long sz = read( http->pollfds[ conn_idx ].fd, conn->request_bytes+conn->request_bytes_read, http->max_request_len-conn->request_bytes_read );
441 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data to read, continue. */
442 0 : else if( FD_UNLIKELY( !sz || (-1==sz && is_expected_network_error( errno ) ) ) ) {
443 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
444 0 : return;
445 0 : }
446 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "read failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
447 :
448 : /* New data was read... process it */
449 0 : conn->request_bytes_read += (ulong)sz;
450 0 : if( FD_UNLIKELY( conn->request_bytes_read==http->max_request_len ) ) {
451 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_LARGE_REQUEST );
452 0 : return;
453 0 : }
454 :
455 0 : char const * method;
456 0 : ulong method_len;
457 0 : char const * path;
458 0 : ulong path_len;
459 0 : int minor_version;
460 0 : struct phr_header headers[ 32 ];
461 0 : ulong num_headers = 32UL;
462 0 : int result = phr_parse_request( conn->request_bytes,
463 0 : conn->request_bytes_read,
464 0 : &method, &method_len,
465 0 : &path, &path_len,
466 0 : &minor_version,
467 0 : headers, &num_headers,
468 0 : conn->request_bytes_read - (ulong)sz );
469 0 : if( FD_UNLIKELY( -2==result ) ) return; /* Request still partial, wait for more data */
470 0 : else if( FD_UNLIKELY( -1==result ) ) {
471 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
472 0 : return;
473 0 : }
474 :
475 0 : FD_TEST( result>0 && (ulong)result<=conn->request_bytes_read );
476 :
477 0 : uchar method_enum = UCHAR_MAX;
478 0 : if( FD_LIKELY( method_len==3UL && !strncmp( method, "GET", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_GET;
479 0 : else if( FD_LIKELY( method_len==4UL && !strncmp( method, "POST", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_POST;
480 0 : else if( FD_LIKELY( method_len==7UL && !strncmp( method, "OPTIONS", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_OPTIONS;
481 0 : else if( FD_LIKELY( method_len==3UL && !strncmp( method, "PUT", method_len ) ) ) method_enum = FD_HTTP_SERVER_METHOD_PUT;
482 :
483 0 : if( FD_UNLIKELY( method_enum==UCHAR_MAX ) ) {
484 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_UNKNOWN_METHOD );
485 0 : return;
486 0 : }
487 :
488 0 : ulong content_len = 0UL;
489 0 : ulong content_length_len = 0UL;
490 0 : if( FD_UNLIKELY( method_enum==FD_HTTP_SERVER_METHOD_POST || method_enum==FD_HTTP_SERVER_METHOD_PUT ) ) {
491 0 : char const * content_length = NULL;
492 0 : for( ulong i=0UL; i<num_headers; i++ ) {
493 0 : if( FD_LIKELY( headers[ i ].name_len==14UL && !strncasecmp( headers[ i ].name, "Content-Length", 14UL ) && headers[ i ].value_len>0UL ) ) {
494 0 : content_length = headers[ i ].value;
495 0 : content_length_len = headers[ i ].value_len;
496 0 : break;
497 0 : }
498 0 : }
499 :
500 0 : if( FD_UNLIKELY( !content_length ) ) {
501 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_MISSING_CONENT_LENGTH_HEADER );
502 0 : return;
503 0 : }
504 :
505 0 : for( ulong i=0UL; i<content_length_len; i++ ) {
506 0 : if( FD_UNLIKELY( content_length[ i ]<'0' || content_length[ i ]>'9' ) ) {
507 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
508 0 : return;
509 0 : }
510 :
511 0 : ulong next = content_len*10UL + (ulong)(content_length[ i ]-'0');
512 0 : if( FD_UNLIKELY( next<content_len ) ) { /* Overflow */
513 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_LARGE_REQUEST );
514 0 : return;
515 0 : }
516 :
517 0 : content_len = next;
518 0 : }
519 :
520 0 : ulong total_len = (ulong)result+content_len;
521 :
522 0 : if( FD_UNLIKELY( total_len<content_len ) ) { /* Overflow */
523 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_LARGE_REQUEST );
524 0 : return;
525 0 : }
526 :
527 :
528 0 : if( FD_UNLIKELY( conn->request_bytes_read<(ulong)result+content_len ) ) {
529 0 : return; /* Request still partial, wait for more data */
530 0 : }
531 0 : }
532 :
533 0 : char content_type_nul_terminated[ 128 ] = {0};
534 0 : char accept_encoding_nul_terminated[ 128 ] = {0};
535 0 : for( ulong i=0UL; i<num_headers; i++ ) {
536 0 : if( FD_LIKELY( headers[ i ].name_len==12UL && !strncasecmp( headers[ i ].name, "Content-Type", 12UL ) ) ) {
537 0 : if( FD_UNLIKELY( headers[ i ].value_len>(sizeof(content_type_nul_terminated)-1UL) ) ) {
538 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
539 0 : return;
540 0 : }
541 0 : memcpy( content_type_nul_terminated, headers[ i ].value, headers[ i ].value_len );
542 0 : break;
543 0 : }
544 :
545 0 : if( FD_LIKELY( headers[ i ].name_len==15UL && !strncasecmp( headers[ i ].name, "Accept-Encoding", 15UL ) ) ) {
546 0 : if( FD_UNLIKELY( headers[ i ].value_len>(sizeof(accept_encoding_nul_terminated)-1UL) ) ) {
547 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_BAD_REQUEST );
548 0 : return;
549 0 : }
550 0 : memcpy( accept_encoding_nul_terminated, headers[ i ].value, headers[ i ].value_len );
551 0 : }
552 0 : }
553 :
554 0 : char path_nul_terminated[ 128 ] = {0};
555 0 : if( FD_UNLIKELY( path_len>(sizeof( path_nul_terminated )-1UL) ) ) {
556 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PATH_TOO_LONG );
557 0 : return;
558 0 : }
559 0 : memcpy( path_nul_terminated, path, path_len );
560 :
561 0 : char const * upgrade_key = NULL;
562 0 : for( ulong i=0UL; i<num_headers; i++ ) {
563 0 : if( FD_LIKELY( headers[ i ].name_len==7UL && !strncasecmp( headers[ i ].name, "Upgrade", 7UL ) && headers[ i ].value_len==9UL ) ) {
564 0 : upgrade_key = headers[ i ].value;
565 0 : break;
566 0 : }
567 0 : }
568 :
569 0 : conn->upgrade_websocket = 0;
570 0 : int compress_websocket = 0;
571 0 : if( FD_UNLIKELY( upgrade_key && !strncmp( upgrade_key, "websocket", 9UL ) ) ) {
572 0 : conn->request_bytes_len = (ulong)result;
573 0 : conn->upgrade_websocket = 1;
574 :
575 0 : #if FD_HAS_ZSTD
576 0 : for( ulong i=0UL; i<num_headers; i++ ) {
577 0 : if( FD_LIKELY( headers[ i ].name_len==22UL && !strncasecmp( headers[ i ].name, "Sec-WebSocket-Protocol", 22UL ) && strstr( headers[ i ].value, "compress-zstd" ) ) ) {
578 0 : compress_websocket = 1;
579 0 : }
580 0 : }
581 0 : #endif
582 :
583 0 : char const * sec_websocket_key = NULL;
584 0 : for( ulong i=0UL; i<num_headers; i++ ) {
585 0 : if( FD_LIKELY( headers[ i ].name_len==17UL && !strncasecmp( headers[ i ].name, "Sec-WebSocket-Key", 17UL ) ) ) {
586 0 : sec_websocket_key = headers[ i ].value;
587 0 : if( FD_UNLIKELY( headers[ i ].value_len!=24 ) ) {
588 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_KEY );
589 0 : return;
590 0 : }
591 0 : break;
592 0 : }
593 0 : }
594 :
595 0 : char const * sec_websocket_version = NULL;
596 0 : for( ulong i=0UL; i<num_headers; i++ ) {
597 0 : if( FD_LIKELY( headers[ i ].name_len==21UL && !strncasecmp( headers[ i ].name, "Sec-Websocket-Version", 21UL ) ) ) {
598 0 : sec_websocket_version = headers[ i ].value;
599 0 : if( FD_UNLIKELY( headers[ i ].value_len!=2 || strncmp( sec_websocket_version, "13", 2UL ) ) ) {
600 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_UNEXPECTED_VERSION );
601 0 : return;
602 0 : }
603 0 : break;
604 0 : }
605 0 : }
606 :
607 0 : if( FD_UNLIKELY( !sec_websocket_key ) ) {
608 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_KEY_HEADER );
609 0 : return;
610 0 : }
611 :
612 0 : if( FD_UNLIKELY( !sec_websocket_version ) ) {
613 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_VERSION_HEADER );
614 0 : return;
615 0 : }
616 :
617 0 : conn->sec_websocket_key = sec_websocket_key;
618 0 : }
619 :
620 0 : conn->state = FD_HTTP_SERVER_CONNECTION_STATE_WRITING_HEADER;
621 :
622 0 : fd_http_server_request_t request = {
623 0 : .connection_id = conn_idx,
624 :
625 0 : .method = method_enum,
626 0 : .path = path_nul_terminated,
627 :
628 0 : .ctx = http->callback_ctx,
629 :
630 0 : .headers.content_type = content_type_nul_terminated,
631 0 : .headers.accept_encoding = accept_encoding_nul_terminated,
632 0 : .headers.compress_websocket = compress_websocket,
633 0 : .headers.upgrade_websocket = conn->upgrade_websocket,
634 0 : };
635 :
636 0 : switch( method_enum ) {
637 0 : case FD_HTTP_SERVER_METHOD_POST:
638 0 : case FD_HTTP_SERVER_METHOD_PUT: {
639 0 : request.post.body = (uchar*)conn->request_bytes+result;
640 0 : request.post.body_len = content_len;
641 0 : } break;
642 0 : default: break;
643 0 : }
644 :
645 0 : fd_http_server_response_t response = http->callbacks.request( &request );
646 0 : if( FD_LIKELY( http->pollfds[ conn_idx ].fd==-1 ) ) return; /* Connection was closed by callback */
647 0 : conn->response = response;
648 :
649 : #if FD_HTTP_SERVER_DEBUG
650 : 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 ));
651 : #endif
652 :
653 0 : if( FD_LIKELY( !conn->response.static_body ) ) conn_treap_ele_insert( http->conn_treap, conn, http->conns );
654 0 : }
655 :
656 : static void
657 : read_conn_ws( fd_http_server_t * http,
658 0 : ulong conn_idx ) {
659 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ conn_idx-http->max_conns ];
660 :
661 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 );
662 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data to read, continue. */
663 0 : else if( FD_UNLIKELY( !sz || (-1==sz && is_expected_network_error( errno ) ) ) ) {
664 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
665 0 : return;
666 0 : }
667 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "read failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
668 :
669 : /* New data was read... process it */
670 0 : conn->recv_bytes_read += (ulong)sz;
671 0 : again:
672 0 : if( FD_UNLIKELY( conn->recv_bytes_read<2UL ) ) return; /* Need at least 2 bytes to determine frame length */
673 :
674 0 : int is_mask_set = conn->recv_bytes[ conn->recv_bytes_parsed+1UL ] & 0x80;
675 0 : if( FD_UNLIKELY( !is_mask_set ) ) {
676 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_BAD_MASK );
677 0 : return;
678 0 : }
679 :
680 0 : int opcode = conn->recv_bytes[ conn->recv_bytes_parsed ] & 0x0F;
681 0 : if( FD_UNLIKELY( opcode!=0x0 && opcode!=0x1 && opcode!=0x2 && opcode!=0x8 && opcode!=0x9 && opcode!=0xA ) ) {
682 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_UNKNOWN_OPCODE );
683 0 : return;
684 0 : }
685 :
686 0 : ulong payload_len = conn->recv_bytes[ conn->recv_bytes_parsed+1UL ] & 0x7F;
687 0 : if( FD_UNLIKELY( (payload_len==126 || payload_len==127) && (opcode==0x8 || opcode==0x9 || opcode==0xA) ) ) {
688 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CONTROL_FRAME_TOO_LARGE );
689 0 : return;
690 0 : }
691 :
692 0 : ulong len_bytes;
693 0 : if( FD_LIKELY( payload_len<126UL ) ) {
694 0 : len_bytes = 1UL;
695 0 : } else if( FD_LIKELY( payload_len==126 ) ) {
696 0 : if( FD_UNLIKELY( conn->recv_bytes_read<4UL ) ) return; /* Need at least 4 bytes to determine frame length */
697 0 : payload_len = ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+2UL ]<<8UL) | (ulong)conn->recv_bytes[ conn->recv_bytes_parsed+3UL ];
698 0 : len_bytes = 3UL;
699 0 : } else if( FD_LIKELY( payload_len==127 ) ) {
700 0 : if( FD_UNLIKELY( conn->recv_bytes_read<10UL ) ) return; /* Need at least 10 bytes to determine frame length */
701 0 : payload_len = ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+2 ]<<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) |
702 0 : ((ulong)conn->recv_bytes[ conn->recv_bytes_parsed+6 ]<<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 ];
703 0 : len_bytes = 9UL;
704 0 : } else {
705 0 : FD_LOG_ERR(( "unexpected payload_len %lu", payload_len )); /* Silence clang sanitizer, not possible */
706 0 : }
707 :
708 0 : ulong header_len = 1UL+len_bytes+4UL;
709 0 : ulong frame_len = header_len+payload_len;
710 0 : if( FD_UNLIKELY( frame_len<header_len ) ) { /* Overflow */
711 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_OVERSIZE_FRAME );
712 0 : return;
713 0 : }
714 :
715 0 : if( FD_UNLIKELY( conn->recv_bytes_parsed+frame_len+1UL>http->max_ws_recv_frame_len ) ) {
716 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_OVERSIZE_FRAME );
717 0 : return;
718 0 : }
719 :
720 0 : if( FD_UNLIKELY( conn->recv_bytes_read<frame_len ) ) return; /* Need more data to read the full frame */
721 :
722 : /* Data frame, process it */
723 :
724 0 : int is_fin_set = conn->recv_bytes[ conn->recv_bytes_parsed+0UL ] & 0x80;
725 :
726 0 : uchar * mask = conn->recv_bytes+conn->recv_bytes_parsed+1UL+len_bytes;
727 0 : uchar mask_copy[ 4 ] = { mask[ 0 ], mask[ 1 ], mask[ 2 ], mask[ 3 ] }; /* Bytes will be overwritten by the memmove below */
728 :
729 0 : uchar * payload = conn->recv_bytes+conn->recv_bytes_parsed+header_len;
730 0 : for( ulong i=0UL; i<payload_len; i++ ) conn->recv_bytes[ conn->recv_bytes_parsed+i ] = payload[ i ] ^ mask_copy[ i % 4 ];
731 :
732 : /* Frame is complete, process it */
733 :
734 0 : if( FD_UNLIKELY( opcode==0x8 ) ) {
735 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
736 0 : return;
737 0 : } else if( FD_UNLIKELY( opcode==0x9 ) ) {
738 : /* Ping frame, queue pong unless we are already sending one */
739 0 : if( FD_LIKELY( conn->pong_state!=FD_HTTP_SERVER_PONG_STATE_WAITING ) ) {
740 0 : conn->pong_state = FD_HTTP_SERVER_PONG_STATE_WAITING;
741 0 : conn->pong_data_len = payload_len;
742 0 : FD_TEST( payload_len<=125UL );
743 0 : memcpy( conn->pong_data, conn->recv_bytes+conn->recv_bytes_parsed, payload_len );
744 0 : }
745 0 : if( FD_UNLIKELY( conn->recv_bytes_read-frame_len ) ) {
746 0 : memmove( conn->recv_bytes, conn->recv_bytes+conn->recv_bytes_parsed+frame_len, conn->recv_bytes_read-frame_len );
747 0 : }
748 0 : conn->recv_bytes_parsed = 0UL;
749 0 : conn->recv_bytes_read -= frame_len;
750 0 : return;
751 0 : } else if( FD_UNLIKELY( opcode==0xA ) ) {
752 : /* Pong frame, ignore */
753 0 : if( FD_UNLIKELY( conn->recv_bytes_read-frame_len ) ) {
754 0 : memmove( conn->recv_bytes, conn->recv_bytes+conn->recv_bytes_parsed+frame_len, conn->recv_bytes_read-frame_len );
755 0 : }
756 0 : conn->recv_bytes_parsed = 0UL;
757 0 : conn->recv_bytes_read -= frame_len;
758 0 : return;
759 0 : }
760 :
761 0 : if( FD_UNLIKELY( conn->recv_started_msg && opcode!=0x0 ) ) {
762 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_EXPECTED_CONT_OPCODE );
763 0 : return;
764 0 : }
765 :
766 0 : if( FD_UNLIKELY( !conn->recv_started_msg && opcode!=0x1 && opcode!=0x2 ) ) {
767 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_EXPECTED_TEXT_OPCODE );
768 0 : return;
769 0 : }
770 :
771 0 : if( FD_UNLIKELY( conn->recv_started_msg && opcode!=conn->recv_last_opcode ) ) {
772 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CHANGED_OPCODE );
773 0 : return;
774 0 : }
775 0 : conn->recv_last_opcode = opcode;
776 :
777 : /* Check if this is a complete message */
778 :
779 0 : if( FD_UNLIKELY( !is_fin_set ) ) {
780 0 : conn->recv_started_msg = 1;
781 0 : conn->recv_bytes_read -= frame_len;
782 0 : conn->recv_bytes_parsed += payload_len;
783 0 : return; /* Not a complete message yet */
784 0 : }
785 :
786 : /* Complete message, process it */
787 :
788 0 : uchar * trailing_data = conn->recv_bytes+conn->recv_bytes_parsed+frame_len;
789 0 : ulong trailing_data_len = conn->recv_bytes_read-frame_len;
790 :
791 0 : conn->recv_bytes_parsed += payload_len;
792 0 : conn->recv_bytes_read -= frame_len;
793 :
794 0 : uchar tmp = conn->recv_bytes[ conn->recv_bytes_parsed ];
795 0 : conn->recv_bytes[ conn->recv_bytes_parsed ] = 0; /* NUL terminate */
796 0 : http->callbacks.ws_message( conn_idx-http->max_conns, conn->recv_bytes, conn->recv_bytes_parsed, http->callback_ctx );
797 0 : if( FD_UNLIKELY( -1==http->pollfds[ conn_idx ].fd ) ) return; /* Connection was closed by callback */
798 0 : conn->recv_bytes[ conn->recv_bytes_parsed ] = tmp;
799 :
800 0 : conn->recv_started_msg = 0;
801 0 : conn->recv_bytes_parsed = 0UL;
802 0 : if( FD_UNLIKELY( trailing_data_len ) ) {
803 0 : memmove( conn->recv_bytes, trailing_data, trailing_data_len );
804 0 : goto again; /* Might be another message in the buffer to process */
805 0 : }
806 0 : }
807 :
808 : static void
809 : read_conn( fd_http_server_t * http,
810 0 : ulong conn_idx ) {
811 0 : if( FD_LIKELY( conn_idx<http->max_conns ) ) read_conn_http( http, conn_idx );
812 0 : else read_conn_ws( http, conn_idx );
813 0 : }
814 :
815 : static void
816 : write_conn_http( fd_http_server_t * http,
817 0 : ulong conn_idx ) {
818 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
819 :
820 0 : char header_buf[ 1024 ];
821 :
822 0 : uchar const * response;
823 0 : ulong response_len;
824 0 : switch( conn->state ) {
825 0 : case FD_HTTP_SERVER_CONNECTION_STATE_READING:
826 0 : return; /* No data staged for write yet. */
827 0 : case FD_HTTP_SERVER_CONNECTION_STATE_WRITING_HEADER:
828 0 : switch( conn->response.status ) {
829 0 : case 200:
830 0 : if( FD_UNLIKELY( conn->response.upgrade_websocket ) ) {
831 0 : if( FD_UNLIKELY( !conn->upgrade_websocket ) ) {
832 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_UPGRADE );
833 0 : return;
834 0 : }
835 :
836 0 : uchar sec_websocket_key[ 60 ];
837 0 : fd_memcpy( sec_websocket_key, conn->sec_websocket_key, 24 );
838 0 : fd_memcpy( sec_websocket_key+24, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", 36 );
839 :
840 0 : uchar sec_websocket_accept[ 20 ];
841 0 : fd_sha1_hash( sec_websocket_key, 60, sec_websocket_accept );
842 0 : char sec_websocket_accept_base64[ FD_BASE64_ENC_SZ( 20 ) ];
843 0 : ulong encoded_len = fd_base64_encode( sec_websocket_accept_base64, sec_websocket_accept, 20 );
844 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 ) );
845 0 : } else {
846 0 : ulong body_len = conn->response.static_body ? conn->response.static_body_len : conn->response._body_len;
847 0 : FD_TEST( fd_cstr_printf_check( header_buf, sizeof( header_buf ), &response_len, "HTTP/1.1 200 OK\r\nContent-Length: %lu\r\nConnection: close\r\n", body_len ) );
848 0 : }
849 0 : break;
850 0 : case 204: {
851 0 : ulong body_len = conn->response.static_body ? conn->response.static_body_len : conn->response._body_len;
852 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 ) );
853 0 : break;
854 0 : }
855 0 : case 400: {
856 0 : ulong body_len = conn->response.static_body ? conn->response.static_body_len : conn->response._body_len;
857 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 ) );
858 0 : break;
859 0 : }
860 0 : case 404:
861 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" ) );
862 0 : break;
863 0 : case 405:
864 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" ) );
865 0 : break;
866 0 : case 500:
867 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" ) );
868 0 : break;
869 0 : default:
870 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" ) );
871 0 : break;
872 0 : }
873 :
874 0 : if( FD_LIKELY( conn->response.compress_websocket ) ) {
875 0 : ulong compress_websocket_len;
876 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" ) );
877 0 : response_len += compress_websocket_len;
878 0 : }
879 0 : if( FD_LIKELY( conn->response.content_type ) ) {
880 0 : ulong content_type_len;
881 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 ) );
882 0 : response_len += content_type_len;
883 0 : }
884 0 : if( FD_LIKELY( conn->response.cache_control ) ) {
885 0 : ulong cache_control_len;
886 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 ) );
887 0 : response_len += cache_control_len;
888 0 : }
889 0 : if( FD_LIKELY( conn->response.content_encoding ) ) {
890 0 : ulong content_encoding_len;
891 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 ) );
892 0 : response_len += content_encoding_len;
893 0 : }
894 0 : if( FD_LIKELY( conn->response.access_control_allow_origin ) ) {
895 0 : ulong access_control_allow_origin_len;
896 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 ) );
897 0 : response_len += access_control_allow_origin_len;
898 0 : }
899 0 : if( FD_LIKELY( conn->response.access_control_allow_methods ) ) {
900 0 : ulong access_control_allow_methods_len;
901 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 ) );
902 0 : response_len += access_control_allow_methods_len;
903 0 : }
904 0 : if( FD_LIKELY( conn->response.access_control_allow_headers ) ) {
905 0 : ulong access_control_allow_headers_len;
906 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 ) );
907 0 : response_len += access_control_allow_headers_len;
908 0 : }
909 0 : if( FD_LIKELY( conn->response.access_control_max_age ) ) {
910 0 : ulong access_control_max_age_len;
911 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 ) );
912 0 : response_len += access_control_max_age_len;
913 0 : }
914 0 : FD_TEST( fd_cstr_printf_check( header_buf+response_len, sizeof( header_buf )-response_len, NULL, "\r\n" ) );
915 0 : response_len += 2UL;
916 :
917 0 : response = (uchar const *)header_buf;
918 0 : break;
919 0 : case FD_HTTP_SERVER_CONNECTION_STATE_WRITING_BODY:
920 0 : if( FD_UNLIKELY( conn->response.static_body ) ) {
921 0 : response = conn->response.static_body;
922 0 : response_len = conn->response.static_body_len;
923 0 : } else {
924 0 : response = http->oring+(conn->response._body_off%http->oring_sz);
925 0 : response_len = conn->response._body_len;
926 0 : }
927 0 : break;
928 0 : default:
929 0 : FD_LOG_ERR(( "invalid server state (%d)", conn->state ));
930 0 : }
931 :
932 0 : long sz = send( http->pollfds[ conn_idx ].fd, response+conn->response_bytes_written, response_len-conn->response_bytes_written, MSG_NOSIGNAL );
933 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data was written, continue. */
934 0 : if( FD_UNLIKELY( -1==sz && is_expected_network_error( errno ) ) ) {
935 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
936 0 : return;
937 0 : }
938 0 : if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "write failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
939 :
940 0 : conn->response_bytes_written += (ulong)sz;
941 0 : if( FD_UNLIKELY( conn->response_bytes_written==response_len ) ) {
942 0 : switch( conn->state ) {
943 0 : case FD_HTTP_SERVER_CONNECTION_STATE_WRITING_HEADER:
944 0 : if( FD_UNLIKELY( conn->response.upgrade_websocket ) ) {
945 0 : if( FD_UNLIKELY( !conn->upgrade_websocket ) ) {
946 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_MISSING_UPGRADE );
947 0 : return;
948 0 : }
949 :
950 0 : int fd = http->pollfds[ conn_idx ].fd;
951 0 : http->pollfds[ conn_idx ].fd = -1;
952 :
953 0 : struct fd_http_server_connection * conn = &http->conns[ conn_idx ];
954 0 : if( FD_LIKELY( !conn->response.static_body ) ) conn_treap_ele_remove( http->conn_treap, conn, http->conns );
955 0 : conn_pool_ele_release( http->conns, conn );
956 :
957 0 : if( FD_UNLIKELY( !ws_conn_pool_free( http->ws_conns ) ) ) {
958 0 : ws_conn_treap_rev_iter_t it = ws_conn_treap_rev_iter_init( http->ws_conn_treap, http->ws_conns );
959 0 : if( FD_LIKELY( !ws_conn_treap_rev_iter_done( it ) ) ) {
960 0 : ulong ws_conn_id = ws_conn_treap_rev_iter_idx( it );
961 0 : close_conn( http, http->max_conns+ws_conn_id, FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
962 0 : } else {
963 0 : close_conn( http, http->max_conns+http->evict_ws_conn_id, FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
964 0 : http->evict_ws_conn_id = (http->evict_ws_conn_id+1UL) % http->max_ws_conns;
965 0 : }
966 0 : }
967 :
968 0 : ulong ws_conn_id = ws_conn_pool_idx_acquire( http->ws_conns );
969 0 : http->pollfds[ http->max_conns+ws_conn_id ].fd = fd;
970 :
971 0 : http->ws_conns[ ws_conn_id ].pong_state = FD_HTTP_SERVER_PONG_STATE_NONE;
972 0 : http->ws_conns[ ws_conn_id ].send_frame_cnt = 0UL;
973 0 : http->ws_conns[ ws_conn_id ].send_frame_state = FD_HTTP_SERVER_SEND_FRAME_STATE_HEADER;
974 0 : http->ws_conns[ ws_conn_id ].send_frame_idx = 0UL;
975 0 : http->ws_conns[ ws_conn_id ].recv_started_msg = 0;
976 0 : http->ws_conns[ ws_conn_id ].recv_bytes_parsed = 0UL;
977 0 : http->ws_conns[ ws_conn_id ].recv_bytes_read = 0UL;
978 0 : http->ws_conns[ ws_conn_id ].send_frame_bytes_written = 0UL;
979 0 : http->ws_conns[ ws_conn_id ].compress_websocket = conn->response.compress_websocket;
980 :
981 0 : FD_TEST( conn->request_bytes_read>=conn->request_bytes_len );
982 0 : if( FD_UNLIKELY( conn->request_bytes_read-conn->request_bytes_len>0UL ) ) {
983 : /* Client might have already started sending data prior to
984 : response, so make sure to move it to the recv buffer. */
985 0 : FD_TEST( conn->request_bytes_read-conn->request_bytes_len<=http->max_ws_recv_frame_len );
986 0 : fd_memcpy( http->ws_conns[ ws_conn_id ].recv_bytes, conn->request_bytes+conn->request_bytes_len, conn->request_bytes_read-conn->request_bytes_len );
987 0 : http->ws_conns[ ws_conn_id ].recv_bytes_read = conn->request_bytes_read-conn->request_bytes_len;
988 0 : }
989 :
990 : #if FD_HTTP_SERVER_DEBUG
991 : FD_LOG_WARNING(( "Upgraded connection %lu (fd=%d) to websocket connection %lu", conn_idx, fd, ws_conn_id ));
992 : #endif
993 :
994 0 : if( FD_LIKELY( http->callbacks.ws_open ) ) http->callbacks.ws_open( ws_conn_id, http->callback_ctx );
995 0 : } else {
996 0 : conn->state = FD_HTTP_SERVER_CONNECTION_STATE_WRITING_BODY;
997 0 : conn->response_bytes_written = 0UL;
998 0 : }
999 0 : break;
1000 0 : case FD_HTTP_SERVER_CONNECTION_STATE_WRITING_BODY:
1001 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_OK );
1002 0 : break;
1003 0 : }
1004 0 : }
1005 0 : }
1006 :
1007 : static int
1008 : maybe_write_pong( fd_http_server_t * http,
1009 0 : ulong conn_idx ) {
1010 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ conn_idx-http->max_conns ];
1011 :
1012 : /* No need to pong if ....
1013 :
1014 : Client has not sent a ping */
1015 0 : if( FD_LIKELY( conn->pong_state==FD_HTTP_SERVER_PONG_STATE_NONE ) ) return 0;
1016 : /* We are in the middle of writing a data frame */
1017 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;
1018 :
1019 : /* Otherwise, we need to pong */
1020 0 : if( FD_LIKELY( conn->pong_state==FD_HTTP_SERVER_PONG_STATE_WAITING ) ) {
1021 0 : conn->pong_state = FD_HTTP_SERVER_PONG_STATE_WRITING;
1022 0 : conn->pong_bytes_written = 0UL;
1023 0 : }
1024 :
1025 0 : uchar frame[ 2UL+125UL ];
1026 0 : frame[ 0 ] = 0x80 | 0x0A; /* FIN, 0xA for pong. */
1027 0 : frame[ 1 ] = (uchar)conn->pong_data_len;
1028 0 : fd_memcpy( frame+2UL, conn->pong_data, conn->pong_data_len );
1029 :
1030 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 );
1031 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return 1; /* No data was written, continue. */
1032 0 : else if( FD_UNLIKELY( -1==sz && is_expected_network_error( errno ) ) ) {
1033 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
1034 0 : return 1;
1035 0 : }
1036 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "write failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
1037 :
1038 0 : conn->pong_bytes_written += (ulong)sz;
1039 0 : if( FD_UNLIKELY( conn->pong_bytes_written==2UL+conn->pong_data_len ) ) {
1040 0 : conn->pong_state = FD_HTTP_SERVER_PONG_STATE_NONE;
1041 0 : return 0;
1042 0 : }
1043 :
1044 0 : return 1;
1045 0 : }
1046 :
1047 : static void
1048 : write_conn_ws( fd_http_server_t * http,
1049 0 : ulong conn_idx ) {
1050 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ conn_idx-http->max_conns ];
1051 :
1052 0 : if( FD_UNLIKELY( maybe_write_pong( http, conn_idx ) ) ) return;
1053 0 : if( FD_UNLIKELY( !conn->send_frame_cnt ) ) return;
1054 :
1055 0 : fd_http_server_ws_frame_t * frame = &conn->send_frames[ conn->send_frame_idx ];
1056 0 : switch( conn->send_frame_state ) {
1057 0 : case FD_HTTP_SERVER_SEND_FRAME_STATE_HEADER: {
1058 0 : uchar header[ 10 ];
1059 0 : ulong header_len;
1060 0 : header[ 0 ] = 0x80 | fd_uchar_if(frame->compressed, 0x02, 0x01); /* FIN, 0x1 for text, 0x2 for binary */
1061 0 : if( FD_LIKELY( frame->len<126UL ) ) {
1062 0 : header[ 1 ] = (uchar)frame->len;
1063 0 : header_len = 2UL;
1064 0 : } else if( FD_LIKELY( frame->len<65536UL ) ) {
1065 0 : header[ 1 ] = 126;
1066 0 : header[ 2 ] = (uchar)(frame->len>>8);
1067 0 : header[ 3 ] = (uchar)(frame->len);
1068 0 : header_len = 4UL;
1069 0 : } else {
1070 0 : header[ 1 ] = 127;
1071 0 : header[ 2 ] = (uchar)(frame->len>>56);
1072 0 : header[ 3 ] = (uchar)(frame->len>>48);
1073 0 : header[ 4 ] = (uchar)(frame->len>>40);
1074 0 : header[ 5 ] = (uchar)(frame->len>>32);
1075 0 : header[ 6 ] = (uchar)(frame->len>>24);
1076 0 : header[ 7 ] = (uchar)(frame->len>>16);
1077 0 : header[ 8 ] = (uchar)(frame->len>>8);
1078 0 : header[ 9 ] = (uchar)(frame->len);
1079 0 : header_len = 10UL;
1080 0 : }
1081 :
1082 0 : long sz = send( http->pollfds[ conn_idx ].fd, header+conn->send_frame_bytes_written, header_len-conn->send_frame_bytes_written, MSG_NOSIGNAL );
1083 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data was written, continue. */
1084 0 : else if( FD_UNLIKELY( -1==sz && is_expected_network_error( errno ) ) ) {
1085 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
1086 0 : return;
1087 0 : }
1088 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "write failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
1089 :
1090 0 : conn->send_frame_bytes_written += (ulong)sz;
1091 0 : if( FD_UNLIKELY( conn->send_frame_bytes_written==header_len ) ) {
1092 0 : conn->send_frame_state = FD_HTTP_SERVER_SEND_FRAME_STATE_DATA;
1093 0 : conn->send_frame_bytes_written = 0UL;
1094 0 : }
1095 0 : break;
1096 0 : }
1097 0 : case FD_HTTP_SERVER_SEND_FRAME_STATE_DATA: {
1098 : /* frame->off can point to either the compressed or uncompressed region */
1099 0 : uchar const * data = http->oring+(frame->off%http->oring_sz)+conn->send_frame_bytes_written;
1100 0 : ulong data_sz = frame->len-conn->send_frame_bytes_written;
1101 :
1102 0 : long sz = send( http->pollfds[ conn_idx ].fd, data, data_sz, MSG_NOSIGNAL );
1103 0 : if( FD_UNLIKELY( -1==sz && errno==EAGAIN ) ) return; /* No data was written, continue. */
1104 0 : else if( FD_UNLIKELY( -1==sz && is_expected_network_error( errno ) ) ) {
1105 0 : close_conn( http, conn_idx, FD_HTTP_SERVER_CONNECTION_CLOSE_PEER_RESET );
1106 0 : return;
1107 0 : }
1108 0 : else if( FD_UNLIKELY( -1==sz ) ) FD_LOG_ERR(( "write failed (%i-%s)", errno, strerror( errno ) )); /* Unexpected programmer error, abort */
1109 :
1110 0 : conn->send_frame_bytes_written += (ulong)sz;
1111 0 : if( FD_UNLIKELY( conn->send_frame_bytes_written==frame->len ) ) {
1112 0 : conn->send_frame_state = FD_HTTP_SERVER_SEND_FRAME_STATE_HEADER;
1113 0 : conn->send_frame_idx = (conn->send_frame_idx+1UL) % http->max_ws_send_frame_cnt;
1114 0 : conn->send_frame_cnt--;
1115 0 : conn->send_frame_bytes_written = 0UL;
1116 :
1117 0 : ws_conn_treap_ele_remove( http->ws_conn_treap, conn, http->ws_conns );
1118 0 : if( FD_LIKELY( conn->send_frame_cnt ) ) ws_conn_treap_ele_insert( http->ws_conn_treap, conn, http->ws_conns );
1119 0 : }
1120 0 : break;
1121 0 : }
1122 0 : }
1123 0 : }
1124 :
1125 : static void
1126 : write_conn( fd_http_server_t * http,
1127 0 : ulong conn_idx ) {
1128 0 : if( FD_LIKELY( conn_idx<http->max_conns ) ) write_conn_http( http, conn_idx );
1129 0 : else write_conn_ws( http, conn_idx );
1130 0 : }
1131 :
1132 : int
1133 : fd_http_server_poll( fd_http_server_t * http,
1134 0 : int poll_timeout ) {
1135 0 : int nfds = fd_syscall_poll( http->pollfds, (uint)( http->max_conns+http->max_ws_conns+1UL ), poll_timeout );
1136 0 : if( FD_UNLIKELY( 0==nfds ) ) return 0;
1137 0 : else if( FD_UNLIKELY( -1==nfds && errno==EINTR ) ) return 0;
1138 0 : else if( FD_UNLIKELY( -1==nfds ) ) FD_LOG_ERR(( "poll failed (%i-%s)", errno, strerror( errno ) ));
1139 :
1140 : /* Poll existing connections for new data. */
1141 0 : for( ulong i=0UL; i<http->max_conns+http->max_ws_conns+1UL; i++ ) {
1142 0 : if( FD_UNLIKELY( -1==http->pollfds[ i ].fd ) ) continue;
1143 0 : if( FD_UNLIKELY( i==http->max_conns+http->max_ws_conns ) ) {
1144 0 : accept_conns( http );
1145 0 : } else {
1146 0 : if( FD_LIKELY( http->pollfds[ i ].revents & POLLIN ) ) read_conn( http, i );
1147 0 : if( FD_UNLIKELY( -1==http->pollfds[ i ].fd ) ) continue;
1148 0 : if( FD_LIKELY( http->pollfds[ i ].revents & POLLOUT ) ) write_conn( http, i );
1149 : /* No need to handle POLLHUP, read() will return 0 soon enough. */
1150 0 : }
1151 0 : }
1152 :
1153 0 : return 1;
1154 0 : }
1155 :
1156 : static void
1157 : fd_http_server_evict_until( fd_http_server_t * http,
1158 676965 : ulong off ) {
1159 676965 : conn_treap_fwd_iter_t next;
1160 676965 : 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 ) {
1161 0 : next = conn_treap_fwd_iter_next( it, http->conns );
1162 0 : struct fd_http_server_connection * conn = conn_treap_fwd_iter_ele( it, http->conns );
1163 :
1164 0 : if( FD_UNLIKELY( conn->response._body_off<off ) ) {
1165 0 : close_conn( http, conn_treap_fwd_iter_idx( it ), FD_HTTP_SERVER_CONNECTION_CLOSE_EVICTED );
1166 0 : } else {
1167 0 : break;
1168 0 : }
1169 0 : }
1170 :
1171 676965 : ws_conn_treap_fwd_iter_t ws_next;
1172 676965 : 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 ) {
1173 0 : ws_next = ws_conn_treap_fwd_iter_next( it, http->ws_conns );
1174 0 : struct fd_http_server_ws_connection * conn = ws_conn_treap_fwd_iter_ele( it, http->ws_conns );
1175 :
1176 0 : if( FD_UNLIKELY( conn->send_frames[ conn->send_frame_idx ].off<off ) ) {
1177 0 : close_conn( http, ws_conn_treap_fwd_iter_idx( it )+http->max_conns, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CLIENT_TOO_SLOW );
1178 0 : } else {
1179 0 : break;
1180 0 : }
1181 0 : }
1182 676965 : }
1183 :
1184 : static void
1185 : fd_http_server_reserve( fd_http_server_t * http,
1186 747624 : ulong len ) {
1187 : /* fd_http_server_reserve should not be called after
1188 : fd_http_server_compress */
1189 747624 : FD_TEST( http->stage_comp_len == 0 );
1190 :
1191 747624 : ulong remaining = http->oring_sz-((http->stage_off%http->oring_sz)+http->stage_len);
1192 747624 : if( FD_UNLIKELY( len>remaining ) ) {
1193 : /* Appending the format string into the hcache would go past the end
1194 : of the buffer... two cases, */
1195 81420 : if( FD_UNLIKELY( http->stage_len+len>http->oring_sz ) ) {
1196 : /* Case 1: The snap is going to be larger than the entire buffer,
1197 : there's no way to fit it even if we evict everything
1198 : else. Mark the hcache as errored and exit. */
1199 :
1200 70659 : FD_LOG_WARNING(( "tried to reserve %lu bytes for an outgoing message which exceeds the entire data size", http->stage_len+len ));
1201 70659 : http->stage_err = 1;
1202 70659 : return;
1203 70659 : } else {
1204 : /* Case 2: The snap can fit if we relocate it to the start of the
1205 : buffer and evict whatever was there. We also evict the
1206 : rest of the buffer behind where the snap was to
1207 : preserve the invariant that snaps are always evicted in
1208 : circular order. */
1209 :
1210 10761 : ulong stage_end = http->stage_off+remaining+http->stage_len+len;
1211 10761 : ulong clamp = fd_ulong_if( stage_end>=http->oring_sz, stage_end-http->oring_sz, 0UL );
1212 10761 : fd_http_server_evict_until( http, clamp );
1213 10761 : memmove( http->oring, http->oring+(http->stage_off%http->oring_sz), http->stage_len );
1214 10761 : http->stage_off += http->stage_len+remaining;
1215 10761 : }
1216 666204 : } else {
1217 : /* The snap can fit in the buffer, we just need to evict whatever
1218 : was there before. */
1219 666204 : ulong stage_end = http->stage_off+http->stage_len+len;
1220 666204 : ulong clamp = fd_ulong_if( stage_end>=http->oring_sz, stage_end-http->oring_sz, 0UL );
1221 666204 : fd_http_server_evict_until( http, clamp );
1222 666204 : }
1223 747624 : }
1224 :
1225 : static int
1226 0 : fd_http_ws_compress_maybe( fd_http_server_t * http ) {
1227 : /* we don't compress if the message is small, or if compression is
1228 : disabled in the config */
1229 0 : if( FD_LIKELY( !http->compress_websocket || http->stage_len <= 200 || http->stage_err ) ) return 0;
1230 :
1231 0 : #if FD_HAS_ZSTD
1232 0 : ulong worst_case_compressed_sz = ZSTD_compressBound( http->stage_len );
1233 0 : fd_http_server_reserve( http, worst_case_compressed_sz );
1234 :
1235 0 : if( FD_UNLIKELY( http->stage_err ) ) return 0;
1236 :
1237 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 );
1238 0 : if( FD_UNLIKELY( ZSTD_isError( compressed_sz ) ) ) {
1239 0 : FD_LOG_WARNING(( "ZSTD_compress2 failed (%s)", ZSTD_getErrorName( compressed_sz ) ) );
1240 0 : http->stage_err = 1;
1241 0 : return 0;
1242 0 : }
1243 0 : FD_TEST( compressed_sz <= worst_case_compressed_sz );
1244 :
1245 0 : http->stage_comp_len = compressed_sz;
1246 :
1247 0 : return 1;
1248 : #else
1249 : return 0;
1250 : #endif
1251 0 : }
1252 :
1253 : int
1254 : fd_http_server_ws_send( fd_http_server_t * http,
1255 0 : ulong ws_conn_id ) {
1256 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ ws_conn_id ];
1257 0 : int compressed = conn->compress_websocket;
1258 0 : if( FD_LIKELY( compressed ) ) compressed = fd_http_ws_compress_maybe( http );
1259 :
1260 :
1261 0 : if( FD_UNLIKELY( http->stage_err ) ) {
1262 0 : http->stage_err = 0;
1263 0 : http->stage_len = 0;
1264 0 : http->stage_comp_len = 0;
1265 0 : return -1;
1266 0 : }
1267 :
1268 : /* It is possible that ws_conn_id has already been closed by
1269 : fd_http_server_reserve during staging. If the staging buffer is
1270 : full, the incoming frame is added to the beginning of the buffer,
1271 : and any connections that were previously using that allotted space
1272 : are closed. There is a small chance that ws_conn_id is one of
1273 : those connections, and has therefore already been closed. */
1274 0 : if( FD_LIKELY( http->pollfds[ http->max_conns+ws_conn_id ].fd==-1 ) ) {
1275 0 : http->stage_len = 0;
1276 0 : return 0;
1277 0 : }
1278 :
1279 0 : if( FD_UNLIKELY( conn->send_frame_cnt==http->max_ws_send_frame_cnt ) ) {
1280 0 : close_conn( http, ws_conn_id+http->max_conns, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CLIENT_TOO_SLOW );
1281 0 : http->stage_len = 0;
1282 0 : return 0;
1283 0 : }
1284 :
1285 : /* A frame is compressed only if the connection is configured to do
1286 : so, and if the compression step wasn't skipped (i.e. stage_len>200) */
1287 0 : fd_http_server_ws_frame_t frame = {
1288 0 : .off = fd_ulong_if(compressed, http->stage_off+http->stage_len, http->stage_off),
1289 0 : .len = fd_ulong_if(compressed, http->stage_comp_len, http->stage_len),
1290 0 : .compressed = compressed,
1291 0 : };
1292 :
1293 0 : conn->send_frames[ (conn->send_frame_idx+conn->send_frame_cnt) % http->max_ws_send_frame_cnt ] = frame;
1294 0 : conn->send_frame_cnt++;
1295 :
1296 0 : if( FD_LIKELY( conn->send_frame_cnt==1UL ) ) {
1297 0 : ws_conn_treap_ele_insert( http->ws_conn_treap, conn, http->ws_conns );
1298 0 : }
1299 :
1300 0 : http->stage_off += http->stage_len+http->stage_comp_len;
1301 0 : http->stage_len = 0;
1302 0 : http->stage_comp_len = 0;
1303 :
1304 0 : return 0;
1305 0 : }
1306 :
1307 : int
1308 0 : fd_http_server_ws_broadcast( fd_http_server_t * http ) {
1309 0 : int compressed = fd_http_ws_compress_maybe( http );
1310 :
1311 0 : if( FD_UNLIKELY( http->stage_err ) ) {
1312 0 : http->stage_err = 0;
1313 0 : http->stage_len = 0;
1314 0 : http->stage_comp_len = 0;
1315 0 : return -1;
1316 0 : }
1317 :
1318 0 : for( ulong i=0UL; i<http->max_ws_conns; i++ ) {
1319 0 : if( FD_LIKELY( http->pollfds[ http->max_conns+i ].fd==-1 ) ) continue;
1320 :
1321 0 : struct fd_http_server_ws_connection * conn = &http->ws_conns[ i ];
1322 0 : if( FD_UNLIKELY( conn->send_frame_cnt==http->max_ws_send_frame_cnt ) ) {
1323 0 : close_conn( http, i+http->max_conns, FD_HTTP_SERVER_CONNECTION_CLOSE_WS_CLIENT_TOO_SLOW );
1324 0 : continue;
1325 0 : }
1326 :
1327 0 : fd_http_server_ws_frame_t frame = {
1328 0 : .off = fd_ulong_if(conn->compress_websocket && compressed, http->stage_off+http->stage_len, http->stage_off),
1329 0 : .len = fd_ulong_if(conn->compress_websocket && compressed, http->stage_comp_len, http->stage_len),
1330 0 : .compressed = conn->compress_websocket && compressed,
1331 0 : };
1332 :
1333 0 : conn->send_frames[ (conn->send_frame_idx+conn->send_frame_cnt) % http->max_ws_send_frame_cnt ] = frame;
1334 0 : conn->send_frame_cnt++;
1335 :
1336 0 : if( FD_LIKELY( conn->send_frame_cnt==1UL ) ) {
1337 0 : ws_conn_treap_ele_insert( http->ws_conn_treap, conn, http->ws_conns );
1338 0 : }
1339 0 : }
1340 :
1341 0 : http->stage_off += http->stage_len+http->stage_comp_len;
1342 0 : http->stage_len = 0;
1343 0 : http->stage_comp_len = 0;
1344 :
1345 0 : return 0;
1346 0 : }
1347 :
1348 : void
1349 : fd_http_server_stage_trunc( fd_http_server_t * http,
1350 0 : ulong len ) {
1351 0 : http->stage_comp_len = 0;
1352 0 : http->stage_len = len;
1353 0 : }
1354 :
1355 : ulong
1356 0 : fd_http_server_stage_len( fd_http_server_t * http ) {
1357 0 : return http->stage_len;
1358 0 : }
1359 :
1360 : void
1361 : fd_http_server_printf( fd_http_server_t * http,
1362 : char const * fmt,
1363 1524840 : ... ) {
1364 1524840 : if( FD_UNLIKELY( http->stage_err ) ) return;
1365 :
1366 747624 : va_list ap;
1367 747624 : va_start( ap, fmt );
1368 747624 : ulong printed_len = (ulong)vsnprintf( NULL, 0UL, fmt, ap );
1369 747624 : va_end( ap );
1370 :
1371 747624 : fd_http_server_reserve( http, printed_len );
1372 747624 : if( FD_UNLIKELY( http->stage_err ) ) return;
1373 :
1374 747624 : va_start( ap, fmt );
1375 676965 : vsnprintf( (char *)http->oring+(http->stage_off%http->oring_sz)+http->stage_len,
1376 676965 : INT_MAX, /* We already proved it's going to fit above */
1377 676965 : fmt,
1378 676965 : ap );
1379 676965 : va_end( ap );
1380 :
1381 676965 : http->stage_len += printed_len;
1382 676965 : }
1383 :
1384 : void
1385 : fd_http_server_memcpy( fd_http_server_t * http,
1386 : uchar const * data,
1387 0 : ulong data_len ) {
1388 0 : fd_http_server_reserve( http, data_len );
1389 0 : if( FD_UNLIKELY( http->stage_err ) ) return;
1390 :
1391 0 : fd_memcpy( (char *)http->oring+(http->stage_off%http->oring_sz)+http->stage_len,
1392 0 : data,
1393 0 : data_len );
1394 0 : http->stage_len += data_len;
1395 0 : }
1396 :
1397 : void
1398 6 : fd_http_server_unstage( fd_http_server_t * http ) {
1399 6 : http->stage_err = 0;
1400 6 : http->stage_len = 0UL;
1401 6 : http->stage_comp_len = 0UL;
1402 6 : }
1403 :
1404 : int
1405 : fd_http_server_stage_body( fd_http_server_t * http,
1406 95244 : fd_http_server_response_t * response ) {
1407 95244 : if( FD_UNLIKELY( http->stage_err ) ) {
1408 70659 : http->stage_err = 0;
1409 70659 : http->stage_len = 0;
1410 70659 : return -1;
1411 70659 : }
1412 :
1413 24585 : response->_body_off = http->stage_off;
1414 24585 : response->_body_len = http->stage_len;
1415 24585 : http->stage_off += http->stage_len;
1416 24585 : http->stage_len = 0;
1417 24585 : return 0;
1418 95244 : }
|