LCOV - code coverage report
Current view: top level - ballet/http - fd_http_server.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 134 972 13.8 %
Date: 2024-11-13 11:58:15 Functions: 9 33 27.3 %

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

Generated by: LCOV version 1.14