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

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

E-mail: