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

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

E-mail: