Annotation of parser3/src/main/pa_common.C, revision 1.181

1.15      paf         1: /** @file
1.16      paf         2:        Parser: commonly functions.
                      3: 
1.174     paf         4:        Copyright(c) 2001-2004 ArtLebedev Group (http://www.artlebedev.com)
1.101     paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.111     paf         6: */
1.16      paf         7: 
1.181   ! paf         8: static const char * const IDENT_COMMON_C="$Date: 2004/03/05 15:14:47 $"; 
1.1       paf         9: 
                     10: #include "pa_common.h"
1.4       paf        11: #include "pa_exception.h"
1.154     paf        12: #include "pa_hash.h"
1.14      paf        13: #include "pa_globals.h"
1.154     paf        14: #include "pa_request_charsets.h"
                     15: #include "pa_charsets.h"
                     16: 
                     17: #define PA_HTTP
                     18: 
                     19: #ifdef PA_HTTP
1.126     paf        20: #include "pa_vstring.h"
1.154     paf        21: #include "pa_vint.h"
1.155     paf        22: #include "pa_vhash.h"
                     23: #include "pa_vtable.h"
1.154     paf        24: 
                     25: #ifdef CYGWIN
                     26: #define _GNU_H_WINDOWS32_SOCKETS
                     27: // for PASCAL
                     28: #include <windows.h>
                     29: // SOCKET
                     30: typedef u_int  SOCKET;
                     31: int PASCAL closesocket(SOCKET);
                     32: #else
                     33: #      if defined(WIN32)
                     34: #              include <windows.h>
                     35: #      else
                     36: #              define closesocket close
                     37: #      endif
                     38: #endif
1.1       paf        39: 
1.126     paf        40: #else
1.154     paf        41: 
                     42: #      if defined(WIN32)
                     43: #              include <windows.h>
                     44: #      endif
                     45: 
1.98      paf        46: #endif
                     47: 
1.93      paf        48: // some maybe-undefined constants
                     49: 
1.82      paf        50: #ifndef _O_TEXT
                     51: #      define _O_TEXT 0
                     52: #endif
                     53: #ifndef _O_BINARY
                     54: #      define _O_BINARY 0
1.47      paf        55: #endif
1.80      paf        56: 
1.138     paf        57: #ifdef HAVE_FTRUNCATE
                     58: #      define PA_O_TRUNC 0
                     59: #else
                     60: #      ifdef _O_TRUNC
                     61: #              define PA_O_TRUNC _O_TRUNC
                     62: #      else
                     63: #              error you must have either ftruncate function or _O_TRUNC bit declared
                     64: #      endif
1.154     paf        65: #endif
1.176     paf        66: 
                     67: #      ifndef INADDR_NONE
                     68: #              define INADDR_NONE ((ulong) -1)
                     69: #      endif
1.154     paf        70: 
                     71: // defines for globals
                     72: 
                     73: #define FILE_STATUS_NAME  "status"
                     74: 
                     75: // globals
                     76: 
                     77: const String file_status_name(FILE_STATUS_NAME);
                     78: 
1.178     paf        79: // defines
1.154     paf        80: 
                     81: #define HTTP_METHOD_NAME  "method"
1.180     paf        82: #define HTTP_FORM_NAME  "form"
                     83: #define HTTP_BODY_NAME  "body"
1.154     paf        84: #define HTTP_TIMEOUT_NAME    "timeout"
                     85: #define HTTP_HEADERS_NAME "headers"
                     86: #define HTTP_ANY_STATUS_NAME "any-status"
                     87: #define HTTP_CHARSET_NAME "charset"
1.155     paf        88: #define HTTP_TABLES_NAME "tables"
1.178     paf        89: #define HTTP_USER "user"
                     90: #define HTTP_PASSWORD "password"
1.154     paf        91: 
                     92: // defines
                     93: 
1.127     paf        94: #define DEFAULT_USER_AGENT "parser3"
                     95: 
1.154     paf        96: // functions
1.127     paf        97: 
1.154     paf        98: void fix_line_breaks(char *str, size_t& length) {
1.87      paf        99:        //_asm int 3;
1.154     paf       100:        const char* const eob=str+length;
                    101:        char* dest=str;
1.72      parser    102:        // fix DOS: \r\n -> \n
                    103:        // fix Macintosh: \r -> \n
1.154     paf       104:        char* bol=str;
1.137     paf       105:        while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72      parser    106:                size_t len=eol-bol;
                    107:                if(dest!=bol)
1.126     paf       108:                        memcpy(dest, bol, len); 
1.72      parser    109:                dest+=len;
1.126     paf       110:                *dest++='\n'; 
1.72      parser    111: 
1.126     paf       112:                if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72      parser    113:                        bol=eol+2;
1.154     paf       114:                        length--; 
1.126     paf       115:                } else // \r, not \n = Macintosh
1.72      parser    116:                        bol=eol+1;
                    117:        }
1.154     paf       118:        // last piece without \r
1.72      parser    119:        if(dest!=bol)
1.126     paf       120:                memcpy(dest, bol, eob-bol); 
1.154     paf       121:        str[length]=0; // terminating
1.72      parser    122: }
1.18      paf       123: 
1.154     paf       124: char* file_read_text(Request_charsets& charsets, 
                    125:                     const String& file_spec, 
                    126:                     bool fail_on_read_problem,
                    127:                     HashStringValue* params/*, HashStringValue* * out_fields*/) {
                    128:        File_read_result file=
                    129:                file_read(charsets, file_spec, true, params, fail_on_read_problem);
                    130:        return file.success?file.str:0;
1.126     paf       131: }
                    132: 
1.178     paf       133: //http request stuff
1.154     paf       134: #ifdef PA_HTTP
                    135: 
                    136: #undef CRLF
                    137: #define CRLF "\r\n"
1.126     paf       138: 
                    139: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
                    140:     memset(addr, 0, sizeof(*addr)); 
                    141:     addr->sin_family=AF_INET;
                    142:     addr->sin_port=htons(port); 
                    143:     if(host) {
1.175     paf       144:                ulong packed_ip=inet_addr(host);
                    145:                struct hostent *hostIP = packed_ip==INADDR_NONE?
                    146:                        gethostbyname(host)
                    147:                        : gethostbyaddr((char *)&packed_ip, sizeof(packed_ip), AF_INET);
                    148:                if(hostIP) 
1.126     paf       149:                        memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length); 
                    150:                else
                    151:                        return false;
                    152:     } else 
                    153:                addr->sin_addr.s_addr=INADDR_ANY;
                    154:     return true;
                    155: }
                    156: 
1.171     paf       157: static int http_read_response(char*& response, size_t& response_size, int sock, bool fail_on_status_ne_200){
                    158:        response=(char*)pa_malloc_atomic(1/*terminator*/); // setting memory block type
                    159:        response[(response_size=0)]=0;
1.154     paf       160:        int result=0;
1.171     paf       161:        char* EOLat=0;
1.126     paf       162:        while(true) {
1.171     paf       163:                char buf[MAX_STRING*10]; 
                    164:                ssize_t received_size=recv(sock, buf, sizeof(buf), 0); 
                    165:                if(received_size<=0)
1.126     paf       166:                        break;
1.171     paf       167:                response=(char*)pa_realloc(response, response_size+received_size+1/*terminator*/);
                    168:                memcpy(response+response_size, buf, received_size);
                    169:                response_size+=received_size;
                    170:                response[response_size]=0;
                    171: 
                    172:                if(!result && (EOLat=strstr(response, CRLF))) { // checking status in first response
                    173:                        const String status_line(pa_strdup(response, EOLat-response));
1.154     paf       174:                        ArrayString astatus; 
                    175:                        size_t pos_after=0;
                    176:                        status_line.split(astatus, pos_after, " "); 
                    177:                        const String& status_code=*astatus.get(1);
                    178:                        result=status_code.as_int(); 
1.142     paf       179: 
1.154     paf       180:                        if(fail_on_status_ne_200 && result!=200)
1.142     paf       181:                                throw Exception("http.status",
1.154     paf       182:                                        &status_code,
1.142     paf       183:                                        "invalid HTTP response status");
                    184:                }
                    185:        }
1.154     paf       186:        if(result)
                    187:                return result;
1.142     paf       188:        else
                    189:                throw Exception("http.response",
                    190:                        0,
1.173     paf       191:                        "bad response from host - no status found (size=%u)", response_size); 
1.126     paf       192: }
                    193: 
                    194: /* ********************** request *************************** */
                    195: 
                    196: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
1.145     paf       197: #      define PA_USE_ALARM
1.126     paf       198: #endif
                    199: 
1.145     paf       200: #ifdef PA_USE_ALARM
1.126     paf       201: static sigjmp_buf timeout_env;
                    202: static void timeout_handler(int sig){
                    203:     siglongjmp(timeout_env, 1); 
                    204: }
                    205: #endif
                    206: 
1.171     paf       207: static int http_request(char*& response, size_t& response_size,
1.152     paf       208:                        const char* host, int port, 
                    209:                        const char* request, 
1.166     paf       210:                        int 
                    211: #ifdef PA_USE_ALARM
                    212:                        timeout
                    213: #endif
                    214:                        ,
1.152     paf       215:                        bool fail_on_status_ne_200) {
1.126     paf       216:        if(!host)
                    217:                throw Exception("http.host", 
1.154     paf       218:                        0, 
1.126     paf       219:                        "zero hostname");  //never
                    220: 
1.145     paf       221: #ifdef PA_USE_ALARM
1.146     paf       222:        signal(SIGALRM, timeout_handler); 
1.126     paf       223: #endif
                    224:        int sock=-1;
1.145     paf       225: #ifdef PA_USE_ALARM
                    226:        if(sigsetjmp(timeout_env, 1)) {
                    227:                // stupid gcc [2.95.4] generated bad code
                    228:                // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
                    229:                // rewritten simplier [though duplicating closesocket code]
                    230:                if(sock>=0) 
                    231:                        closesocket(sock); 
                    232:                throw Exception("http.timeout", 
                    233:                        origin_string, 
                    234:                        "timeout occured while retrieving document"); 
1.146     paf       235:                return 0; // never
1.145     paf       236:        } else {
                    237:                alarm(timeout); 
                    238: #endif
1.146     paf       239:                try {
                    240:                        int result;
1.126     paf       241:                        struct sockaddr_in dest;
1.154     paf       242:                
                    243:                        if(!set_addr(&dest, host, port))
1.126     paf       244:                                throw Exception("http.host", 
1.154     paf       245:                                        0, 
1.127     paf       246:                                        "can not resolve hostname \"%s\"", host); 
1.126     paf       247:                        
                    248:                        if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0)
                    249:                                throw Exception("http.connect", 
1.154     paf       250:                                        0, 
1.127     paf       251:                                        "can not make socket: %s (%d)", strerror(errno), errno); 
1.126     paf       252:                        if(connect(sock, (struct sockaddr *)&dest, sizeof(dest)))
                    253:                                throw Exception("http.connect", 
1.154     paf       254:                                        0, 
1.127     paf       255:                                        "can not connect to host \"%s\": %s (%d)", host, strerror(errno), errno); 
1.126     paf       256:                        size_t request_size=strlen(request);
                    257:                        if(send(sock, request, request_size, 0)!=(ssize_t)request_size)
                    258:                                throw Exception("http.connect", 
1.154     paf       259:                                        0, 
1.127     paf       260:                                        "error sending request: %s (%d)", strerror(errno), errno); 
1.126     paf       261: 
1.171     paf       262:                        result=http_read_response(response, response_size, sock, fail_on_status_ne_200); 
1.142     paf       263:                        closesocket(sock); 
1.145     paf       264: #ifdef PA_USE_ALARM
1.142     paf       265:                        alarm(0)1.126     paf       266: #endif
1.147     paf       267:                        return result;
1.146     paf       268:                } catch(...) {
1.145     paf       269: #ifdef PA_USE_ALARM
1.146     paf       270:                        alarm(0)1.126     paf       271: #endif
1.146     paf       272:                        if(sock>=0) 
                    273:                                closesocket(sock); 
1.154     paf       274:                        rethrow;
1.146     paf       275:                }
1.148     paf       276: #ifdef PA_USE_ALARM
1.126     paf       277:        }
1.148     paf       278: #endif
1.126     paf       279: }
                    280: 
1.127     paf       281: #ifndef DOXYGEN
                    282: struct Http_pass_header_info {
1.154     paf       283:        Request_charsets* charsets;
1.127     paf       284:        String* request;
                    285:        bool user_agent_specified;
                    286: };
                    287: #endif
1.154     paf       288: static void http_pass_header(HashStringValue::key_type key, 
                    289:                             HashStringValue::value_type value, 
                    290:                             Http_pass_header_info *info) {
                    291:     *info->request <<key<<": "
                    292:        << attributed_meaning_to_string(*value, String::L_HTTP_HEADER, false)
                    293:        << CRLF; 
1.135     paf       294:        
1.154     paf       295:     if(String(key, String::L_TAINTED).change_case(info->charsets->source(), String::CC_UPPER)=="USER-AGENT")
                    296:        info->user_agent_specified=true;
1.126     paf       297: }
1.154     paf       298: 
                    299: 
                    300: static Charset* detect_charset(Charset& source_charset, const String& content_type_value) {
1.156     paf       301:        const String::Body CONTENT_TYPE_VALUE=
1.154     paf       302:                content_type_value.change_case(source_charset, String::CC_UPPER);
                    303:        // content-type: xxx/xxx; source_charset=WE-NEED-THIS
                    304:        // content-type: xxx/xxx; source_charset="WE-NEED-THIS"
                    305:        // content-type: xxx/xxx; source_charset="WE-NEED-THIS";
                    306:        size_t before_charseteq_pos=CONTENT_TYPE_VALUE.pos("CHARSET=");
                    307:        if(before_charseteq_pos!=STRING_NOT_FOUND) {
                    308:                size_t charset_begin=before_charseteq_pos+8/*CHARSET="*/;
                    309:                size_t open_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
                    310:                bool quoted=open_quote_pos==charset_begin;
                    311:                if(quoted)
                    312:                        charset_begin++; // skip opening '"'
                    313:                size_t charset_end=CONTENT_TYPE_VALUE.length();
                    314:                if(quoted) {
                    315:                        size_t close_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
                    316:                        if(close_quote_pos!=STRING_NOT_FOUND)
                    317:                                charset_end=close_quote_pos;
                    318:                } else {
                    319:                        size_t delim_pos=CONTENT_TYPE_VALUE.pos(';', charset_begin);
                    320:                        if(delim_pos!=STRING_NOT_FOUND)
                    321:                                charset_end=delim_pos;
                    322:                }
1.156     paf       323:                const String::Body CHARSET_NAME_BODY=
1.154     paf       324:                        CONTENT_TYPE_VALUE.mid(charset_begin, charset_end);
                    325: 
                    326:                return &charsets.get(CHARSET_NAME_BODY);
                    327:        }
                    328: 
                    329:        return 0;
                    330: }
                    331: 
1.178     paf       332: static const String* basic_authorization_field(const char* user, const char* pass) {
                    333:        if(!user&& !pass)
                    334:                return 0;
                    335: 
                    336:        String combined;  
                    337:        if(user)
                    338:                combined<<user;
                    339:        combined<<":";
                    340:        if(pass)
                    341:                combined<<pass;
                    342:        
                    343:        String* result=new String("Basic "); *result<<pa_base64(combined.cstr(), combined.length());
                    344:        return result;
                    345: }
1.154     paf       346: 
1.181   ! paf       347: static void form_string_value2string(
        !           348:                                                                  HashStringValue::key_type key, 
        !           349:                                                                  const String& value, 
        !           350:                                                                  String& result) 
        !           351: {
        !           352:        result << String(key, String::L_TAINTED) << "=";
        !           353:        result.append(value, String::L_URI, true);
        !           354:        result<< "&";
        !           355: }
        !           356: #ifndef DOXYGEN
        !           357: struct Form_table_value2string_info {
        !           358:        HashStringValue::key_type key;
        !           359:        String& result;
        !           360: 
        !           361:        Form_table_value2string_info(HashStringValue::key_type akey, String& aresult): 
        !           362:                key(akey), result(aresult) {}
        !           363: };
        !           364: #endif
        !           365: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
        !           366:        form_string_value2string(info->key, *row->get(0), info->result);
        !           367: }
1.180     paf       368: static void form_value2string(
                    369:                                                                  HashStringValue::key_type key, 
                    370:                                                                  HashStringValue::value_type value, 
                    371:                                                                  String* result) 
                    372: {
1.181   ! paf       373:        if(const String* svalue=value->get_string())
        !           374:                form_string_value2string(key, *svalue, *result);
        !           375:        else if(Table* tvalue=value->get_table()) {
        !           376:                Form_table_value2string_info info(key, *result);
        !           377:                tvalue->for_each(form_table_value2string, &info);
        !           378:        } else
        !           379:                throw Exception(0,
        !           380:                        new String(key, String::L_TAINTED),
        !           381:                        "is %s, "HTTP_FORM_NAME" option value must either string or table", value->type());
1.180     paf       382: }
                    383: static const char* form2string(HashStringValue& form) {
                    384:        String string;
                    385:        form.for_each(form_value2string, &string);
1.181   ! paf       386:        return string.cstr(String::L_UNSPECIFIED);
1.180     paf       387: }
1.154     paf       388: #ifndef DOXYGEN
                    389: struct File_read_http_result {
                    390:        char *str; size_t length;
                    391:        HashStringValue* headers;
                    392: }; 
                    393: #endif
1.155     paf       394: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.154     paf       395: static File_read_http_result file_read_http(Request_charsets& charsets, 
                    396:                                            const String& file_spec, 
1.169     paf       397:                                            bool as_text,
                    398:                                                HashStringValue *options=0) {
1.154     paf       399:        File_read_http_result result;
1.126     paf       400:        char host[MAX_STRING]; 
1.129     paf       401:        const char* uri; 
1.126     paf       402:        int port;
1.180     paf       403:        const char* method="GET"; bool method_is_get;
                    404:        HashStringValue* form=0;
                    405:        const char* body_cstr=0;
1.126     paf       406:        int timeout=2;
1.142     paf       407:        bool fail_on_status_ne_200=true;
1.154     paf       408:        Value* vheaders=0;
                    409:        Charset *asked_remote_charset=0;
1.178     paf       410:        const char* user_cstr=0;
                    411:        const char* password_cstr=0;
1.126     paf       412: 
1.127     paf       413:        if(options) {
                    414:                int valid_options=0;
1.177     paf       415:                if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
1.127     paf       416:                        valid_options++;
1.154     paf       417:                        method=vmethod->as_string().cstr();
1.181   ! paf       418:                }
        !           419:                if(Value* vform=options->get(HTTP_FORM_NAME)) {
1.180     paf       420:                        valid_options++;
                    421:                        form=vform->get_hash(); 
1.181   ! paf       422:                } 
        !           423:                if(Value* vbody=options->get(HTTP_BODY_NAME)) {
1.180     paf       424:                        valid_options++;
                    425:                        body_cstr=vbody->as_string().cstr(String::L_UNSPECIFIED);
1.181   ! paf       426:                } 
        !           427:                if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
1.127     paf       428:                        valid_options++;
                    429:                        timeout=vtimeout->as_int(); 
1.181   ! paf       430:                } 
        !           431:                if((vheaders=options->get(HTTP_HEADERS_NAME))) {
1.127     paf       432:                        valid_options++;
1.181   ! paf       433:                } 
        !           434:                if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
1.142     paf       435:                        valid_options++;
                    436:                        fail_on_status_ne_200=!vany_status->as_bool(); 
1.181   ! paf       437:                } 
        !           438:                if(Value* vcharset_name=options->get(HTTP_CHARSET_NAME)) {
1.154     paf       439:                        valid_options++;
                    440:                        asked_remote_charset=&::charsets.get(vcharset_name->as_string().
                    441:                                change_case(charsets.source(), String::CC_UPPER));
1.181   ! paf       442:                } 
        !           443:                if(Value* vuser=options->get(HTTP_USER)) {
1.178     paf       444:                        valid_options++;
                    445:                        user_cstr=vuser->as_string().cstr();
1.181   ! paf       446:                } 
        !           447:                if(Value* vpassword=options->get(HTTP_PASSWORD)) {
1.178     paf       448:                        valid_options++;
                    449:                        password_cstr=vpassword->as_string().cstr();
                    450:                }
1.142     paf       451: 
1.154     paf       452:                if(valid_options!=options->count())
1.127     paf       453:                        throw Exception("parser.runtime",
                    454:                                0,
                    455:                                "invalid option passed");
1.154     paf       456:        }
                    457:        if(!asked_remote_charset) // defaulting to $request:charset
                    458:                asked_remote_charset=&charsets.source();
                    459: 
1.180     paf       460:        method_is_get=strcmp(method, "GET")==0;
                    461:        if(method_is_get && body_cstr)
                    462:                throw Exception("parser.runtime",
                    463:                        0,
                    464:                        "you can not use $."HTTP_BODY_NAME" option with method GET");
                    465: 
1.154     paf       466:        //preparing request
                    467:        String& connect_string=*new String;
                    468:        // not in ^sql{... L_SQL ...} spirit, but closer to ^file::load one
                    469:        connect_string.append(file_spec, String::L_URI); // tainted pieces -> URI pieces
                    470: 
1.180     paf       471:        String request_head_and_body;
1.154     paf       472:        {
                    473:                // influence URLencoding of tainted pieces to String::L_URI lang
                    474:                Temp_client_charset temp(charsets, *asked_remote_charset);
                    475: 
                    476:                const char* connect_string_cstr=connect_string.cstr(String::L_UNSPECIFIED); 
1.126     paf       477: 
1.154     paf       478:                const char* current=connect_string_cstr;
                    479:                if(strncmp(current, "http://", 7)!=0)
                    480:                        throw Exception(0, 
                    481:                                &connect_string, 
                    482:                                "does not start with http://"); //never
                    483:                current+=7;
                    484: 
                    485:                strncpy(host, current, sizeof(host)-1);  host[sizeof(host)-1]=0;
                    486:                char* host_uri=lsplit(host, '/'); 
                    487:                uri=host_uri?current+(host_uri-1-host):"/"; 
                    488:                char* port_cstr=lsplit(host, ':'); 
                    489:                char* error_pos=0;
                    490:                port=port_cstr?strtol(port_cstr, &error_pos, 0):80;
                    491: 
1.180     paf       492:                if(strchr(uri, '?') && form)
                    493:                        throw Exception("parser.runtime",
                    494:                                0,
                    495:                                "use either uri with ?params or $."HTTP_FORM_NAME" option");
                    496: 
                    497:                //making request head
                    498:                String head;
                    499:                head << method;
                    500:                head << " " << uri;
                    501:                if(form)
                    502:                        if(method_is_get)
1.181   ! paf       503:                                head << "?" << form2string(*form);
1.180     paf       504:                head <<" HTTP/1.0" CRLF
1.154     paf       505:                        "host: "<< host << CRLF; 
1.181   ! paf       506:                if(form && !method_is_get) {
        !           507:                        head << "content-type: application/x-www-form-urlencoded" CRLF;
        !           508:                        body_cstr = form2string(*form);
        !           509:                }
1.178     paf       510: 
1.179     paf       511:                // http://www.ietf.org/rfc/rfc2617.txt
1.178     paf       512:                if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.180     paf       513:                        head<<"authorization: "<<*authorization_field_value<<CRLF;
1.178     paf       514: 
1.154     paf       515:                bool user_agent_specified=false;
                    516:                if(vheaders && !vheaders->is_string()) { // allow empty
                    517:                        if(HashStringValue *headers=vheaders->get_hash()) {
1.180     paf       518:                                Http_pass_header_info info={&charsets, &head, false};
1.154     paf       519:                                headers->for_each(http_pass_header, &info); 
                    520:                                user_agent_specified=info.user_agent_specified;
                    521:                        } else
                    522:                                throw Exception("parser.runtime", 
                    523:                                        &connect_string,
                    524:                                        "headers param must be hash"); 
                    525:                };
                    526:                if(!user_agent_specified) // defaulting
1.180     paf       527:                        head << "user-agent: " DEFAULT_USER_AGENT CRLF;
                    528: 
                    529:                if(body_cstr) {
                    530:                        // recode those pieces which are not in String::L_URI lang 
                    531:                        // [those violating HTTP standard, but widly used]
                    532:                        body_cstr=Charset::transcode(
                    533:                                String::C(body_cstr, strlen(body_cstr)),
                    534:                                charsets.source(),
                    535:                                *asked_remote_charset);
1.181   ! paf       536: 
        !           537:                        head << "content-length: " << format(strlen(body_cstr), "%u") << CRLF;
1.180     paf       538:                }
1.154     paf       539: 
1.181   ! paf       540:                const char* head_cstr=head.cstr(String::L_UNSPECIFIED);
        !           541: 
        !           542:                // recode those pieces which are not in String::L_URI lang 
        !           543:                // [those violating HTTP standard, but widly used]
        !           544:                head_cstr=Charset::transcode(
        !           545:                        String::C(head_cstr, strlen(head_cstr)),
        !           546:                        charsets.source(),
        !           547:                        *asked_remote_charset);
1.180     paf       548: 
1.181   ! paf       549:                // head + end of header
        !           550:                request_head_and_body << head_cstr << CRLF;
1.180     paf       551:                // body
                    552:                if(body_cstr)
                    553:                        request_head_and_body << body_cstr;
1.154     paf       554:        }
1.126     paf       555:        
                    556:        //sending request
1.171     paf       557:        char* response;
                    558:        size_t response_size;
                    559:        int status_code=http_request(response, response_size,
1.180     paf       560:                host, port, request_head_and_body.cstr(), 
1.142     paf       561:                timeout, fail_on_status_ne_200); 
1.126     paf       562:        
                    563:        //processing results    
1.171     paf       564:        char* raw_body; size_t raw_body_size;
                    565:        char* headers_end_at=strstr(response, CRLF CRLF /*change '4' below along!*/); 
                    566:        if(headers_end_at) {
                    567:                raw_body=headers_end_at+4;
                    568:                raw_body_size=response_size-(raw_body-response);
                    569:        } else
1.126     paf       570:                throw Exception("http.response", 
1.133     paf       571:                        &connect_string,
1.126     paf       572:                        "bad response from host - no headers found"); 
1.171     paf       573:        
                    574:        *headers_end_at=0;
                    575:        const String header_block(response, headers_end_at-response, true);
1.126     paf       576:        
1.154     paf       577:        ArrayString aheaders;
                    578:        result.headers=new HashStringValue;
1.155     paf       579:        VHash* vtables=new VHash;
1.177     paf       580:        result.headers->put(HTTP_TABLES_NAME, vtables);
1.155     paf       581:        HashStringValue& tables=vtables->hash();
                    582: 
1.154     paf       583:        size_t pos_after=0;
                    584:        header_block.split(aheaders, pos_after, CRLF); 
1.126     paf       585:        
                    586:        //processing headers
1.154     paf       587:        size_t aheaders_count=aheaders.count();
                    588:        Charset* real_remote_charset=0; // undetected, yet
                    589:        for(size_t i=1; i<aheaders_count; i++) {
                    590:                const String& line=*aheaders.get(i);
1.171     paf       591:                size_t pos=line.pos(": ", 2); 
1.154     paf       592:                if(pos==STRING_NOT_FOUND || pos<1)
1.126     paf       593:                        throw Exception("http.response", 
1.154     paf       594:                                &connect_string,
                    595:                                "bad response from host - bad header \"%s\"", line.cstr());
1.156     paf       596:                const String::Body HEADER_NAME=
1.154     paf       597:                        line.mid(0, pos).change_case(charsets.source(), String::CC_UPPER);
                    598:                const String& header_value=line.mid(pos+2, line.length());
                    599:                if(HEADER_NAME=="CONTENT-TYPE")
                    600:                        real_remote_charset=detect_charset(charsets.source(), header_value);
1.155     paf       601: 
                    602:                // tables
                    603:                {
                    604:                        Value *valready=(Value *)tables.get(HEADER_NAME);
                    605:                        bool existed=valready!=0;
                    606:                        Table *table;
                    607:                        if(existed) {
                    608:                                // second+ appearence
                    609:                                table=valready->get_table();
                    610:                        } else {
                    611:                                // first appearence
                    612:                                Table::columns_type columns =new ArrayString(1);
                    613:                                *columns+=new String("value");
                    614:                                table=new Table(columns);
                    615:                        }
                    616:                        // this string becomes next row
                    617:                        ArrayString& row=*new ArrayString(1);
                    618:                        row+=&header_value;
                    619:                        *table+=&row;
                    620:                        // not existed before? add it
                    621:                        if(!existed)
                    622:                                tables.put(HEADER_NAME, new VTable(table));
                    623:                }
                    624: 
1.154     paf       625:                result.headers->put(HEADER_NAME, new VString(header_value));
1.126     paf       626:        }
1.154     paf       627:        // defaulting to used-asked charset [it's never empty!]
                    628:        if(!real_remote_charset)
                    629:                real_remote_charset=asked_remote_charset;
1.126     paf       630: 
                    631:        // output response
1.171     paf       632:        String::C real_body=String::C(raw_body, raw_body_size);
                    633:        if(as_text && raw_body_size) // must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
1.169     paf       634:                real_body=Charset::transcode(real_body, *real_remote_charset, charsets.source());
1.154     paf       635: 
                    636:        result.str=const_cast<char *>(real_body.str); // hacking a little
                    637:        result.length=real_body.length;
                    638:        result.headers->put(file_status_name, new VInt(status_code));
                    639:        return result;
1.34      paf       640: }
1.123     paf       641: 
1.154     paf       642: #endif
                    643: 
1.123     paf       644: #ifndef DOXYGEN
                    645: struct File_read_action_info {
1.154     paf       646:        char **data; size_t *data_size;
1.126     paf       647: }; 
1.123     paf       648: #endif
1.154     paf       649: static void file_read_action(
                    650:                             struct stat& finfo, 
                    651:                             int f, 
1.166     paf       652:                             const String& file_spec, const char* /*fname*/, bool as_text, 
1.154     paf       653:                             void *context) {
1.126     paf       654:        File_read_action_info& info=*static_cast<File_read_action_info *>(context); 
1.123     paf       655:        if(size_t to_read_size=(size_t)finfo.st_size) { 
1.154     paf       656:                *info.data=new(PointerFreeGC) char[to_read_size+(as_text?1:0)]; 
1.126     paf       657:                *info.data_size=(size_t)read(f, *info.data, to_read_size); 
1.123     paf       658: 
                    659:                if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126     paf       660:                        throw Exception(0, 
1.123     paf       661:                                &file_spec, 
1.173     paf       662:                                "read failed: actually read %u bytes count not in [0..%u] valid range", 
1.126     paf       663:                                        *info.data_size, to_read_size); 
1.123     paf       664:        } else { // empty file
                    665:                if(as_text) {
1.154     paf       666:                        *info.data=new(PointerFreeGC) char[1]; 
1.123     paf       667:                        *(char*)(*info.data)=0;
                    668:                } else 
                    669:                        *info.data=0;
                    670:                *info.data_size=0;
                    671:                return;
                    672:        }
1.126     paf       673: }
1.154     paf       674: File_read_result file_read(Request_charsets& charsets, const String& file_spec, 
                    675:                           bool as_text, HashStringValue *params,
1.126     paf       676:                           bool fail_on_read_problem) {
1.167     paf       677:        File_read_result result={false, 0, 0, 0};
1.154     paf       678: #ifdef PA_HTTP
                    679:        if(file_spec.starts_with("http://")) {
1.126     paf       680:                // fail on read problem
1.169     paf       681:                File_read_http_result http=file_read_http(charsets, file_spec, as_text, params);
1.154     paf       682:                result.success=true;
                    683:                result.str=http.str;
                    684:                result.length=http.length;
                    685:                result.headers=http.headers; 
1.126     paf       686:        } else {
1.154     paf       687: #endif
1.161     paf       688:                if(params && params->count())
                    689:                        throw Exception("parser.runtime",
                    690:                                0,
                    691:                                "invalid option passed");
                    692: 
1.154     paf       693:                File_read_action_info info={&result.str, &result.length}; 
                    694:                result.success=file_read_action_under_lock(file_spec, 
1.126     paf       695:                        "read", file_read_action, &info, 
                    696:                        as_text, fail_on_read_problem); 
1.154     paf       697: #ifdef PA_HTTP
1.126     paf       698:        }
1.154     paf       699: #endif
1.123     paf       700: 
1.154     paf       701:        if(result.success && as_text) {
1.131     paf       702:                // UTF-8 signature: EF BB BF
1.154     paf       703:                if(result.length>=3) {
                    704:                        char *in=(char *)result.str;
1.159     paf       705:                        if(strncmp(in, "\xEF\xBB\xBF", 3)==0) {
1.154     paf       706:                                result.str=in+3; result.length-=3;// skip prefix
1.131     paf       707:                        }
                    708:                }
                    709: 
1.154     paf       710:                fix_line_breaks((char *)(result.str), result.length); 
1.123     paf       711:        }
1.126     paf       712: 
                    713:        return result;
1.123     paf       714: }
                    715: 
1.154     paf       716: #ifdef PA_SAFE_MODE 
                    717: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) { 
                    718:        if(finfo.st_uid/*foreign?*/!=geteuid() 
                    719:                && finfo.st_gid/*foreign?*/!=getegid()) 
                    720:                throw Exception("parser.runtime",  
                    721:                        &file_spec,  
                    722:                        "parser is in safe mode: " 
                    723:                        "reading files of foreign group and user disabled " 
                    724:                        "[recompile parser with --disable-safe-mode configure option], " 
                    725:                        "actual filename '%s', " 
                    726:                        "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",  
                    727:                                fname, 
                    728:                                finfo.st_uid, geteuid(), 
                    729:                                finfo.st_gid, getegid()); 
                    730: } 
                    731: #endif 
1.149     paf       732: 
1.154     paf       733: bool file_read_action_under_lock(const String& file_spec, 
1.126     paf       734:                                const char* action_name, File_read_action action, void *context, 
                    735:                                bool as_text, 
1.123     paf       736:                                bool fail_on_read_problem) {
1.154     paf       737:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.33      paf       738:        int f;
                    739: 
                    740:        // first open, next stat:
1.45      paf       741:        // directory update of NTFS hard links performed on open.
1.33      paf       742:        // ex: 
                    743:        //   a.html:^test[] and b.html hardlink to a.html
                    744:        //   user inserts ! before ^test in a.html
1.126     paf       745:        //   directory entry of b.html in NTFS not updated at once, 
1.35      paf       746:        //   they delay update till open, so we would receive "!^test[" string
                    747:        //   if would do stat, next open.
1.123     paf       748:        // later: it seems, even this does not help sometimes
1.98      paf       749:     if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123     paf       750:                try {
1.162     paf       751:                        if(pa_lock_shared_blocking(f)!=0)
1.126     paf       752:                                throw Exception("file.lock", 
1.123     paf       753:                                                &file_spec, 
                    754:                                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       755:                                                        strerror(errno), errno, fname);
1.123     paf       756: 
1.124     paf       757:                        struct stat finfo;
                    758:                        if(stat(fname, &finfo)!=0)
                    759:                                throw Exception("file.missing", // hardly possible: we just opened it OK
                    760:                                        &file_spec, 
                    761:                                        "stat failed: %s (%d), actual filename '%s'", 
1.154     paf       762:                                                strerror(errno), errno, fname);
1.124     paf       763: 
1.140     paf       764: #ifdef PA_SAFE_MODE
1.149     paf       765:                        check_safe_mode(finfo, file_spec, fname);
1.105     paf       766: #endif
1.32      paf       767: 
1.154     paf       768:                        action(finfo, f, file_spec, fname, as_text, context); 
1.123     paf       769:                } catch(...) {
1.162     paf       770:                        pa_unlock(f);close(f); 
1.123     paf       771:                        if(fail_on_read_problem)
1.154     paf       772:                                rethrow;
1.123     paf       773:                        return false;                   
                    774:                } 
1.87      paf       775: 
1.162     paf       776:                pa_unlock(f);close(f); 
1.72      parser    777:                return true;
1.118     paf       778:     } else {
                    779:                if(fail_on_read_problem)
1.126     paf       780:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.118     paf       781:                                &file_spec, 
1.123     paf       782:                                "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       783:                                        action_name, strerror(errno), errno, fname);
1.118     paf       784:                return false;
                    785:        }
1.8       paf       786: }
                    787: 
1.63      parser    788: static void create_dir_for_file(const String& file_spec) {
                    789:        size_t pos_after=1;
1.154     paf       790:        size_t pos_before;
                    791:        while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
                    792:                mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775); 
1.63      parser    793:                pos_after=pos_before+1;
                    794:        }
                    795: }
                    796: 
1.98      paf       797: bool file_write_action_under_lock(
1.28      paf       798:                                const String& file_spec, 
1.126     paf       799:                                const char* action_name, File_write_action action, void *context, 
                    800:                                bool as_text, 
                    801:                                bool do_append, 
                    802:                                bool do_block, 
1.110     paf       803:                                bool fail_on_lock_problem) {
1.154     paf       804:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.28      paf       805:        int f;
1.80      paf       806:        if(access(fname, W_OK)!=0) // no
1.126     paf       807:                create_dir_for_file(file_spec); 
1.50      paf       808: 
1.80      paf       809:        if((f=open(fname, 
                    810:                O_CREAT|O_RDWR
                    811:                |(as_text?_O_TEXT:_O_BINARY)
1.138     paf       812:                |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162     paf       813:                if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126     paf       814:                        Exception e("file.lock", 
1.110     paf       815:                                &file_spec, 
                    816:                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       817:                                strerror(errno), errno, fname);
1.126     paf       818:                        close(f); 
1.110     paf       819:                        if(fail_on_lock_problem)
                    820:                                throw e;
1.98      paf       821:                        return false;
                    822:                }
1.96      paf       823: 
1.158     paf       824:                try {
1.126     paf       825:                        action(f, context); 
1.158     paf       826:                } catch(...) {
1.138     paf       827: #ifdef HAVE_FTRUNCATE
1.104     paf       828:                        if(!do_append)
1.125     paf       829:                                ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138     paf       830: #endif
1.162     paf       831:                        pa_unlock(f);close(f); 
1.154     paf       832:                        rethrow;
1.158     paf       833:                }
1.80      paf       834:                
1.138     paf       835: #ifdef HAVE_FTRUNCATE
1.104     paf       836:                if(!do_append)
1.125     paf       837:                        ftruncate(f, lseek(f, 0, SEEK_CUR)); // O_TRUNC truncates even exclusevely write-locked file [thanks to Igor Milyakov <virtan@rotabanner.com> for discovering]
1.138     paf       838: #endif
1.162     paf       839:                pa_unlock(f);close(f); 
1.98      paf       840:                return true;
1.80      paf       841:        } else
1.126     paf       842:                throw Exception(errno==EACCES?"file.access":0, 
1.80      paf       843:                        &file_spec, 
1.96      paf       844:                        "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       845:                                action_name, strerror(errno), errno, fname);
1.96      paf       846:        // here should be nothing, see rethrow above
                    847: }
                    848: 
                    849: #ifndef DOXYGEN
                    850: struct File_write_action_info {
1.154     paf       851:        const char* str; size_t length;
1.126     paf       852: }; 
1.96      paf       853: #endif
                    854: static void file_write_action(int f, void *context) {
1.126     paf       855:        File_write_action_info& info=*static_cast<File_write_action_info *>(context); 
1.154     paf       856:        if(info.length) {
                    857:                int written=write(f, info.str, info.length); 
1.116     paf       858:                if(written<0)
1.126     paf       859:                        throw Exception(0, 
                    860:                                0, 
                    861:                                "write failed: %s (%d)",  strerror(errno), errno); 
1.113     paf       862:        }
1.96      paf       863: }
                    864: void file_write(
                    865:                                const String& file_spec, 
1.154     paf       866:                                const char* data, size_t size, 
1.126     paf       867:                                bool as_text, 
1.96      paf       868:                                bool do_append) {
1.126     paf       869:        File_write_action_info info={data, size}; 
1.98      paf       870:        file_write_action_under_lock(
1.154     paf       871:                file_spec, 
                    872:                "write", file_write_action, &info, 
                    873:                as_text, 
                    874:                do_append); 
1.30      paf       875: }
                    876: 
1.63      parser    877: // throws nothing! [this is required in file_move & file_delete]
1.50      paf       878: static void rmdir(const String& file_spec, size_t pos_after) {
1.154     paf       879:        size_t pos_before;
                    880:        if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126     paf       881:                rmdir(file_spec, pos_before+1); 
1.50      paf       882:        
1.154     paf       883:        rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC)); 
1.50      paf       884: }
1.164     paf       885: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.154     paf       886:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.54      parser    887:        if(unlink(fname)!=0)
1.164     paf       888:                if(fail_on_problem)
1.126     paf       889:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.93      paf       890:                                &file_spec, 
                    891:                                "unlink failed: %s (%d), actual filename '%s'", 
1.154     paf       892:                                        strerror(errno), errno, fname);
1.93      paf       893:                else
                    894:                        return false;
1.50      paf       895: 
1.126     paf       896:        rmdir(file_spec, 1); 
1.93      paf       897:        return true;
1.60      parser    898: }
1.95      paf       899: void file_move(const String& old_spec, const String& new_spec) {
1.154     paf       900:        const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC); 
                    901:        const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC); 
1.63      parser    902:        
1.126     paf       903:        create_dir_for_file(new_spec); 
1.63      parser    904: 
1.60      parser    905:        if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126     paf       906:                throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.60      parser    907:                        &old_spec, 
                    908:                        "rename failed: %s (%d), actual filename '%s' to '%s'", 
1.154     paf       909:                                strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63      parser    910: 
1.126     paf       911:        rmdir(old_spec, 1); 
1.31      paf       912: }
                    913: 
1.51      paf       914: 
1.126     paf       915: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118     paf       916:        struct stat lfinfo;
                    917:        bool result=stat(fname, &lfinfo)==0;
                    918:        if(afinfo)
                    919:                *afinfo=lfinfo;
                    920:        return result;
1.119     paf       921: }
                    922: 
                    923: bool entry_exists(const String& file_spec) {
1.154     paf       924:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.126     paf       925:        return entry_exists(fname, 0); 
1.118     paf       926: }
                    927: 
1.51      paf       928: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154     paf       929:        char* fname=file_spec.cstrm(String::L_FILE_SPEC); 
1.120     paf       930:        if(need_dir) {
1.126     paf       931:                size_t size=strlen(fname); 
1.120     paf       932:                while(size) {
1.126     paf       933:                        char c=fname[size-1]; 
1.120     paf       934:                        if(c=='/' || c=='\\')
                    935:                                fname[--size]=0;
                    936:                        else
                    937:                                break;
                    938:                }
                    939:        }
1.51      paf       940:        struct stat finfo;
1.118     paf       941:        if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109     paf       942:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51      paf       943:                return is_dir==need_dir;
                    944:        }
                    945:        return false;
                    946: }
1.31      paf       947: bool file_readable(const String& file_spec) {
1.126     paf       948:        return entry_readable(file_spec, false); 
1.51      paf       949: }
                    950: bool dir_readable(const String& file_spec) {
1.126     paf       951:        return entry_readable(file_spec, true); 
1.65      parser    952: }
1.154     paf       953: const String* file_readable(const String& path, const String& name) {
                    954:        String& result=*new String(path);
                    955:        result << "/"; 
                    956:        result << name;
                    957:        return file_readable(result)?&result:0;
1.43      paf       958: }
                    959: bool file_executable(const String& file_spec) {
1.154     paf       960:     return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44      paf       961: }
                    962: 
1.64      parser    963: bool file_stat(const String& file_spec, 
1.58      parser    964:                           size_t& rsize, 
1.126     paf       965:                           time_t& ratime, 
                    966:                           time_t& rmtime, 
                    967:                           time_t& rctime, 
1.64      parser    968:                           bool fail_on_read_problem) {
1.154     paf       969:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
                    970:        struct stat finfo;
1.44      paf       971:        if(stat(fname, &finfo)!=0)
1.64      parser    972:                if(fail_on_read_problem)
1.126     paf       973:                        throw Exception("file.missing", 
1.67      parser    974:                                &file_spec, 
                    975:                                "getting file size failed: %s (%d), real filename '%s'", 
1.154     paf       976:                                        strerror(errno), errno, fname);
1.64      parser    977:                else
                    978:                        return false;
1.58      parser    979:        rsize=finfo.st_size;
                    980:        ratime=finfo.st_atime;
                    981:        rmtime=finfo.st_mtime;
                    982:        rctime=finfo.st_ctime;
1.64      parser    983:        return true;
1.18      paf       984: }
                    985: 
1.126     paf       986: char* getrow(char* *row_ref, char delim) {
                    987:     char* result=*row_ref;
1.8       paf       988:     if(result) {
1.126     paf       989:                *row_ref=strchr(result, delim); 
1.8       paf       990:                if(*row_ref) 
                    991:                        *((*row_ref)++)=0; 
                    992:                else if(!*result) 
                    993:                        return 0;
                    994:     }
                    995:     return result;
                    996: }
                    997: 
1.126     paf       998: char* lsplit(char* string, char delim) {
1.23      paf       999:     if(string) {
1.126     paf      1000:                char* v=strchr(string, delim); 
1.8       paf      1001:                if(v) {
                   1002:                        *v=0;
                   1003:                        return v+1;
                   1004:                }
                   1005:     }
                   1006:     return 0;
                   1007: }
                   1008: 
1.126     paf      1009: char* lsplit(char* *string_ref, char delim) {
                   1010:     char* result=*string_ref;
                   1011:        char* next=lsplit(*string_ref, delim); 
1.8       paf      1012:     *string_ref=next;
                   1013:     return result;
1.9       paf      1014: }
                   1015: 
1.126     paf      1016: char* rsplit(char* string, char delim) {
1.18      paf      1017:     if(string) {
1.126     paf      1018:                char* v=strrchr(string, delim); 
1.18      paf      1019:                if(v) {
1.9       paf      1020:                        *v=0;
                   1021:                        return v+1;
                   1022:                }
                   1023:     }
                   1024:     return NULL;       
1.10      paf      1025: }
                   1026: 
1.37      paf      1027: /// @todo less stupid type detection
1.154     paf      1028: const char* format(double value, char* fmt) {
1.126     paf      1029:        char local_buf[MAX_NUMBER]; 
1.108     paf      1030:        size_t size;
                   1031:        
1.10      paf      1032:        if(fmt)
                   1033:                if(strpbrk(fmt, "diouxX"))
                   1034:                        if(strpbrk(fmt, "ouxX"))
1.126     paf      1035:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.10      paf      1036:                        else
1.126     paf      1037:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
1.10      paf      1038:                else
1.126     paf      1039:                        size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
1.10      paf      1040:        else
1.126     paf      1041:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value); 
1.10      paf      1042:        
1.154     paf      1043:        return pa_strdup(local_buf, size);
1.12      paf      1044: }
                   1045: 
1.36      paf      1046: size_t stdout_write(const void *buf, size_t size) {
1.12      paf      1047: #ifdef WIN32
                   1048:        do{
1.154     paf      1049:                int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); 
1.12      paf      1050:                if(chunk_written<=0)
                   1051:                        break;
                   1052:                size-=chunk_written;
1.36      paf      1053:                buf=((const char*)buf)+chunk_written;
1.126     paf      1054:        } while(size>0); 
1.12      paf      1055: 
                   1056:        return size;
                   1057: #else
1.126     paf      1058:        return fwrite(buf, 1, size, stdout); 
1.12      paf      1059: #endif
1.2       paf      1060: }
1.14      paf      1061: 
1.154     paf      1062: char* unescape_chars(const char* cp, int len) {
                   1063:        char* s=new(PointerFreeGC) char[len + 1]; 
1.14      paf      1064:        enum EscapeState {
1.33      paf      1065:                EscapeRest, 
                   1066:                EscapeFirst, 
1.14      paf      1067:                EscapeSecond
                   1068:        } escapeState=EscapeRest;
                   1069:        int escapedValue=0;
                   1070:        int srcPos=0;
                   1071:        int dstPos=0;
                   1072:        while(srcPos < len) {
1.126     paf      1073:                int ch=cp[srcPos]; 
1.14      paf      1074:                switch(escapeState) {
                   1075:                        case EscapeRest:
                   1076:                        if(ch=='%') {
                   1077:                                escapeState=EscapeFirst;
                   1078:                        } else if(ch=='+') {
1.126     paf      1079:                                s[dstPos++]=' '; 
1.14      paf      1080:                        } else {
                   1081:                                s[dstPos++]=ch; 
                   1082:                        }
                   1083:                        break;
                   1084:                        case EscapeFirst:
                   1085:                        escapedValue=hex_value[ch] << 4;        
                   1086:                        escapeState=EscapeSecond;
                   1087:                        break;
                   1088:                        case EscapeSecond:
1.126     paf      1089:                        escapedValue +=hex_value[ch]; 
1.14      paf      1090:                        s[dstPos++]=escapedValue;
                   1091:                        escapeState=EscapeRest;
                   1092:                        break;
                   1093:                }
1.126     paf      1094:                srcPos++; 
1.14      paf      1095:        }
                   1096:        s[dstPos]=0;
                   1097:        return s;
1.24      paf      1098: }
                   1099: 
                   1100: #ifdef WIN32
1.126     paf      1101: void back_slashes_to_slashes(char* s) {
1.24      paf      1102:        if(s)
                   1103:                for(; *s; s++)
                   1104:                        if(*s=='\\')
1.126     paf      1105:                                *s='/'; 
1.24      paf      1106: }
1.42      paf      1107: /*
1.126     paf      1108: void slashes_to_back_slashes(char* s) {
1.42      paf      1109:        if(s)
                   1110:                for(; *s; s++)
                   1111:                        if(*s=='/')
1.126     paf      1112:                                *s='\\'; 
1.42      paf      1113: }
                   1114: */
1.24      paf      1115: #endif
1.41      paf      1116: 
1.126     paf      1117: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41      paf      1118:        while(true) {
                   1119:                if(!(*s1)) {
                   1120:                        if(!(*s2))
                   1121:                                return true;
                   1122:                        else
                   1123:                                return !strict;
                   1124:                } else if(!(*s2))
                   1125:                        return !strict;
                   1126:                if(isalpha(*s1)) {
                   1127:                        if(tolower(*s1) !=tolower(*s2))
                   1128:                                return false;
                   1129:                } else if((*s1) !=(*s2))
                   1130:                        return false;
1.126     paf      1131:                s1++; 
                   1132:                s2++; 
1.41      paf      1133:        }
1.57      parser   1134: }
                   1135: 
1.84      paf      1136: static bool isLeap(int year) {
1.57      parser   1137:     return !(
                   1138:              (year % 4) || ((year % 400) && !(year % 100))
1.126     paf      1139:             ); 
1.57      parser   1140: }
                   1141: 
                   1142: int getMonthDays(int year, int month) {
                   1143:     int monthDays[]={
1.126     paf      1144:         31, 
                   1145:         isLeap(year) ? 29 : 28, 
                   1146:         31, 
                   1147:         30, 
                   1148:         31, 
                   1149:         30, 
                   1150:         31, 
                   1151:         31, 
                   1152:         30, 
                   1153:         31, 
                   1154:         30, 
1.57      parser   1155:         31
1.126     paf      1156:     }; 
                   1157:     return monthDays[month]; 
1.41      paf      1158: }
1.69      parser   1159: 
1.126     paf      1160: void remove_crlf(char* start, char* end) {
                   1161:        for(char* p=start; p<end; p++)
1.69      parser   1162:                switch(*p) {
1.126     paf      1163:                        case '\n': *p='|';  break;
                   1164:                        case '\r': *p=' ';  break;
1.69      parser   1165:                }
1.91      paf      1166: }
                   1167: 
                   1168: 
                   1169: /// must be last in this file
                   1170: #undef vsnprintf
1.126     paf      1171: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91      paf      1172:        if(!s)
                   1173:                return 0;
                   1174: 
                   1175:        int r;
                   1176:        // note: on win32& maybe somewhere else
                   1177:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                   1178:        --s;
1.172     paf      1179: 
                   1180:        // clients do not check for negative 's', feature: ignore such prints
                   1181:        if((ssize_t)s<0)
                   1182:                return 0;
                   1183: 
1.91      paf      1184: #if _MSC_VER
                   1185:        /*
                   1186:        win32: 
                   1187:        mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
                   1188: 
1.154     paf      1189:          if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91      paf      1190:        */
1.126     paf      1191:        r=_vsnprintf(b, s, f, l); 
1.91      paf      1192:        if(r<0) 
                   1193:                r=s;
                   1194: #else
1.126     paf      1195:        r=vsnprintf(b, s, f, l); 
1.91      paf      1196:        /*
                   1197:        solaris: 
                   1198:        man vsnprintf
                   1199: 
                   1200:          The snprintf() function returns  the  number  of  characters
                   1201:        formatted, that is, the number of characters that would have
                   1202:        been written to the buffer if it were large enough.  If  the
                   1203:        value  of  n  is  0  on a call to snprintf(), an unspecified
                   1204:        value less than 1 is returned.
                   1205:        */
                   1206: 
                   1207:        if(r<0)
                   1208:                r=0;
1.167     paf      1209:        else if((size_t)r>s)
1.91      paf      1210:                r=s;
                   1211: #endif
                   1212:        b[r]=0;
                   1213:        return r;
                   1214: }
                   1215: 
1.126     paf      1216: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91      paf      1217:        va_list l;
1.126     paf      1218:     va_start(l, f); 
                   1219:     int r=__vsnprintf(b, s, f, l); 
                   1220:     va_end(l); 
1.91      paf      1221:        return r;
1.178     paf      1222: }
                   1223: 
                   1224: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
                   1225: /*
                   1226:  *  Authors: Michael Zucchi <notzed@helixcode.com>
                   1227:  *           Jeffrey Stedfast <fejj@helixcode.com>
                   1228:  *
                   1229:  *  Copyright 2000 Helix Code, Inc. (www.helixcode.com)
                   1230:  *
                   1231:  *  This program is free software; you can redistribute it and/or modify
                   1232:  *  it under the terms of the GNU General Public License as published by
                   1233:  *  the Free Software Foundation; either version 2 of the License, or
                   1234:  *  (at your option) any later version.
                   1235:  *
                   1236:  *  This program is distributed in the hope that it will be useful,
                   1237:  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
                   1238:  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                   1239:  *  GNU General Public License for more details.
                   1240:  *
                   1241:  *  You should have received a copy of the GNU General Public License
                   1242:  *  along with this program; if not, write to the Free Software
                   1243:  *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
                   1244:  *
                   1245:  */
                   1246: static char *base64_alphabet =
                   1247:        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                   1248: 
                   1249: /**
                   1250:  * g_mime_utils_base64_encode_step:
                   1251:  * @in: input stream
                   1252:  * @inlen: length of the input
                   1253:  * @out: output string
                   1254:  * @state: holds the number of bits that are stored in @save
                   1255:  * @save: leftover bits that have not yet been encoded
                   1256:  *
                   1257:  * Base64 encodes a chunk of data. Performs an 'encode step', only
                   1258:  * encodes blocks of 3 characters to the output at a time, saves
                   1259:  * left-over state in state and save (initialise to 0 on first
                   1260:  * invocation).
                   1261:  *
                   1262:  * Returns the number of bytes encoded.
                   1263:  **/
                   1264: static size_t
                   1265: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1266: {
                   1267:        const register unsigned char *inptr;
                   1268:        register unsigned char *outptr;
                   1269:        
                   1270:        if (inlen <= 0)
                   1271:                return 0;
                   1272:        
                   1273:        inptr = in;
                   1274:        outptr = out;
                   1275:        
                   1276:        if (inlen + ((unsigned char *)save)[0] > 2) {
                   1277:                const unsigned char *inend = in + inlen - 2;
                   1278:                register int c1 = 0, c2 = 0, c3 = 0;
                   1279:                register int already;
                   1280:                
                   1281:                already = *state;
                   1282:                
                   1283:                switch (((char *)save)[0]) {
                   1284:                case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
                   1285:                case 2: c1 = ((unsigned char *)save)[1];
                   1286:                        c2 = ((unsigned char *)save)[2]; goto skip2;
                   1287:                }
                   1288:                
                   1289:                /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
                   1290:                while (inptr < inend) {
                   1291:                        c1 = *inptr++;
                   1292:                skip1:
                   1293:                        c2 = *inptr++;
                   1294:                skip2:
                   1295:                        c3 = *inptr++;
                   1296:                        *outptr++ = base64_alphabet [c1 >> 2];
                   1297:                        *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
                   1298:                        *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
                   1299:                        *outptr++ = base64_alphabet [c3 & 0x3f];
                   1300:                        /* this is a bit ugly ... */
                   1301:                        if ((++already) >= 19) {
                   1302:                                *outptr++ = '\n';
                   1303:                                already = 0;
                   1304:                        }
                   1305:                }
                   1306:                
                   1307:                ((unsigned char *)save)[0] = 0;
                   1308:                inlen = 2 - (inptr - inend);
                   1309:                *state = already;
                   1310:        }
                   1311:        
                   1312:        //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
                   1313:        
                   1314:        if (inlen > 0) {
                   1315:                register char *saveout;
                   1316:                
                   1317:                /* points to the slot for the next char to save */
                   1318:                saveout = & (((char *)save)[1]) + ((char *)save)[0];
                   1319:                
                   1320:                /* inlen can only be 0 1 or 2 */
                   1321:                switch (inlen) {
                   1322:                case 2: *saveout++ = *inptr++;
                   1323:                case 1: *saveout++ = *inptr++;
                   1324:                }
                   1325:                ((char *)save)[0] += inlen;
                   1326:        }
                   1327:        
                   1328:        /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
                   1329:                  (int)((char *)save)[0],
                   1330:                  (int)((char *)save)[1],
                   1331:                  (int)((char *)save)[2]));*/
                   1332:        
                   1333:        return (outptr - out);
                   1334: }
                   1335: 
                   1336: /**
                   1337:  * g_mime_utils_base64_encode_close:
                   1338:  * @in: input stream
                   1339:  * @inlen: length of the input
                   1340:  * @out: output string
                   1341:  * @state: holds the number of bits that are stored in @save
                   1342:  * @save: leftover bits that have not yet been encoded
                   1343:  *
                   1344:  * Base64 encodes the input stream to the output stream. Call this
                   1345:  * when finished encoding data with g_mime_utils_base64_encode_step to
                   1346:  * flush off the last little bit.
                   1347:  *
                   1348:  * Returns the number of bytes encoded.
                   1349:  **/
                   1350: static size_t
                   1351: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1352: {
                   1353:        unsigned char *outptr = out;
                   1354:        int c1, c2;
                   1355:        
                   1356:        if (inlen > 0)
                   1357:                outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
                   1358:        
                   1359:        c1 = ((unsigned char *)save)[1];
                   1360:        c2 = ((unsigned char *)save)[2];
                   1361:        
                   1362:        switch (((unsigned char *)save)[0]) {
                   1363:        case 2:
                   1364:                outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
                   1365:                goto skip;
                   1366:        case 1:
                   1367:                outptr[2] = '=';
                   1368:        skip:
                   1369:                outptr[0] = base64_alphabet [c1 >> 2];
                   1370:                outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
                   1371:                outptr[3] = '=';
                   1372:                outptr += 4;
                   1373:                break;
                   1374:        }
                   1375:        
                   1376:        *outptr++ = 0;
                   1377:        
                   1378:        *save = 0;
                   1379:        *state = 0;
                   1380:        
                   1381:        return (outptr - out);
                   1382: }
                   1383: 
                   1384: char* pa_base64(const char *in, size_t len)
                   1385: {
                   1386:        /* wont go to more than 2x size (overly conservative) */
                   1387:        char* result=new(PointerFreeGC) char[len * 2 + 6];
                   1388:        int state=0;
                   1389:        int save=0;
                   1390:        size_t filled=g_mime_utils_base64_encode_close ((const unsigned char*)in, len, 
                   1391:                (unsigned char*)result, &state, &save);
                   1392:        assert(filled <= len * 2 + 6);
                   1393: 
                   1394:        return result;
1.98      paf      1395: }

E-mail: