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

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

E-mail: