--- parser3/src/main/pa_http.C 2024/11/04 03:53:25 1.129 +++ parser3/src/main/pa_http.C 2026/10/29 19:51:53 1.147 @@ -1,7 +1,7 @@ /** @file Parser: http support functions. - Copyright (c) 2001-2024 Art. Lebedev Studio (http://www.artlebedev.com) + Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com) Authors: Konstantin Morshnev , Alexandr Petrosian */ @@ -10,11 +10,15 @@ #include "pa_base64.h" #include "pa_charsets.h" #include "pa_request_charsets.h" -#include "pa_request.h" #include "pa_vfile.h" #include "pa_random.h" +#include "pa_threads.h" -volatile const char * IDENT_PA_HTTP_C="$Id: pa_http.C,v 1.129 2024/11/04 03:53:25 moko Exp $" IDENT_PA_HTTP_H; +#ifndef WIN32 +#include // for TCP_NODELAY +#endif + +volatile const char * IDENT_PA_HTTP_C="$Id: pa_http.C,v 1.147 2026/10/29 19:51:53 moko Exp $" IDENT_PA_HTTP_H; // defines @@ -37,16 +41,68 @@ volatile const char * IDENT_PA_HTTP_C="$ #define INADDR_NONE ((ulong) -1) #endif +#ifdef SOCK_CLOEXEC +// avoid inheritance by the executed programs +#define PA_ACCEPT(sock, addr, len) ::accept4(sock, addr, len, SOCK_CLOEXEC) +#define PA_SOCKET(domain, type, protocol) ::socket(domain, (type) | SOCK_CLOEXEC, protocol) +#else +#define PA_ACCEPT(sock, addr, len) ::accept(sock, addr, len) +#define PA_SOCKET(domain, type, protocol) ::socket(domain, type, protocol) +#endif + #undef CRLF #define CRLF "\r\n" +#define HTTP_TIMEOUT_COMMENT "timeout occurred while retrieving document" + // helpers +#ifdef HTTPD_DEBUG +void pa_log(const char* fmt, ...); +#define LOG(action) action +#else +#define LOG(action) +#endif + +ssize_t pa_send(int sock, const char *buffer, size_t len){ + size_t total_sent = 0; + while (total_sent < len) { + ssize_t bytes_sent=pa_sock_send(sock, buffer + total_sent, len - total_sent); + if (bytes_sent < 0) { + return bytes_sent; + } else if (bytes_sent == 0) { + // Connection closed by the remote peer? + break; + } + LOG( + if(bytes_sent != len - total_sent) + pa_log("httpd [%d] partial send %d of (%d)", sock, bytes_sent, len - total_sent) + ); + total_sent += bytes_sent; + } + return total_sent; +} + +// socket operation failed on SO_*TIMEO timeout +static bool sock_timed_out(int no){ +#ifdef WIN32 + return no==WSAETIMEDOUT; +#else + return no==EAGAIN || no==EWOULDBLOCK || no==EINPROGRESS /* connect on linux */; +#endif +} + +static int check_socket_timeout(int no){ + if(sock_timed_out(no)) + throw Exception("http.timeout", 0, HTTP_TIMEOUT_COMMENT); + return no; +} + bool HTTP_Headers::add_header(const char *line){ const char *value=strchr(line, ':'); if(value && value != line){ // we need only headers, not the response code - Header header(str_upper(line, value-line), String::Body(value+1).trim(String::TRIM_BOTH, " \t\n\r")); + Header header = Header(String::Body(str_upper(line, value-line)), String::Body(value+1).trim(String::TRIM_BOTH, " \t\n\r")); if(header.name == String::Body(HTTP_CONTENT_TYPE_UPPER) && content_type.is_empty()) content_type=header.value; @@ -109,11 +165,11 @@ public: bool read(SOCKET sock, size_t size){ if(length + size > buf_size) resize(buf_size * 2 + size); - ssize_t received_size=recv(sock, buf + length, size, 0); + ssize_t received_size=pa_sock_recv(sock, buf + length, size); if(received_size == 0) return false; if(received_size < 0) { - if(int no = pa_socks_errno()) + if(int no = check_socket_timeout(pa_socks_errno())) throw Exception("http.timeout", 0, "error receiving response: %s (%d)", pa_socks_strerr(no), no); return false; } @@ -249,35 +305,47 @@ int HTTP_response::read_response(SOCKET /* ********************** request *************************** */ #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP) -# define PA_USE_ALARM +# define PA_HAVE_ALARM #endif -#ifdef PA_USE_ALARM +#ifdef PA_HAVE_ALARM static sigjmp_buf timeout_env; static void timeout_handler(int /*sig*/){ siglongjmp(timeout_env, 1); } -#define PA_NO_THREADS (HTTPD_Server::mode != HTTPD_Server::MULTITHREADED) +// alarm is per process, threads use SO_*TIMEO +#define PA_USE_ALARM (HTTPD_Server::mode != HTTPD_Server::MULTITHREADED) -#define ALARM(value) if(PA_NO_THREADS) alarm(value) +#define ALARM(value) if(PA_USE_ALARM) alarm(value) #else +#define PA_USE_ALARM false #define ALARM(value) #endif +// SO_*TIMEO can be defined in .h but not implemented in protocol, so errors are ignored +static void set_socket_timeout(SOCKET sock, int option, int timeout_secs){ +#ifdef WIN32 + int timeout=timeout_secs < INT_MAX/1000 ? timeout_secs*1000 : 0 /* infinite */; +#else + struct timeval timeout={timeout_secs, 0}; +#endif + setsockopt(sock, SOL_SOCKET, option, (const char*)&timeout, sizeof(timeout)); +} + static int http_request(HTTP_response& response, const char* host, short port, const char* request, size_t request_size, int timeout_secs, bool fail_on_status_ne_200) { if(!host) throw Exception("http.host", 0, "zero hostname"); //never volatile SOCKET sock=INVALID_SOCKET; // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning] -#ifdef PA_USE_ALARM - if(PA_NO_THREADS) signal(SIGALRM, timeout_handler); - if(PA_NO_THREADS && sigsetjmp(timeout_env, 1)) { +#ifdef PA_HAVE_ALARM + if(PA_USE_ALARM) signal(SIGALRM, timeout_handler); + if(PA_USE_ALARM && sigsetjmp(timeout_env, 1)) { // duplicating closesocket to make code more simple for old compilers if(sock != INVALID_SOCKET) closesocket(sock); - throw Exception("http.timeout", 0, "timeout occurred while retrieving document"); + throw Exception("http.timeout", 0, HTTP_TIMEOUT_COMMENT); return 0; // never } else #endif @@ -300,22 +368,18 @@ static int http_request(HTTP_response& r linger dont_linger={0,0}; setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger)); -#ifdef WIN32 -// SO_*TIMEO can be defined in .h but not implemlemented in protocol, -// failing subsequently with Option not supported by protocol (99) message -// could not suppress that, so leaving this only for win32 - int timeout_ms=timeout_secs*1000; - setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms)); - setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms)); -#endif + if(!PA_USE_ALARM){ + set_socket_timeout(sock, SO_SNDTIMEO, timeout_secs); + set_socket_timeout(sock, SO_RCVTIMEO, timeout_secs); + } - if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) { - int no=pa_socks_errno(); + if(pa_sock_connect(sock, (struct sockaddr *)&dest, sizeof(dest))) { + int no=check_socket_timeout(pa_socks_errno()); throw Exception("http.connect", 0, "cannot connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no); } - if(send(sock, request, request_size, 0)!=(ssize_t)request_size) { - int no=pa_socks_errno(); + if(pa_send(sock, request, request_size) < 0) { + int no=check_socket_timeout(pa_socks_errno()); throw Exception("http.timeout", 0, "error sending request: %s (%d)", pa_socks_strerr(no), no); } @@ -504,17 +568,31 @@ static void form_table_value2part(Table: form_string_value2part(part->info->key, *row->get(0), *part); } -static void form_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) { - if(const String* svalue=value->get_string()) +static bool form_element_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) { + if(const String* svalue=value->get_string()){ form_string_value2part(key, *svalue, part); - else if(Table* tvalue=value->get_table()) { + } else if(VFile* vfile=dynamic_cast(value)){ + form_file_value2part(key, *vfile, part); + } else { + return false; + } + return true; +} + +static void form_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) { + if(form_element_value2part(key, value, part)) { + // string or file + } else if(Table* tvalue=value->get_table()) { Form_table_value2string_info info(key, *part.string); part.info = &info; tvalue->for_each(form_table_value2part, &part); - } else if(VFile* vfile=dynamic_cast(value)){ - form_file_value2part(key, *vfile, part); + } else if(HashStringValue* hvalue=value->get_hash()){ + // hash or array: several strings/files under the same field name + for(HashStringValue::Iterator j(*hvalue); j; j.next()) + if(!form_element_value2part(key, j.value(), part)) + throw Exception(PARSER_RUNTIME, new String(j.key(), String::L_TAINTED), "is %s, multiple values of " HTTP_FORM_NAME " field '%s' must be strings or files", j.value()->type(), key.cstr()); } else - throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED), "is %s, " HTTP_FORM_NAME " option value can be string, table or file only", value->type()); + throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED), "is %s, " HTTP_FORM_NAME " field value can be string, table, file, hash or array", value->type()); } const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){ @@ -864,7 +942,7 @@ File_read_http_result pa_internal_file_r result.headers=new HashStringValue; VHash* vtables=new VHash; - result.headers->put("tables", vtables); + HASH_PUT_CSTR(*result.headers, "tables", vtables); if (!real_remote_charset && !response.headers.content_type.is_empty()) real_remote_charset=detect_charset(response.headers.content_type.cstr()); @@ -888,7 +966,7 @@ File_read_http_result pa_internal_file_r // filling $.cookies if(vcookies=vtables->hash().get("SET-COOKIE")) - result.headers->put(HTTP_COOKIES_NAME, new VTable(parse_cookies(r, vcookies->get_table()))); + HASH_PUT_CSTR(*result.headers, HTTP_COOKIES_NAME, new VTable(parse_cookies(r, vcookies->get_table()))); // output response String::C real_body=String::C(raw_body, raw_body_size); @@ -910,13 +988,6 @@ File_read_http_result pa_internal_file_r /* ********************** httpd *************************** */ -#ifdef HTTPD_DEBUG -void pa_log(const char* fmt, ...); -#define LOG(action) action -#else -#define LOG(action) -#endif - enum EscapeState { Initial, Default, @@ -1031,22 +1102,29 @@ enum HTTPD_request_state { HTTPD_HEADERS }; +// timeout on "void" connection is normal +#define PA_RECV_TIMEOUT \ + LOG(pa_log("httpd [%d] recv got %d sec timeout", sockfd, pa_httpd_timeout)); \ + if(length) \ + throw Exception("httpd.timeout", 0, "timeout occurred while receiving request"); \ + return 0; + ssize_t HTTPD_request::pa_recv(SOCKET sockfd, char *buffer, size_t len){ LOG(pa_log("httpd [%d] recv %d appending to %d ...", sockfd, len, length)); -#ifdef PA_USE_ALARM - if(PA_NO_THREADS) signal(SIGALRM, timeout_handler); - if(PA_NO_THREADS && sigsetjmp(timeout_env, 1)) { - LOG(pa_log("httpd [%d] recv got %d sec timeout", sockfd, pa_httpd_timeout)); - if(length) // timeout on "void" connection is normal - throw Exception("httpd.timeout", 0, "timeout occurred while receiving request"); - return 0; +#ifdef PA_HAVE_ALARM + if(PA_USE_ALARM) signal(SIGALRM, timeout_handler); + if(PA_USE_ALARM && sigsetjmp(timeout_env, 1)) { + PA_RECV_TIMEOUT } else #endif { ALARM(pa_httpd_timeout); - ssize_t result=recv(sockfd, buffer, len, 0); + ssize_t result=pa_sock_recv(sockfd, buffer, len); ALARM(0); + if(result < 0 && sock_timed_out(pa_socks_errno())) { + PA_RECV_TIMEOUT + } LOG(pa_log("httpd [%d] recv got %d bytes", sockfd, result)); LOG(pa_log("httpd [%d] %s", sockfd, buffer)); return result; @@ -1093,6 +1171,11 @@ bool HTTPD_request::read_header(SOCKET s break; parse_headers(); + + if(length==body_offset){ // nothing but the headers (GET, websocket handshake), the buffer is no longer needed + buf=NULL; + length=body_offset=buf_size=0; + } return true; } } @@ -1116,7 +1199,8 @@ bool HTTPD_request::read_header(SOCKET s size_t HTTPD_request::read_post(SOCKET sock, char *body, size_t max_bytes) { size_t total_read = min(length - body_offset, max_bytes); - memcpy(body, buf + body_offset, total_read); + if(total_read) + memcpy(body, buf + body_offset, total_read); while (total_read < max_bytes){ ssize_t received_size = pa_recv(sock, body + total_read, max_bytes - total_read); @@ -1170,39 +1254,50 @@ size_t HTTPD_Connection::read_post(char size_t HTTPD_Connection::send_body(const void *buf, size_t size) { LOG(pa_log("httpd [%d] response %d bytes", sock, size)); LOG(pa_log("httpd [%d] %s", sock, buf)); - if(send(sock, (const char*)buf, size, 0) != (ssize_t)size) { + ssize_t result=pa_send(sock, (const char*)buf, size); + if(result < 0) { int no=pa_socks_errno(); throw Exception("httpd.write", 0, "error sending response: %s (%d)", pa_socks_strerr(no), no); } - return size; + return result; +} + +String::C HTTPD_Connection::unprocessed() { + return String::C(request->buf + request->body_offset, request->length - request->body_offset); +} + +size_t HTTPD_Connection::receive(char *dest, size_t max_bytes) { + ssize_t received_size=pa_sock_recv(sock, dest, max_bytes); + if(received_size < 0) { + int no=pa_socks_errno(); + if(pa_socks_is_reset(no)) + return 0; + throw Exception("httpd.read", 0, "error receiving data: %s (%d)", pa_socks_strerr(no), no); + } + return received_size; +} + +void HTTPD_Connection::set_nodelay() { + int nodelay=1; + setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&nodelay, sizeof(nodelay)); +} + +void HTTPD_Connection::set_send_timeout(int timeout_secs) { + set_socket_timeout(sock, SO_SNDTIMEO, timeout_secs); } HTTPD_Connection::~HTTPD_Connection(){ if(sock != INVALID_SOCKET){ LOG(pa_log("httpd [%d] closed", sock)); closesocket(sock); - } -} - -static int sock_ready(SOCKET fd, int operation, int timeout_value){ - struct timeval timeout = {0, timeout_value * 1000}; - fd_set fds; - FD_ZERO(&fds); - FD_SET(fd, &fds); - int nfds = (int)fd + 1; /* typecast as nfds is ignored in MSVC anyway */ - switch (operation){ - case 0: return select(nfds, &fds, NULL, NULL, &timeout)>0; /* read */ - case 1: return select(nfds, NULL, &fds, NULL, &timeout)>0; /* write */ - default: return select(nfds, &fds, &fds, NULL, &timeout)>0; /* both */ + HTTPD_Server::track_connection(-1); } } bool HTTPD_Connection::accept(SOCKET server_sock, int timeout_value) { - int ready = sock_ready(server_sock, 0, timeout_value); + int ready = pa_sock_ready(server_sock, false, timeout_value); if (ready < 0) { int no=pa_socks_errno(); - if(no == EINTR) - return false; throw Exception("httpd.accept", 0, "error waiting for connection: %s (%d)", pa_socks_strerr(no), no); } if (ready == 0) @@ -1212,16 +1307,20 @@ bool HTTPD_Connection::accept(SOCKET ser socklen_t sock_addr_len = sizeof(struct sockaddr_in); memset(&addr, 0, sock_addr_len); - sock = ::accept(server_sock, (struct sockaddr *)&addr, &sock_addr_len); + sock = PA_ACCEPT(server_sock, (struct sockaddr *)&addr, &sock_addr_len); if(sock == INVALID_SOCKET){ int no=pa_socks_errno(); throw Exception("httpd.accept", 0, "error accepting connection: %s (%d)", pa_socks_strerr(no), no); } + HTTPD_Server::track_connection(1); // taken back by the owner // Has no positive performance effect, requires include // static int sock_on=1; // setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&sock_on, sizeof(sock_on)); + if(!PA_USE_ALARM) + set_socket_timeout(sock, SO_RCVTIMEO, pa_httpd_timeout); + remote_addr = pa_strdup(inet_ntoa(addr.sin_addr)); LOG(pa_log("httpd [%d] accepted from %s", sock, remote_addr)); return true; @@ -1229,6 +1328,13 @@ bool HTTPD_Connection::accept(SOCKET ser HTTPD_Server::HTTPD_MODE HTTPD_Server::mode = HTTPD_Server::SEQUENTIAL; const char *HTTPD_Server::port=NULL; +int HTTPD_Server::max_connections=INT_MAX; +int HTTPD_Server::connections=0; + +void HTTPD_Server::track_connection(int delta){ + SYNCHRONIZED; + connections+=delta; +} void HTTPD_Server::set_mode(const String &value){ if(value == "sequental") mode = SEQUENTIAL; @@ -1262,7 +1368,7 @@ SOCKET HTTPD_Server::bind(const char *ho me.sin_addr.s_addr=INADDR_ANY; } - SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/); + SOCKET sock = PA_SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/); if(sock == INVALID_SOCKET){ int no=pa_socks_errno(); @@ -1274,7 +1380,7 @@ SOCKET HTTPD_Server::bind(const char *ho if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&sock_on, sizeof(sock_on)) || setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&sock_on, sizeof(sock_on)) || ::bind(sock, (struct sockaddr*)&me, sizeof(me)) || - listen(sock, 16)) { + listen(sock, 511)) { // same default as in apache/nginx closesocket(sock); int no = pa_socks_errno(); throw Exception("httpd.bind", 0, "cannot bind socket: %s (%d)", pa_socks_strerr(no), no);