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

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

E-mail: