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

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

E-mail: