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

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

E-mail: