Annotation of parser3/src/main/pa_http.C, revision 1.148

1.1       paf         1: /** @file
                      2:        Parser: http support functions.
                      3: 
1.135     moko        4:        Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)
1.121     moko        5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.1       paf         6:  */
                      7: 
                      8: #include "pa_http.h"
                      9: #include "pa_common.h"
1.81      moko       10: #include "pa_base64.h"
1.1       paf        11: #include "pa_charsets.h"
                     12: #include "pa_request_charsets.h"
1.22      misha      13: #include "pa_vfile.h"
                     14: #include "pa_random.h"
1.145     moko       15: #include "pa_threads.h"
1.1       paf        16: 
1.140     moko       17: #ifndef WIN32
                     18: #include <netinet/tcp.h> // for TCP_NODELAY
                     19: #endif
                     20: 
1.148   ! moko       21: 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; 
1.53      moko       22: 
1.1       paf        23: // defines
                     24: 
1.19      misha      25: #define HTTP_METHOD_NAME       "method"
                     26: #define HTTP_FORM_NAME "form"
                     27: #define HTTP_BODY_NAME "body"
                     28: #define HTTP_TIMEOUT_NAME      "timeout"
                     29: #define HTTP_HEADERS_NAME      "headers"
1.22      misha      30: #define HTTP_FORM_ENCTYPE_NAME "enctype"
1.19      misha      31: #define HTTP_ANY_STATUS_NAME   "any-status"
1.59      moko       32: #define HTTP_OMIT_POST_CHARSET_NAME    "omit-post-charset"     // ^file::load[...;http://...;$.method[post]] by default adds charset to content-type
1.12      misha      33: 
1.1       paf        34: #define HTTP_USER "user"
                     35: #define HTTP_PASSWORD "password"
                     36: 
1.70      moko       37: #define HTTP_USER_AGENT "user-agent"
1.1       paf        38: #define DEFAULT_USER_AGENT "parser3"
                     39: 
1.59      moko       40: #ifndef INADDR_NONE
                     41: #define INADDR_NONE ((ulong) -1)
                     42: #endif
1.1       paf        43: 
1.146     moko       44: #ifdef SOCK_CLOEXEC
                     45: // avoid inheritance by the executed programs
                     46: #define PA_ACCEPT(sock, addr, len) ::accept4(sock, addr, len, SOCK_CLOEXEC)
                     47: #define PA_SOCKET(domain, type, protocol) ::socket(domain, (type) | SOCK_CLOEXEC, protocol)
                     48: #else
1.148   ! moko       49: #ifdef FD_CLOEXEC
        !            50: // FreeBSD < 10: a program executed by another thread between the call and fcntl still inherits the socket
        !            51: static SOCKET pa_cloexec(SOCKET sock) {
        !            52:        if(sock != INVALID_SOCKET)
        !            53:                fcntl(sock, F_SETFD, FD_CLOEXEC);
        !            54:        return sock;
        !            55: }
        !            56: #define PA_ACCEPT(sock, addr, len) pa_cloexec(::accept(sock, addr, len))
        !            57: #define PA_SOCKET(domain, type, protocol) pa_cloexec(::socket(domain, type, protocol))
        !            58: #else
1.146     moko       59: #define PA_ACCEPT(sock, addr, len) ::accept(sock, addr, len)
                     60: #define PA_SOCKET(domain, type, protocol) ::socket(domain, type, protocol)
                     61: #endif
1.148   ! moko       62: #endif
1.146     moko       63: 
1.1       paf        64: #undef CRLF
                     65: #define CRLF "\r\n"
                     66: 
1.138     moko       67: #define HTTP_TIMEOUT_COMMENT "timeout occurred while retrieving document"
                     68: 
1.54      misha      69: // helpers
1.56      misha      70: 
1.130     moko       71: #ifdef HTTPD_DEBUG
                     72: void pa_log(const char* fmt, ...);
                     73: #define LOG(action) action
                     74: #else
                     75: #define LOG(action)
                     76: #endif
                     77: 
                     78: ssize_t pa_send(int sock, const char *buffer, size_t len){
                     79:        size_t total_sent = 0;
                     80:        while (total_sent < len) {
1.141     moko       81:                ssize_t bytes_sent=pa_sock_send(sock, buffer + total_sent, len - total_sent);
1.130     moko       82:                if (bytes_sent < 0) {
                     83:                        return bytes_sent;
                     84:                } else if (bytes_sent == 0) {
                     85:                        // Connection closed by the remote peer?
                     86:                        break;
                     87:                }
                     88:                LOG(
                     89:                        if(bytes_sent != len - total_sent)
                     90:                                pa_log("httpd [%d] partial send %d of (%d)", sock, bytes_sent, len - total_sent)
                     91:                );
                     92:                total_sent += bytes_sent;
                     93:        }
                     94:        return total_sent;
                     95: }
                     96: 
1.138     moko       97: // socket operation failed on SO_*TIMEO timeout
                     98: static bool sock_timed_out(int no){
                     99: #ifdef WIN32
                    100:        return no==WSAETIMEDOUT;
                    101: #else
                    102:        return no==EAGAIN || no==EWOULDBLOCK || no==EINPROGRESS /* connect on linux */;
                    103: #endif
                    104: }
                    105: 
                    106: static int check_socket_timeout(int no){
                    107:        if(sock_timed_out(no))
                    108:                throw Exception("http.timeout", 0, HTTP_TIMEOUT_COMMENT);
                    109:        return no;
                    110: }
                    111: 
1.85      moko      112: bool HTTP_Headers::add_header(const char *line){
1.78      moko      113:        const char *value=strchr(line, ':');
                    114: 
                    115:        if(value && value != line){ // we need only headers, not the response code
1.134     moko      116:                Header header = Header(String::Body(str_upper(line, value-line)), String::Body(value+1).trim(String::TRIM_BOTH, " \t\n\r"));
1.78      moko      117: 
                    118:                if(header.name == String::Body(HTTP_CONTENT_TYPE_UPPER) && content_type.is_empty())
                    119:                        content_type=header.value;
                    120: 
                    121:                if(header.name == String::Body("CONTENT-LENGTH") && content_length==0)
1.95      moko      122:                        ALTER_EXCEPTION_COMMENT(content_length=pa_atoul(header.value.cstr()), " for content-length");
1.78      moko      123: 
                    124:                headers+=header;
                    125: 
                    126:                return true;
                    127:        }
                    128:        return false;
                    129: }
                    130: 
1.54      misha     131: class Cookies_table_template_columns: public ArrayString {
                    132: public:
                    133:        Cookies_table_template_columns() {
                    134:                *this+=new String("name");
                    135:                *this+=new String("value");
                    136:                *this+=new String("expires");
                    137:                *this+=new String("max-age");
                    138:                *this+=new String("domain");
                    139:                *this+=new String("path");
                    140:                *this+=new String("httponly");
                    141:                *this+=new String("secure");
                    142:        }
                    143: };
                    144: 
                    145: 
1.1       paf       146: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
1.22      misha     147:        memset(addr, 0, sizeof(*addr)); 
                    148:        addr->sin_family=AF_INET;
                    149:        addr->sin_port=htons(port); 
                    150:        if(host) {
1.65      moko      151:                struct hostent *hostIP=gethostbyname(host);
                    152:                if(hostIP && hostIP->h_addrtype == AF_INET){
                    153:                        memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length);
                    154:                        return true;
                    155:                }
                    156:        }
                    157:        return false;
1.1       paf       158: }
                    159: 
1.84      moko      160: class HTTP_response : public PA_Allocated {
1.78      moko      161: public:
                    162:        char *buf;
                    163:        size_t length;
                    164:        size_t buf_size;
                    165:        size_t body_offset;
                    166: 
1.85      moko      167:        HTTP_Headers headers;
1.78      moko      168: 
1.97      moko      169:        HTTP_response() : buf(NULL), length(0), buf_size(0), body_offset(0){}
1.78      moko      170: 
                    171:        void resize(size_t size){
                    172:                buf_size=size;
                    173:                buf=(char *)pa_realloc(buf, size + 1);
                    174:        }
                    175: 
1.120     moko      176:        bool read(SOCKET sock, size_t size){
1.103     moko      177:                if(length + size > buf_size)
                    178:                        resize(buf_size * 2 + size);
1.141     moko      179:                ssize_t received_size=pa_sock_recv(sock, buf + length, size);
1.103     moko      180:                if(received_size == 0)
1.78      moko      181:                        return false;
1.103     moko      182:                if(received_size < 0) {
1.138     moko      183:                        if(int no = check_socket_timeout(pa_socks_errno()))
1.102     moko      184:                                throw Exception("http.timeout", 0, "error receiving response: %s (%d)", pa_socks_strerr(no), no);
1.78      moko      185:                        return false;
                    186:                }
                    187:                length+=received_size;
                    188:                buf[length]='\0';
                    189:                return true;
                    190:        }
                    191: 
1.83      moko      192:        size_t first_line(){
1.89      moko      193:                char *header=strchr(buf, '\n');
                    194:                if(!header)
1.78      moko      195:                        return false;
                    196: 
1.89      moko      197:                return header-buf;
1.78      moko      198:        }
                    199: 
                    200:        const char *status_code(char *status_line, int &result){
                    201:                char* status_start = strchr(status_line, ' ');
                    202: 
                    203:                if(!(status_start++))
                    204:                        return status_line;
                    205: 
                    206:                char* status_end=strchr(status_start, ' ');
                    207: 
                    208:                if(!status_end)
                    209:                        return status_line;
                    210: 
                    211:                if(status_end==status_start)
                    212:                        return status_line;
1.1       paf       213: 
1.78      moko      214:                const char *result_str=pa_strdup(status_start, status_end-status_start);
1.95      moko      215:                ALTER_EXCEPTION_COMMENT(result=pa_atoui(result_str), " for HTTP status");
1.78      moko      216:                return result_str;
                    217:        }
1.2       paf       218: 
1.78      moko      219:        bool body_start(){
                    220:                char *p=buf;
                    221:                while((p=strchr(p, '\n'))) {
                    222:                        if(p[1]=='\r' && p[2]=='\n'){  // \r\n\r\n
                    223:                                *p='\0';
                    224:                                body_offset=p-buf+3;
                    225:                                return true;
                    226:                        }
                    227:                        if(p[1]=='\n') { // \n\n
                    228:                                *p='\0';
                    229:                                body_offset=p-buf+2;
                    230:                                return true;
                    231:                        }
                    232:                        p++;
                    233:                }
                    234:                return false;
1.2       paf       235:        }
1.78      moko      236: 
                    237:        void parse_headers(){
                    238:                const String header_block(buf, String::L_TAINTED);
                    239:                
                    240:                ArrayString aheaders;
                    241:                header_block.split(aheaders, 0, "\n");
                    242: 
1.124     moko      243:                ArrayString::Iterator i(aheaders);
1.78      moko      244:                i.next(); // skipping status
1.125     moko      245:                for(;i;){
1.78      moko      246:                        const char *line=i.next()->cstr();
                    247:                        if(!headers.add_header(line))
1.97      moko      248:                                throw Exception("http.response", 0, "bad response from host - bad header \"%s\"", line);
1.78      moko      249:                }
1.1       paf       250:        }
                    251: 
1.120     moko      252:        int read_response(SOCKET sock, bool fail_on_status_ne_200);
1.78      moko      253: };
                    254: 
                    255: enum HTTP_response_state {
                    256:        HTTP_STATUS_CODE,
                    257:        HTTP_HEADERS,
                    258:        HTTP_BODY
                    259: };
                    260: 
1.120     moko      261: int HTTP_response::read_response(SOCKET sock, bool fail_on_status_ne_200) {
1.78      moko      262:        HTTP_response_state state=HTTP_STATUS_CODE;
                    263:        int result=0;
                    264: 
                    265:        size_t chunk_size=0x400*16;
1.88      moko      266:        resize(2*chunk_size);
1.78      moko      267: 
1.88      moko      268:        while(read(sock, chunk_size)){
1.78      moko      269:                switch(state){
                    270:                        case HTTP_STATUS_CODE: {
1.88      moko      271:                                size_t status_size=first_line();
1.78      moko      272:                                if(!status_size)
                    273:                                        break;
                    274: 
1.88      moko      275:                                const char *status=status_code(pa_strdup(buf, status_size), result);
1.78      moko      276: 
                    277:                                if(!result || fail_on_status_ne_200 && result!=200)
                    278:                                        throw Exception("http.status", status ? new String(status) : &String::Empty, "invalid HTTP response status");
                    279: 
                    280:                                state=HTTP_HEADERS;
                    281:                        }
                    282: 
                    283:                        case HTTP_HEADERS: {
1.88      moko      284:                                if(!body_start())
1.78      moko      285:                                        break;
                    286: 
1.88      moko      287:                                parse_headers();
1.78      moko      288: 
1.97      moko      289:                                size_t content_length=check_file_size(headers.content_length, 0);
1.88      moko      290:                                if(content_length>0 && (content_length + body_offset) > length){
                    291:                                        resize(content_length + body_offset + 0x400*64);
1.78      moko      292:                                }
                    293: 
                    294:                                state=HTTP_BODY;
1.1       paf       295:                                break;
                    296:                        }
1.78      moko      297: 
                    298:                        case HTTP_BODY: {
                    299:                                chunk_size=0x400*64;
1.1       paf       300:                                break;
                    301:                        }
                    302:                }
                    303:        }
1.78      moko      304: 
                    305:        if(state==HTTP_STATUS_CODE)
1.97      moko      306:                throw Exception("http.response", 0, "bad response from host - no status found (size=%u)", length);
1.78      moko      307: 
                    308:        if(state==HTTP_HEADERS){
1.88      moko      309:                parse_headers();
                    310:                body_offset=length;
1.1       paf       311:        }
1.78      moko      312: 
                    313:        return result;
1.1       paf       314: }
                    315: 
                    316: /* ********************** request *************************** */
                    317: 
                    318: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
1.138     moko      319: #      define PA_HAVE_ALARM
1.1       paf       320: #endif
                    321: 
1.138     moko      322: #ifdef PA_HAVE_ALARM
1.1       paf       323: static sigjmp_buf timeout_env;
                    324: static void timeout_handler(int /*sig*/){
1.101     moko      325:        siglongjmp(timeout_env, 1);
1.1       paf       326: }
1.118     moko      327: 
1.138     moko      328: // alarm is per process, threads use SO_*TIMEO
                    329: #define PA_USE_ALARM (HTTPD_Server::mode != HTTPD_Server::MULTITHREADED)
1.118     moko      330: 
1.138     moko      331: #define ALARM(value) if(PA_USE_ALARM) alarm(value)
1.101     moko      332: #else
1.138     moko      333: #define PA_USE_ALARM false
1.101     moko      334: #define ALARM(value)
1.1       paf       335: #endif
                    336: 
1.138     moko      337: // SO_*TIMEO can be defined in .h but not implemented in protocol, so errors are ignored
                    338: static void set_socket_timeout(SOCKET sock, int option, int timeout_secs){
                    339: #ifdef WIN32
                    340:        int timeout=timeout_secs < INT_MAX/1000 ? timeout_secs*1000 : 0 /* infinite */;
                    341: #else
                    342:        struct timeval timeout={timeout_secs, 0};
                    343: #endif
                    344:        setsockopt(sock, SOL_SOCKET, option, (const char*)&timeout, sizeof(timeout));
                    345: }
                    346: 
1.78      moko      347: 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) {
1.1       paf       348:        if(!host)
1.73      moko      349:                throw Exception("http.host", 0, "zero hostname");  //never
1.1       paf       350: 
1.120     moko      351:        volatile SOCKET sock=INVALID_SOCKET; // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning]
1.101     moko      352:                
1.138     moko      353: #ifdef PA_HAVE_ALARM
                    354:        if(PA_USE_ALARM) signal(SIGALRM, timeout_handler);
                    355:        if(PA_USE_ALARM && sigsetjmp(timeout_env, 1)) {
1.101     moko      356:                // duplicating closesocket to make code more simple for old compilers
1.120     moko      357:                if(sock != INVALID_SOCKET)
1.101     moko      358:                        closesocket(sock);
1.138     moko      359:                throw Exception("http.timeout", 0, HTTP_TIMEOUT_COMMENT);
1.1       paf       360:                return 0; // never
1.101     moko      361:        } else
1.1       paf       362: #endif
1.101     moko      363:        {
                    364:                ALARM(timeout_secs);
1.1       paf       365:                try {
                    366:                        int result;
                    367:                        struct sockaddr_in dest;
                    368:                
                    369:                        if(!set_addr(&dest, host, port))
1.127     moko      370:                                throw Exception("http.host", 0, "cannot resolve hostname \"%s\"", host); 
1.1       paf       371:                        
1.120     moko      372:                        if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/)) == INVALID_SOCKET) {
1.1       paf       373:                                int no=pa_socks_errno();
1.127     moko      374:                                throw Exception("http.connect", 0, "cannot make socket: %s (%d)", pa_socks_strerr(no), no); 
1.1       paf       375:                        }
                    376: 
                    377:                        // To enable SO_DONTLINGER (that is, disable SO_LINGER) 
                    378:                        // l_onoff should be set to zero and setsockopt should be called
                    379:                        linger dont_linger={0,0};
                    380:                        setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger));
                    381: 
1.138     moko      382:                        if(!PA_USE_ALARM){
                    383:                                set_socket_timeout(sock, SO_SNDTIMEO, timeout_secs);
                    384:                                set_socket_timeout(sock, SO_RCVTIMEO, timeout_secs);
                    385:                        }
1.1       paf       386: 
1.147     moko      387:                        if(pa_sock_connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
1.138     moko      388:                                int no=check_socket_timeout(pa_socks_errno());
1.127     moko      389:                                throw Exception("http.connect", 0, "cannot connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no);
1.1       paf       390:                        }
1.22      misha     391: 
1.130     moko      392:                        if(pa_send(sock, request, request_size) < 0) {
1.138     moko      393:                                int no=check_socket_timeout(pa_socks_errno());
1.78      moko      394:                                throw Exception("http.timeout", 0, "error sending request: %s (%d)", pa_socks_strerr(no), no);
1.1       paf       395:                        }
                    396: 
1.88      moko      397:                        result=response.read_response(sock, fail_on_status_ne_200);
1.78      moko      398:                        closesocket(sock);
1.101     moko      399:                        ALARM(0);
1.1       paf       400:                        return result;
                    401:                } catch(...) {
1.101     moko      402:                        ALARM(0);
1.120     moko      403:                        if(sock != INVALID_SOCKET)
1.78      moko      404:                                closesocket(sock);
1.1       paf       405:                        rethrow;
                    406:                }
                    407:        }
                    408: }
                    409: 
                    410: #ifndef DOXYGEN
                    411: struct Http_pass_header_info {
                    412:        Request_charsets* charsets;
                    413:        String* request;
1.35      misha     414:        bool* user_agent_specified;
                    415:        bool* content_type_specified;
                    416:        bool* content_type_url_encoded;
1.1       paf       417: };
                    418: #endif
1.50      moko      419: 
                    420: char *pa_http_safe_header_name(const char *name) {
                    421:        char *result=pa_strdup(name);
                    422:        char *n=result;
1.52      misha     423:        if(!pa_isalpha((unsigned char)*n))
1.50      moko      424:                *n++ = '_';
                    425:        for(; *n; ++n) {
1.52      misha     426:                if (!pa_isalnum((unsigned char)*n) && *n != '-' && *n != '_')
1.50      moko      427:                        *n = '_';
                    428:        }
                    429:        return result;
                    430: }
                    431: 
1.101     moko      432: static void http_pass_header(HashStringValue::key_type aname, HashStringValue::value_type avalue, Http_pass_header_info *info) {
1.9       misha     433: 
1.41      misha     434:        const char* name_cstr=aname.cstr();
                    435: 
1.38      misha     436:        if(strcasecmp(name_cstr, HTTP_CONTENT_LENGTH)==0)
                    437:                return;
                    438: 
1.50      moko      439:        String name=String(pa_http_safe_header_name(capitalize(name_cstr)), String::L_AS_IS);
                    440:        String value=attributed_meaning_to_string(*avalue, String::L_HTTP_HEADER, true);
1.9       misha     441: 
1.35      misha     442:        *info->request << name << ": " << value << CRLF;
1.1       paf       443:        
1.38      misha     444:        if(strcasecmp(name_cstr, HTTP_USER_AGENT)==0)
1.35      misha     445:                *info->user_agent_specified=true;
1.38      misha     446:        if(strcasecmp(name_cstr, HTTP_CONTENT_TYPE)==0){
1.35      misha     447:                *info->content_type_specified=true;
1.62      moko      448:                *info->content_type_url_encoded=pa_strncasecmp(value.cstr(), HTTP_CONTENT_TYPE_FORM_URLENCODED)==0;
1.35      misha     449:        }
1.1       paf       450: }
                    451: 
1.10      misha     452: static void http_pass_cookie(HashStringValue::key_type name, 
1.20      misha     453:                                HashStringValue::value_type value, 
                    454:                                Http_pass_header_info *info) {
1.10      misha     455:        
1.17      misha     456:        *info->request << String(name, String::L_HTTP_COOKIE) << "="
1.31      misha     457:                << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, true)
1.10      misha     458:                << "; "; 
                    459: 
                    460: }
1.1       paf       461: 
                    462: static const String* basic_authorization_field(const char* user, const char* pass) {
                    463:        if(!user&& !pass)
                    464:                return 0;
                    465: 
                    466:        String combined;  
                    467:        if(user)
                    468:                combined<<user;
                    469:        combined<<":";
                    470:        if(pass)
                    471:                combined<<pass;
                    472:        
1.20      misha     473:        String* result=new String("Basic ");
1.82      moko      474:        *result<<pa_base64_encode(combined.cstr(), combined.length(), Base64Options(false /*no wrap*/));
1.1       paf       475:        return result;
                    476: }
                    477: 
1.73      moko      478: static void form_string_value2string(HashStringValue::key_type key, const String& value, String& result) {
1.30      misha     479:        result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1       paf       480: }
1.20      misha     481: 
1.1       paf       482: #ifndef DOXYGEN
                    483: struct Form_table_value2string_info {
                    484:        HashStringValue::key_type key;
                    485:        String& result;
                    486: 
                    487:        Form_table_value2string_info(HashStringValue::key_type akey, String& aresult): 
                    488:                key(akey), result(aresult) {}
                    489: };
                    490: #endif
                    491: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
                    492:        form_string_value2string(info->key, *row->get(0), info->result);
                    493: }
1.73      moko      494: 
                    495: static void form_value2string(HashStringValue::key_type key, HashStringValue::value_type value, String* result) {
1.1       paf       496:        if(const String* svalue=value->get_string())
                    497:                form_string_value2string(key, *svalue, *result);
                    498:        else if(Table* tvalue=value->get_table()) {
                    499:                Form_table_value2string_info info(key, *result);
                    500:                tvalue->for_each(form_table_value2string, &info);
                    501:        } else
1.73      moko      502:                throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED),
1.63      moko      503:                        "is %s, " HTTP_FORM_NAME " option value can be string or table only (file is allowed for $." HTTP_METHOD_NAME "[POST] + $." HTTP_FORM_ENCTYPE_NAME "[" HTTP_CONTENT_TYPE_MULTIPART_FORMDATA "])", value->type());
1.1       paf       504: }
1.20      misha     505: 
1.5       misha     506: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1       paf       507:        String string;
1.3       paf       508:        form.for_each<String*>(form_value2string, &string);
1.44      misha     509:        return string.untaint_and_transcode_cstr(String::L_URI, &charsets);
1.1       paf       510: }
1.22      misha     511: 
                    512: struct FormPart {
                    513:        Request* r;
                    514:        const char* boundary;
1.48      moko      515:        String* string;
1.22      misha     516:        Form_table_value2string_info* info;
1.48      moko      517: 
                    518:        struct BinaryBlock{
                    519:                const char* ptr;
                    520:                size_t length;
                    521: 
                    522:                BinaryBlock(String* astring, Request* r): ptr(astring->untaint_and_transcode_cstr(String::L_AS_IS, &r->charsets)), length(strlen(ptr)){}
                    523:                BinaryBlock(const char* aptr, size_t alength): ptr(aptr), length(alength){}
                    524:        };
                    525: 
                    526:        Array<BinaryBlock> blocks;
                    527: 
                    528:        FormPart(Request* ar, const char* aboundary): r(ar), boundary(aboundary), string(new String()){}
                    529: 
                    530:        const char *post(size_t &length){
                    531:                if(blocks.count()){
                    532:                        blocks+=BinaryBlock(string, r);
                    533: 
                    534:                        length=0;
                    535:                        for(size_t i=0; i<blocks.count(); i++)
                    536:                                length+=blocks[i].length;
                    537: 
                    538:                        char *result=(char *)pa_malloc_atomic(length);
                    539:                        char *ptr=result;
                    540: 
                    541:                        for(size_t i=0; i<blocks.count(); i++){
                    542:                                memcpy(ptr, blocks[i].ptr, blocks[i].length);
                    543:                                ptr+=blocks[i].length;
                    544:                        }
                    545: 
                    546:                        return result;
                    547:                } else {
                    548:                        BinaryBlock result(string, r);
                    549:                        length=result.length;
                    550:                        return result.ptr;
                    551:                }
                    552:        }
1.22      misha     553: };
                    554: 
1.73      moko      555: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0) {
                    556:        *part.string << "--" << part.boundary << CRLF CONTENT_DISPOSITION_CAPITALIZED ": form-data; name=\"" << name << "\"";
1.22      misha     557:        if(file_name){
                    558:                if(strcmp(file_name, NONAME_DAT)!=0)
1.48      moko      559:                        *part.string << "; filename=\"" << file_name << "\"";
                    560:                *part.string << CRLF HTTP_CONTENT_TYPE_CAPITALIZED ": " << part.r->mime_type_of(file_name);
1.22      misha     561:        }
1.48      moko      562:        *part.string << CRLF CRLF;
1.22      misha     563: }
                    564: 
1.73      moko      565: static void form_string_value2part(HashStringValue::key_type key, const String& value, FormPart& part) {
1.28      misha     566:        form_part_boundary_header(part, key);
1.48      moko      567:        *part.string << value << CRLF;
1.22      misha     568: }
                    569: 
1.73      moko      570: static void form_file_value2part(HashStringValue::key_type key, VFile& vfile, FormPart& part) {
1.28      misha     571:        form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.48      moko      572:        part.blocks+=FormPart::BinaryBlock(part.string, part.r);
                    573:        part.blocks+=FormPart::BinaryBlock(vfile.value_ptr(), vfile.value_size());
                    574:        part.string=new String();
                    575:        *part.string << CRLF;
1.22      misha     576: }
                    577: 
                    578: static void form_table_value2part(Table::element_type row, FormPart* part) {
                    579:        form_string_value2part(part->info->key, *row->get(0), *part);
                    580: }
                    581: 
1.136     moko      582: static bool form_element_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) {
                    583:        if(const String* svalue=value->get_string()){
                    584:                form_string_value2part(key, *svalue, part);
                    585:        } else if(VFile* vfile=dynamic_cast<VFile *>(value)){
                    586:                form_file_value2part(key, *vfile, part);
                    587:        } else {
                    588:                return false;
                    589:        }
                    590:        return true;
                    591: }
                    592: 
1.73      moko      593: static void form_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) {
1.136     moko      594:        if(form_element_value2part(key, value, part)) {
                    595:                // string or file
                    596:        } else if(Table* tvalue=value->get_table()) {
1.48      moko      597:                Form_table_value2string_info info(key, *part.string);
1.22      misha     598:                part.info = &info;
                    599:                tvalue->for_each(form_table_value2part, &part);
1.136     moko      600:        } else if(HashStringValue* hvalue=value->get_hash()){
                    601:                // hash or array: several strings/files under the same field name
                    602:                for(HashStringValue::Iterator j(*hvalue); j; j.next())
                    603:                        if(!form_element_value2part(key, j.value(), part))
                    604:                                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());
1.22      misha     605:        } else
1.136     moko      606:                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());
1.22      misha     607: }
                    608: 
                    609: const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){
1.48      moko      610:        FormPart formpart(&r, boundary);
1.22      misha     611:        form.for_each<FormPart&>(form_value2part, formpart);
1.48      moko      612:        *formpart.string << "--" << boundary << "--";
                    613:        // @todo: return binary blocks here to save memory in pa_internal_file_read_http
                    614:        return formpart.post(post_size);
1.22      misha     615: }
                    616: 
1.54      misha     617: // Set-Cookie: name=value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly
                    618: static ArrayString* parse_cookie(Request& r, const String& cookie) {
1.64      moko      619:        char *current=pa_strdup(cookie.cstr());
1.54      misha     620:        
                    621:        const String* name=0;
1.55      moko      622:        const String* value=&String::Empty;
                    623:        const String* expires=&String::Empty;
                    624:        const String* max_age=&String::Empty;
                    625:        const String* path=&String::Empty;
                    626:        const String* domain=&String::Empty;
                    627:        const String* httponly=&String::Empty;
                    628:        const String* secure=&String::Empty;
1.54      misha     629: 
                    630:        bool first_pair=true;
                    631: 
                    632:        do {
                    633:                if(char *meaning=search_stop(current, ';'))
                    634:                        if(char *attribute=search_stop(meaning, '=')) {
                    635:                                const String* sname=new String(unescape_chars(attribute, strlen(attribute), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
                    636:                                const String* smeaning=0;
                    637:                                if(meaning)
                    638:                                        smeaning=new String(unescape_chars(meaning, strlen(meaning), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
                    639: 
                    640:                                if(first_pair) {
                    641:                                        // name + value
                    642:                                        name=sname;
1.122     moko      643:                                        if(smeaning)
                    644:                                                value=smeaning;
1.54      misha     645:                                        first_pair=false;
                    646:                                } else {
                    647:                                        const String& slower=sname->change_case(r.charsets.source(), String::CC_LOWER);
                    648: 
                    649:                                        if(slower == "expires")
                    650:                                                expires=smeaning;
                    651:                                        else if(slower == "max-age")
                    652:                                                max_age=smeaning;
                    653:                                        else if(slower == "domain")
                    654:                                                domain=smeaning;
                    655:                                        else if(slower == "path")
                    656:                                                path=smeaning;
                    657:                                        else if(slower == "httponly")
                    658:                                                httponly=new String("1", String::L_CLEAN);
                    659:                                        else if(slower == "secure")
                    660:                                                secure=new String("1", String::L_CLEAN);
                    661:                                        else {
                    662:                                                // todo@ ?
                    663:                                        }
                    664:                                }
                    665:                        }
                    666:        } while(current);
                    667: 
                    668:        if(!name)
                    669:                return 0;
                    670: 
                    671:        ArrayString* result=new ArrayString(8);
                    672:        *result+=name;
                    673:        *result+=value;
                    674:        *result+=expires;
                    675:        *result+=max_age;
                    676:        *result+=domain;
                    677:        *result+=path;
                    678:        *result+=httponly;
                    679:        *result+=secure;
                    680: 
                    681:        return result;
                    682: }
                    683: 
1.56      misha     684: Table* parse_cookies(Request& r, Table *cookies){
                    685:        Table& result=*new Table(new Cookies_table_template_columns);
                    686: 
1.125     moko      687:        for(Array_iterator<Table::element_type> i(*cookies); i; )
1.56      misha     688:                if(ArrayString* row=parse_cookie(r, *i.next()->get(0)))
                    689:                        result+=row;
                    690: 
                    691:        return &result;
                    692: }
                    693: 
1.75      moko      694: void tables_update(HashStringValue& tables, const String::Body name, const String& value){
1.72      moko      695:        Table *table;
                    696:        if(Value *valready=tables.get(name)) {
                    697:                // second+ appearence
                    698:                table=valready->get_table();
                    699:        } else {
                    700:                // first appearence
                    701:                Table::columns_type columns=new ArrayString(1);
                    702:                *columns+=new String("value");
                    703:                table=new Table(columns);
                    704:                tables.put(name, new VTable(table));
                    705:        }
                    706:        // this string becomes next row
                    707:        ArrayString& row=*new ArrayString(1);
                    708:        row+=&value;
                    709:        *table+=&row;
                    710: }
                    711: 
1.1       paf       712: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.72      moko      713: File_read_http_result pa_internal_file_read_http(Request& r, const String& file_spec, bool as_text, HashStringValue *options, bool transcode_text_result) {
1.1       paf       714:        File_read_http_result result;
1.20      misha     715:        char host[MAX_STRING];
1.66      moko      716:        const char *idna_host;
1.1       paf       717:        const char* uri; 
1.49      moko      718:        short port=80;
1.10      misha     719:        const char* method="GET";
1.21      misha     720:        bool method_is_get=true;
1.1       paf       721:        HashStringValue* form=0;
                    722:        int timeout_secs=2;
                    723:        bool fail_on_status_ne_200=true;
1.12      misha     724:        bool omit_post_charset=false;
1.1       paf       725:        Value* vheaders=0;
1.10      misha     726:        Value* vcookies=0;
1.11      misha     727:        Value* vbody=0;
1.72      moko      728:        Charset* asked_remote_charset=0;
1.58      moko      729:        Charset* real_remote_charset=0;
1.1       paf       730:        const char* user_cstr=0;
                    731:        const char* password_cstr=0;
1.22      misha     732:        const char* encode=0;
                    733:        bool multipart=false;
1.1       paf       734: 
                    735:        if(options) {
                    736:                int valid_options=pa_get_valid_file_options_count(*options);
                    737: 
                    738:                if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
                    739:                        valid_options++;
1.21      misha     740:                        method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
                    741:                        method_is_get=strcmp(method, "GET")==0;
1.1       paf       742:                }
1.22      misha     743:                if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
                    744:                        valid_options++;
                    745:                        encode=vencode->as_string().cstr();
                    746:                }
1.1       paf       747:                if(Value* vform=options->get(HTTP_FORM_NAME)) {
                    748:                        valid_options++;
                    749:                        form=vform->get_hash(); 
                    750:                } 
1.11      misha     751:                if(vbody=options->get(HTTP_BODY_NAME)) {
1.1       paf       752:                        valid_options++;
                    753:                } 
                    754:                if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
                    755:                        valid_options++;
                    756:                        timeout_secs=vtimeout->as_int(); 
                    757:                } 
1.11      misha     758:                if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1       paf       759:                        valid_options++;
                    760:                } 
1.11      misha     761:                if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10      misha     762:                        valid_options++;
                    763:                } 
1.1       paf       764:                if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
                    765:                        valid_options++;
                    766:                        fail_on_status_ne_200=!vany_status->as_bool(); 
1.12      misha     767:                }
1.20      misha     768:                if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12      misha     769:                        valid_options++;
                    770:                        omit_post_charset=vomit_post_charset->as_bool();
                    771:                }
1.6       misha     772:                if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.77      moko      773:                        asked_remote_charset=&pa_charsets.get(vcharset_name->as_string());
1.58      moko      774:                } 
                    775:                if(Value* vresponse_charset_name=options->get(PA_RESPONSE_CHARSET_NAME)) {
1.61      moko      776:                        valid_options++;
1.77      moko      777:                        real_remote_charset=&pa_charsets.get(vresponse_charset_name->as_string());
1.1       paf       778:                } 
                    779:                if(Value* vuser=options->get(HTTP_USER)) {
                    780:                        valid_options++;
                    781:                        user_cstr=vuser->as_string().cstr();
                    782:                } 
                    783:                if(Value* vpassword=options->get(HTTP_PASSWORD)) {
                    784:                        valid_options++;
                    785:                        password_cstr=vpassword->as_string().cstr();
                    786:                }
                    787: 
                    788:                if(valid_options!=options->count())
1.46      misha     789:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       paf       790:        }
                    791:        if(!asked_remote_charset) // defaulting to $request:charset
1.22      misha     792:                asked_remote_charset=&(r.charsets).source();
                    793: 
                    794:        if(encode){
                    795:                if(method_is_get)
1.127     moko      796:                        throw Exception(PARSER_RUNTIME, 0, "you cannot use $." HTTP_FORM_ENCTYPE_NAME " option with method GET");
1.22      misha     797: 
                    798:                multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
                    799: 
                    800:                if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
1.72      moko      801:                        throw Exception(PARSER_RUNTIME, 0, "$." HTTP_FORM_ENCTYPE_NAME " option value can be " HTTP_CONTENT_TYPE_FORM_URLENCODED " or " HTTP_CONTENT_TYPE_MULTIPART_FORMDATA " only");
1.22      misha     802:        }
1.1       paf       803: 
1.11      misha     804:        if(vbody){
                    805:                if(method_is_get)
1.127     moko      806:                        throw Exception(PARSER_RUNTIME, 0, "you cannot use $." HTTP_BODY_NAME " option with method GET");
1.11      misha     807: 
                    808:                if(form)
1.127     moko      809:                        throw Exception(PARSER_RUNTIME, 0, "you cannot use options $." HTTP_BODY_NAME " and $." HTTP_FORM_NAME " together");
1.11      misha     810:        }
1.1       paf       811: 
                    812:        //preparing request
1.29      misha     813:        String& connect_string=*new String(file_spec);
1.1       paf       814: 
1.48      moko      815:        const char* request;
                    816:        size_t request_size;
1.1       paf       817:        {
                    818:                // influence URLencoding of tainted pieces to String::L_URI lang
1.22      misha     819:                Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1       paf       820: 
1.44      misha     821:                const char* connect_string_cstr=connect_string.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1       paf       822: 
                    823:                const char* current=connect_string_cstr;
                    824:                if(strncmp(current, "http://", 7)!=0)
1.72      moko      825:                        throw Exception(PARSER_RUNTIME, &connect_string, "does not start with http://"); //never
1.1       paf       826:                current+=7;
                    827: 
1.119     moko      828:                pa_strncpy(host, current, sizeof(host));
1.34      misha     829:                char* host_uri=lsplit(host, '/');
                    830:                uri=host_uri?current+(host_uri-1-host):"/";
                    831:                char* port_cstr=lsplit(host, ':');
1.49      moko      832:                
                    833:                if (port_cstr){
                    834:                        char* error_pos=0;
                    835:                        port=(short)strtol(port_cstr, &error_pos, 10);
                    836:                        if(port==0 || *error_pos)
                    837:                                throw Exception(PARSER_RUNTIME, &connect_string, "invalid port number '%s'", port_cstr);
                    838:                }
1.1       paf       839: 
1.66      moko      840:                idna_host=pa_idna_encode(host, r.charsets.source());
                    841: 
1.11      misha     842:                // making request head
1.1       paf       843:                String head;
1.11      misha     844:                head << method << " " << uri;
1.28      misha     845:                if(method_is_get && form)
                    846:                        head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11      misha     847: 
1.66      moko      848:                head <<" HTTP/1.0" CRLF "Host: "<< idna_host;
1.49      moko      849:                if (port != 80)
                    850:                        head << ":" << port_cstr;
                    851:                head << CRLF;
1.11      misha     852: 
1.71      moko      853:                char* boundary= multipart ? get_uuid_boundary() : 0;
1.22      misha     854: 
1.35      misha     855:                String user_headers;
                    856:                bool user_agent_specified=false;
                    857:                bool content_type_specified=false;
                    858:                bool content_type_url_encoded=false;
                    859:                if(vheaders && !vheaders->is_string()) { // allow empty
                    860:                        if(HashStringValue *headers=vheaders->get_hash()) {
                    861:                                Http_pass_header_info info={
                    862:                                        &(r.charsets),
                    863:                                        &user_headers,
                    864:                                        &user_agent_specified,
                    865:                                        &content_type_specified,
                    866:                                        &content_type_url_encoded};
                    867:                                headers->for_each<Http_pass_header_info*>(http_pass_header, &info); 
                    868:                        } else
1.72      moko      869:                                throw Exception(PARSER_RUNTIME, 0, "headers param must be hash"); 
1.35      misha     870:                };
                    871: 
1.48      moko      872:                const char* request_body=0;
1.22      misha     873:                size_t post_size=0;
                    874:                if(form && !method_is_get) {
1.38      misha     875:                        head << "Content-Type: " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
1.28      misha     876: 
                    877:                        if(!omit_post_charset)
                    878:                                head << "; charset=" << asked_remote_charset->NAME_CSTR();
                    879: 
1.22      misha     880:                        if(multipart) {
1.28      misha     881:                                head << "; boundary=" << boundary;
1.48      moko      882:                                request_body=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22      misha     883:                        } else {
1.48      moko      884:                                request_body=pa_form2string(*form, r.charsets);
                    885:                                post_size=strlen(request_body);
1.22      misha     886:                        }
1.28      misha     887:                        head << CRLF;
1.35      misha     888:                } else if(vbody) {
1.38      misha     889:                        // $.body was specified
1.35      misha     890:                        if(content_type_url_encoded){
1.36      misha     891:                                // transcode + url-encode
1.48      moko      892:                                request_body=vbody->as_string().untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.35      misha     893:                        } else {
1.36      misha     894:                                // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.72      moko      895:                                const String &sbody=vbody->as_string();
                    896:                                request_body=Charset::transcode(String::C(sbody.cstr(), sbody.length()), r.charsets.source(), *asked_remote_charset).str;
1.35      misha     897:                        }
1.48      moko      898:                        post_size=strlen(request_body);
1.1       paf       899:                }
                    900: 
                    901:                // http://www.ietf.org/rfc/rfc2617.txt
                    902:                if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.38      misha     903:                        head << "Authorization: " << *authorization_field_value << CRLF;
1.1       paf       904: 
1.35      misha     905:                head << user_headers;
                    906: 
1.1       paf       907:                if(!user_agent_specified) // defaulting
1.38      misha     908:                        head << "User-Agent: " DEFAULT_USER_AGENT CRLF;
1.1       paf       909: 
1.12      misha     910:                if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
1.72      moko      911:                        throw Exception(PARSER_RUNTIME, 0, "$.content-type can't be specified with method POST"); 
1.12      misha     912: 
1.11      misha     913:                if(vcookies && !vcookies->is_string()){ // allow empty
1.10      misha     914:                        if(HashStringValue* cookies=vcookies->get_hash()) {
1.37      misha     915:                                head << "Cookie: ";
1.35      misha     916:                                Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10      misha     917:                                cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info); 
                    918:                                head << CRLF;
                    919:                        } else
1.72      moko      920:                                throw Exception(PARSER_RUNTIME, 0, "cookies param must be hash");
1.10      misha     921:                }
                    922: 
1.48      moko      923:                if(request_body)
1.128     moko      924:                        head << "Content-Length: " << pa_uitoa(post_size) << CRLF;
1.48      moko      925:                
                    926:                head << CRLF;
                    927:                
                    928:                const char *request_head=head.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1       paf       929: 
1.48      moko      930:                if(request_body){
                    931:                        size_t head_size = strlen(request_head);
                    932:                        request_size=post_size + head_size;
                    933:                        char *ptr=(char *)pa_malloc_atomic(request_size);
                    934:                        memcpy(ptr, request_head, head_size);
                    935:                        memcpy(ptr+head_size, request_body, post_size);
                    936:                        request=ptr;
                    937:                } else {
                    938:                        request_size=strlen(request_head);
                    939:                        request=request_head;
                    940:                }
1.1       paf       941:        }
                    942:        
1.78      moko      943: 
1.97      moko      944:        HTTP_response response;
1.22      misha     945: 
1.28      misha     946:        // sending request
1.95      moko      947:        int status_code;
                    948:        ALTER_EXCEPTION_SOURCE(status_code=http_request(response, idna_host, port, request, request_size, timeout_secs, fail_on_status_ne_200), &connect_string);
1.78      moko      949: 
1.72      moko      950:        // processing results
1.78      moko      951:        char* raw_body=response.buf + response.body_offset;
                    952:        size_t raw_body_size=response.length - response.body_offset;
                    953: 
1.1       paf       954:        result.headers=new HashStringValue;
                    955:        VHash* vtables=new VHash;
1.133     moko      956:        HASH_PUT_CSTR(*result.headers, "tables", vtables);
1.72      moko      957: 
1.78      moko      958:        if (!real_remote_charset && !response.headers.content_type.is_empty())
                    959:                real_remote_charset=detect_charset(response.headers.content_type.cstr());
1.1       paf       960: 
1.72      moko      961:        if(as_text)
1.77      moko      962:                real_remote_charset=pa_charsets.checkBOM(raw_body, raw_body_size, real_remote_charset);
1.72      moko      963: 
                    964:        if (!real_remote_charset)
                    965:                real_remote_charset=asked_remote_charset; // never null
                    966: 
1.125     moko      967:        for(Array_iterator<HTTP_Headers::Header> i(response.headers.headers); i; ){
1.85      moko      968:                HTTP_Headers::Header header=i.next();
1.72      moko      969: 
                    970:                header.transcode(*real_remote_charset, r.charsets.source());
                    971: 
                    972:                String &header_value=*new String(header.value, String::L_TAINTED);
                    973: 
                    974:                tables_update(vtables->hash(), header.name, header_value);
                    975:                result.headers->put(header.name, new VString(header_value));
1.16      misha     976:        }
                    977: 
1.72      moko      978:        // filling $.cookies
1.89      moko      979:        if(vcookies=vtables->hash().get("SET-COOKIE"))
1.133     moko      980:                HASH_PUT_CSTR(*result.headers, HTTP_COOKIES_NAME, new VTable(parse_cookies(r, vcookies->get_table())));
1.72      moko      981: 
1.1       paf       982:        // output response
                    983:        String::C real_body=String::C(raw_body, raw_body_size);
1.16      misha     984: 
                    985:        if(as_text && transcode_text_result && raw_body_size) { // raw_body_size must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
1.22      misha     986:                real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.1       paf       987:        }
                    988: 
                    989:        result.str=const_cast<char *>(real_body.str); // hacking a little
                    990:        result.length=real_body.length;
1.16      misha     991: 
1.22      misha     992:        if(as_text && result.length)
                    993:                fix_line_breaks(result.str, result.length);
                    994: 
1.1       paf       995:        result.headers->put(file_status_name, new VInt(status_code));
1.16      misha     996: 
1.1       paf       997:        return result;
                    998: }
1.84      moko      999: 
                   1000: /* ********************** httpd *************************** */
                   1001: 
1.100     moko     1002: enum EscapeState {
                   1003:         Initial,
                   1004:         Default,
                   1005:         EscapeFirst,
                   1006:         EscapeSecond
                   1007: };
                   1008: 
                   1009: static bool check_uri(const char *uri){
                   1010:        EscapeState state=Initial;
1.120     moko     1011:        uint escapedValue=0;
1.100     moko     1012: 
                   1013:        const char *pattern="/../";
                   1014:        const char *pos=pattern;
                   1015: 
                   1016:        while(*uri){
                   1017:                uchar c=(uchar)*(uri++);
                   1018:                switch(state) {
                   1019:                        case Initial:
                   1020:                                if(c!='/')
                   1021:                                        return false;
                   1022:                                state=Default;
                   1023:                                break;
                   1024:                        case Default:
                   1025:                                if(c=='%'){
                   1026:                                        state=EscapeFirst;
                   1027:                                        continue;
                   1028:                                }
                   1029:                                if(c=='?')
                   1030:                                        return true;
                   1031:                                break;
                   1032:                        case EscapeFirst:
                   1033:                                if(isxdigit(c)){
                   1034:                                        state=EscapeSecond;
                   1035:                                        escapedValue=hex_value[c] << 4;
                   1036:                                        continue;
                   1037:                                }
                   1038:                                return false;
                   1039:                        case EscapeSecond:
                   1040:                                if(isxdigit(c)){
                   1041:                                        state=Default;
1.105     moko     1042:                                        c=(uchar)(escapedValue + hex_value[c]);
1.100     moko     1043: 
                   1044:                                        // implementing Apache AllowEncodedSlashes Off just in case
                   1045:                                        if(c=='/' || c=='\\')
                   1046:                                                return false;
                   1047: 
                   1048:                                        break;
                   1049:                                }
                   1050:                                return false;
                   1051:                }
                   1052: 
                   1053:                if(c==*pos || c=='\\' && *pos=='/'){
                   1054:                        if(!*(++pos))
                   1055:                                return false;
                   1056:                } else {
                   1057:                        pos=pattern;
                   1058:                }
                   1059:        }
                   1060:        return true;
                   1061: }
                   1062: 
1.84      moko     1063: class HTTPD_request : public HTTP_response {
                   1064: public:
                   1065:        const char *method;
                   1066:        const char *uri;
                   1067: 
1.97      moko     1068:        HTTPD_request() : HTTP_response(), method(NULL), uri(NULL){};
1.84      moko     1069: 
1.120     moko     1070:        ssize_t pa_recv(SOCKET sockfd, char *buf, size_t len);
1.103     moko     1071: 
1.120     moko     1072:        bool read(SOCKET sock, size_t size){
1.103     moko     1073:                if(length + size > buf_size)
                   1074:                        resize(buf_size * 2 + size);
                   1075:                ssize_t received_size=pa_recv(sock, buf + length, size);
                   1076:                if(received_size == 0)
                   1077:                        return false;
                   1078:                if(received_size < 0) {
                   1079:                        if(int no = pa_socks_errno())
1.111     moko     1080:                                throw Exception("httpd.read", 0, "error receiving request: %s (%d)", pa_socks_strerr(no), no);
1.103     moko     1081:                        return false;
                   1082:                }
                   1083:                length+=received_size;
                   1084:                buf[length]='\0';
                   1085:                return true;
                   1086:        }
                   1087: 
1.84      moko     1088:        const char *extract_method(char *method_line){
                   1089:                char* uri_start = strchr(method_line, ' ');
                   1090: 
                   1091:                if(!uri_start || uri_start == method_line)
                   1092:                        return NULL;
                   1093: 
                   1094:                char* uri_end=strchr(uri_start+1, ' ');
                   1095: 
                   1096:                if(!uri_end || uri_end == uri_start+1)
                   1097:                        return NULL;
                   1098: 
                   1099:                uri=pa_strdup(uri_start+1, uri_end-uri_start-1);
1.100     moko     1100:                if(!check_uri(uri))
                   1101:                        throw Exception("httpd.request", 0, "invalid uri '%s'", uri);
                   1102: 
1.84      moko     1103:                return str_upper(method_line, uri_start-method_line);
                   1104:        }
                   1105: 
1.103     moko     1106: 
1.120     moko     1107:        bool read_header(SOCKET);
                   1108:        size_t read_post(SOCKET, char *, size_t);
1.84      moko     1109: };
                   1110: 
                   1111: enum HTTPD_request_state {
                   1112:        HTTPD_METHOD,
                   1113:        HTTPD_HEADERS
                   1114: };
                   1115: 
1.138     moko     1116: // timeout on "void" connection is normal
                   1117: #define PA_RECV_TIMEOUT                                                                                        \
                   1118:        LOG(pa_log("httpd [%d] recv got %d sec timeout", sockfd, pa_httpd_timeout));                    \
                   1119:        if(length)                                                                                      \
                   1120:                throw Exception("httpd.timeout", 0, "timeout occurred while receiving request");        \
                   1121:        return 0;
                   1122: 
1.120     moko     1123: ssize_t HTTPD_request::pa_recv(SOCKET sockfd, char *buffer, size_t len){
1.111     moko     1124:        LOG(pa_log("httpd [%d] recv %d appending to %d ...", sockfd, len, length));
1.107     moko     1125: 
1.138     moko     1126: #ifdef PA_HAVE_ALARM
                   1127:        if(PA_USE_ALARM) signal(SIGALRM, timeout_handler);
                   1128:        if(PA_USE_ALARM && sigsetjmp(timeout_env, 1)) {
                   1129:                PA_RECV_TIMEOUT
1.103     moko     1130:        } else
1.107     moko     1131: #endif
1.103     moko     1132:        {
1.107     moko     1133:                ALARM(pa_httpd_timeout);
1.141     moko     1134:                ssize_t result=pa_sock_recv(sockfd, buffer, len);
1.107     moko     1135:                ALARM(0);
1.138     moko     1136:                if(result < 0 && sock_timed_out(pa_socks_errno())) {
                   1137:                        PA_RECV_TIMEOUT
                   1138:                }
1.111     moko     1139:                LOG(pa_log("httpd [%d] recv got %d bytes", sockfd, result));
1.112     moko     1140:                LOG(pa_log("httpd [%d] %s", sockfd, buffer));
1.103     moko     1141:                return result;
                   1142:        }
                   1143: }
                   1144: 
1.115     moko     1145: static bool valid_http_method(const char * method){
                   1146:        return method && (
                   1147:                !strcmp(method, "GET") ||
                   1148:                !strcmp(method, "HEAD") ||
                   1149:                !strcmp(method, "POST") ||
                   1150:                !strcmp(method, "PUT") ||
                   1151:                !strcmp(method, "DELETE") ||
                   1152:                !strcmp(method, "CONNECT") ||
                   1153:                !strcmp(method, "OPTIONS") ||
                   1154:                !strcmp(method, "TRACE") ||
                   1155:                !strcmp(method, "PATCH")
                   1156:        );
                   1157: }
                   1158: 
1.120     moko     1159: bool HTTPD_request::read_header(SOCKET sock) {
1.84      moko     1160:        enum HTTPD_request_state state = HTTPD_METHOD;
                   1161: 
                   1162:        size_t chunk_size = 0x400*4;
                   1163:        resize(chunk_size);
                   1164: 
                   1165:        while(read(sock, chunk_size)){
                   1166:                switch(state){
                   1167:                        case HTTPD_METHOD: {
                   1168:                                size_t method_size = first_line();
                   1169:                                if(!method_size)
                   1170:                                        break;
                   1171: 
                   1172:                                char *method_line = pa_strdup(buf, method_size);
                   1173:                                method = extract_method(method_line);
                   1174: 
1.115     moko     1175:                                if(!valid_http_method(method))
1.84      moko     1176:                                        throw Exception("httpd.method", new String(method ? method : method_line), "invalid request method");
                   1177:                                state = HTTPD_HEADERS;
                   1178:                        }
                   1179: 
                   1180:                        case HTTPD_HEADERS: {
                   1181:                                if(!body_start())
                   1182:                                        break;
                   1183: 
                   1184:                                parse_headers();
1.144     moko     1185: 
                   1186:                                if(length==body_offset){ // nothing but the headers (GET, websocket handshake), the buffer is no longer needed
                   1187:                                        buf=NULL;
                   1188:                                        length=body_offset=buf_size=0;
                   1189:                                }
1.110     moko     1190:                                return true;
1.84      moko     1191:                        }
                   1192:                }
                   1193:        }
                   1194: 
1.111     moko     1195:        if(!length){ // browsers open connections in advance and they will be empty unless user requests more pages
                   1196:                LOG(pa_log("httpd [%d] void request", sock));
1.110     moko     1197:                return false;
1.111     moko     1198:        }
1.110     moko     1199: 
1.84      moko     1200:        if(state == HTTPD_METHOD)
                   1201:                throw Exception("httpd.request", 0, "bad request from host - no method found (size=%u)", length);
                   1202: 
                   1203:        if(state == HTTPD_HEADERS){
                   1204:                parse_headers();
                   1205:                body_offset=length;
                   1206:        }
1.110     moko     1207: 
                   1208:        return true;
1.84      moko     1209: }
                   1210: 
1.120     moko     1211: size_t HTTPD_request::read_post(SOCKET sock, char *body, size_t max_bytes) {
1.87      moko     1212:        size_t total_read = min(length - body_offset, max_bytes);
1.144     moko     1213:        if(total_read)
                   1214:                memcpy(body, buf + body_offset, total_read);
1.87      moko     1215: 
                   1216:        while (total_read < max_bytes){
1.103     moko     1217:                ssize_t received_size = pa_recv(sock, body + total_read, max_bytes - total_read);
1.87      moko     1218:                if(received_size == 0)
                   1219:                        return total_read;
                   1220:                if(received_size < 0) {
                   1221:                        if(int no = pa_socks_errno())
1.111     moko     1222:                                throw Exception("httpd.read", new String(uri), "error receiving request body: %s (%d)", pa_socks_strerr(no), no);
1.87      moko     1223:                        return total_read;
                   1224:                }
                   1225:                total_read += received_size;
                   1226:        }
                   1227:        return total_read;
                   1228: }
                   1229: 
1.84      moko     1230: /* ********************************************************** */
                   1231: 
1.85      moko     1232: Array<HTTP_Headers::Header> &HTTPD_Connection::headers() {
1.84      moko     1233:        return request->headers.headers;
                   1234: }
                   1235: 
                   1236: const char *HTTPD_Connection::method() {
                   1237:        return request->method;
                   1238: }
                   1239: 
                   1240: const char *HTTPD_Connection::uri() {
                   1241:        return request->uri;
                   1242: }
                   1243: 
                   1244: const char *HTTPD_Connection::content_type() {
                   1245:        return request->headers.content_type.cstr();
                   1246: }
                   1247: 
                   1248: uint64_t HTTPD_Connection::content_length(){
                   1249:        return request->headers.content_length;
                   1250: }
                   1251: 
1.110     moko     1252: bool HTTPD_Connection::read_header(){
1.84      moko     1253:        request = new HTTPD_request();
1.111     moko     1254:        bool result = request->read_header(sock);
                   1255:        LOG(if(result){
                   1256:                pa_log("httpd [%d] got %s \"%s\"", sock, method(), uri());
                   1257:        })
                   1258:        return result;
1.84      moko     1259: }
                   1260: 
1.87      moko     1261: size_t HTTPD_Connection::read_post(char *body, size_t max_bytes) {
                   1262:        return request->read_post(sock, body, max_bytes);
                   1263: }
                   1264: 
1.90      moko     1265: size_t HTTPD_Connection::send_body(const void *buf, size_t size) {
1.112     moko     1266:        LOG(pa_log("httpd [%d] response %d bytes", sock, size));
                   1267:        LOG(pa_log("httpd [%d] %s", sock, buf));
1.131     moko     1268:        ssize_t result=pa_send(sock, (const char*)buf, size);
                   1269:        if(result < 0) {
1.90      moko     1270:                int no=pa_socks_errno();
1.111     moko     1271:                throw Exception("httpd.write", 0, "error sending response: %s (%d)", pa_socks_strerr(no), no);
1.90      moko     1272:        }
1.131     moko     1273:        return result;
1.90      moko     1274: }
                   1275: 
1.140     moko     1276: String::C HTTPD_Connection::unprocessed() {
                   1277:        return String::C(request->buf + request->body_offset, request->length - request->body_offset);
                   1278: }
                   1279: 
                   1280: size_t HTTPD_Connection::receive(char *dest, size_t max_bytes) {
1.141     moko     1281:        ssize_t received_size=pa_sock_recv(sock, dest, max_bytes);
1.140     moko     1282:        if(received_size < 0) {
                   1283:                int no=pa_socks_errno();
                   1284:                if(pa_socks_is_reset(no))
                   1285:                        return 0;
                   1286:                throw Exception("httpd.read", 0, "error receiving data: %s (%d)", pa_socks_strerr(no), no);
                   1287:        }
                   1288:        return received_size;
                   1289: }
                   1290: 
                   1291: void HTTPD_Connection::set_nodelay() {
                   1292:        int nodelay=1;
                   1293:        setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&nodelay, sizeof(nodelay));
                   1294: }
                   1295: 
                   1296: void HTTPD_Connection::set_send_timeout(int timeout_secs) {
                   1297:        set_socket_timeout(sock, SO_SNDTIMEO, timeout_secs);
                   1298: }
                   1299: 
1.93      moko     1300: HTTPD_Connection::~HTTPD_Connection(){
1.120     moko     1301:        if(sock != INVALID_SOCKET){
1.111     moko     1302:                LOG(pa_log("httpd [%d] closed", sock));
1.93      moko     1303:                closesocket(sock);
1.145     moko     1304:                HTTPD_Server::track_connection(-1);
1.111     moko     1305:        }
1.93      moko     1306: }
                   1307: 
1.120     moko     1308: bool HTTPD_Connection::accept(SOCKET server_sock, int timeout_value) {
1.139     moko     1309:        int ready = pa_sock_ready(server_sock, false, timeout_value);
1.93      moko     1310:        if (ready < 0) {
                   1311:                int no=pa_socks_errno();
                   1312:                throw Exception("httpd.accept", 0, "error waiting for connection: %s (%d)", pa_socks_strerr(no), no);
                   1313:        }
                   1314:        if (ready == 0)
                   1315:                return false; /* Timeout */
                   1316: 
                   1317:        struct sockaddr_in addr;
                   1318:        socklen_t sock_addr_len = sizeof(struct sockaddr_in);
                   1319:        memset(&addr, 0, sock_addr_len);
                   1320: 
1.146     moko     1321:        sock = PA_ACCEPT(server_sock, (struct sockaddr *)&addr, &sock_addr_len);
1.120     moko     1322:        if(sock == INVALID_SOCKET){
1.93      moko     1323:                int no=pa_socks_errno();
                   1324:                throw Exception("httpd.accept", 0, "error accepting connection: %s (%d)", pa_socks_strerr(no), no);
                   1325:        }
1.145     moko     1326:        HTTPD_Server::track_connection(1); // taken back by the owner
1.93      moko     1327: 
1.123     moko     1328: //     Has no positive performance effect, requires include <netinet/tcp.h>
                   1329: //     static int sock_on=1;
                   1330: //     setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&sock_on, sizeof(sock_on));
                   1331: 
1.138     moko     1332:        if(!PA_USE_ALARM)
                   1333:                set_socket_timeout(sock, SO_RCVTIMEO, pa_httpd_timeout);
                   1334: 
1.93      moko     1335:        remote_addr = pa_strdup(inet_ntoa(addr.sin_addr));
1.111     moko     1336:        LOG(pa_log("httpd [%d] accepted from %s", sock, remote_addr));
1.93      moko     1337:        return true;
                   1338: }
1.84      moko     1339: 
1.107     moko     1340: HTTPD_Server::HTTPD_MODE HTTPD_Server::mode = HTTPD_Server::SEQUENTIAL;
1.114     moko     1341: const char *HTTPD_Server::port=NULL;
1.145     moko     1342: int HTTPD_Server::max_connections=INT_MAX;
                   1343: int HTTPD_Server::connections=0;
                   1344: 
                   1345: void HTTPD_Server::track_connection(int delta){
                   1346:        SYNCHRONIZED;
                   1347:        connections+=delta;
                   1348: }
1.106     moko     1349: 
1.108     moko     1350: void HTTPD_Server::set_mode(const String &value){
                   1351:                 if(value == "sequental") mode = SEQUENTIAL;
1.113     moko     1352: #ifdef HAVE_TLS
1.108     moko     1353:                 else if (value == "threaded") mode = MULTITHREADED;
1.113     moko     1354: #endif
1.108     moko     1355: #ifdef _MSC_VER
1.117     moko     1356:                else throw Exception("httpd.mode", &value, "$MAIN:HTTPD.mode must be 'sequental' or 'threaded'");
1.108     moko     1357: #else
                   1358:                 else if (value == "parallel") mode = PARALLEL;
1.117     moko     1359:                else throw Exception("httpd.mode", &value, "$MAIN:HTTPD.mode must be 'sequental', 'parallel' or 'threaded'");
1.108     moko     1360: #endif
                   1361: }
                   1362: 
1.120     moko     1363: SOCKET HTTPD_Server::bind(const char *host_port){
1.84      moko     1364:        struct sockaddr_in me;
                   1365: 
1.114     moko     1366:        port = strchr(host_port, ':');
1.86      moko     1367:        const char *host = NULL;
1.116     moko     1368:        if(port){
1.114     moko     1369:                if(port > host_port)
                   1370:                        host = pa_strdup(host_port, port - host_port);
1.86      moko     1371:                port += 1;
                   1372:        } else {
                   1373:                port = host_port;
                   1374:        }
                   1375: 
1.105     moko     1376:        if(!set_addr(&me, host, (short)pa_atoui(port))){
1.84      moko     1377:                if (host)
1.127     moko     1378:                        throw Exception("httpd.bind", 0, "cannot resolve hostname \"%s\"", host);
1.84      moko     1379:                me.sin_addr.s_addr=INADDR_ANY;
                   1380:        }
                   1381: 
1.146     moko     1382:        SOCKET sock = PA_SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/);
1.84      moko     1383: 
1.120     moko     1384:        if(sock == INVALID_SOCKET){
1.84      moko     1385:                int no=pa_socks_errno();
1.127     moko     1386:                throw Exception("httpd.bind", 0, "cannot make socket: %s (%d)", pa_socks_strerr(no), no);
1.84      moko     1387:        }
                   1388: 
1.93      moko     1389:        static int sock_on = 1;
                   1390: 
1.84      moko     1391:        if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&sock_on, sizeof(sock_on)) ||
                   1392:            setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&sock_on, sizeof(sock_on)) ||
                   1393:            ::bind(sock, (struct sockaddr*)&me, sizeof(me)) ||
1.143     moko     1394:            listen(sock, 511)) { // same default as in apache/nginx
1.89      moko     1395:                closesocket(sock);
1.84      moko     1396:                int no = pa_socks_errno();
1.127     moko     1397:                throw Exception("httpd.bind", 0, "cannot bind socket: %s (%d)", pa_socks_strerr(no), no);
1.84      moko     1398:        }
                   1399:        return sock;
                   1400: }

E-mail: