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

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

E-mail: