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

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

E-mail: