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

1.15      paf         1: /** @file
1.16      paf         2:        Parser: commonly functions.
                      3: 
1.154     paf         4:        Copyright(c) 2001-2003 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.162   ! paf         8: static const char* IDENT_COMMON_C="$Date: 2003/11/03 13:20:30 $"; 
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
                     65: #endif
                     66: 
1.93      paf        67: // locking constants
1.154     paf        68: //#define PA_DEBUG_NO_LOCKING
                     69: 
                     70: #ifdef PA_DEBUG_NO_LOCKING
1.93      paf        71: 
1.99      paf        72: #ifdef HAVE_FLOCK
                     73: 
1.162   ! paf        74: static int pa_lock_shared_blocking(int fd) { return flock(fd, LOCK_SH); }
        !            75: static int pa_lock_exclusive_blocking(int fd) { return flock(fd, LOCK_EX); }
        !            76: static int pa_lock_exclusive_nonblocking(int fd) { return flock(fd, LOCK_EX || LOCK_NB); }
        !            77: static int pa_unlock(int fd) { return flock(fd, LOCK_UN); }
1.99      paf        78: 
1.98      paf        79: #else
1.99      paf        80: #ifdef HAVE__LOCKING
1.98      paf        81: 
1.126     paf        82: #define FLOCK(operation) lseek(fd, 0, SEEK_SET);  return _locking(fd, operation, 1)
1.162   ! paf        83: static int pa_lock_shared_blocking(int fd) { FLOCK(_LK_LOCK); }
        !            84: static int pa_lock_exclusive_blocking(int fd) { FLOCK(_LK_LOCK); }
        !            85: static int pa_lock_exclusive_nonblocking(int fd) { FLOCK(_LK_NBLCK); }
        !            86: static int pa_unlock(int fd) { FLOCK(_LK_UNLCK); }
1.93      paf        87: 
1.99      paf        88: #else
                     89: #ifdef HAVE_FCNTL
1.93      paf        90: 
1.126     paf        91: #define FLOCK(cmd, arg) struct flock ls={arg, SEEK_SET};  return fcntl(fd, cmd, &ls)
1.162   ! paf        92: static int pa_lock_shared_blocking(int fd) { FLOCK(F_SETLKW, F_RDLCK); }
        !            93: static int pa_lock_exclusive_blocking(int fd) { FLOCK(F_SETLKW, F_WRLCK); }
        !            94: static int pa_lock_exclusive_nonblocking(int fd) { FLOCK(F_SETLK, F_RDLCK); }
        !            95: static int pa_unlock(int fd) { FLOCK(F_SETLK, F_UNLCK); }
1.93      paf        96: 
                     97: #else
                     98: #ifdef HAVE_LOCKF
1.99      paf        99: 
1.126     paf       100: #define FLOCK(fd, operation) lseek(fd, 0, SEEK_SET);  return lockf(fd, operation, 1)
1.162   ! paf       101: static int pa_lock_shared_blocking(int fd) { FLOCK(F_LOCK); } // on intel solaris man doesn't have doc on shared blocking
        !           102: static int pa_lock_exclusive_blocking(int fd) { FLOCK(F_LOCK); }
        !           103: static int pa_lock_exclusive_nonblocking(int fd) { FLOCK(F_TLOCK); }
        !           104: static int pa_unlock(int fd) { FLOCK(F_TLOCK); }
1.99      paf       105: 
1.93      paf       106: #else
1.99      paf       107: 
                    108: #error unable to find file locking func
                    109: 
                    110: #endif
1.93      paf       111: #endif
                    112: #endif
                    113: #endif
                    114: 
1.154     paf       115: #else
1.162   ! paf       116: static int pa_lock_shared_blocking(int fd) { return 0; }
        !           117: static int pa_lock_exclusive_blocking(int fd) { return 0; }
        !           118: static int pa_lock_exclusive_nonblocking(int fd) { return 0; }
        !           119: static int pa_unlock(int fd) { return 0; }
1.154     paf       120: 
                    121: #endif
                    122: 
                    123: // defines for globals
                    124: 
                    125: #define FILE_STATUS_NAME  "status"
                    126: 
                    127: // globals
                    128: 
                    129: const String file_status_name(FILE_STATUS_NAME);
                    130: 
                    131: // defines for statics
                    132: 
                    133: #define HTTP_METHOD_NAME  "method"
                    134: #define HTTP_TIMEOUT_NAME    "timeout"
                    135: #define HTTP_HEADERS_NAME "headers"
                    136: #define HTTP_ANY_STATUS_NAME "any-status"
                    137: #define HTTP_CHARSET_NAME "charset"
1.155     paf       138: #define HTTP_TABLES_NAME "tables"
1.154     paf       139: 
                    140: // statics
                    141: 
                    142: static const String http_method_name(HTTP_METHOD_NAME);
                    143: static const String http_timeout_name(HTTP_TIMEOUT_NAME);
                    144: static const String http_headers_name(HTTP_HEADERS_NAME);
                    145: static const String http_any_status_name(HTTP_ANY_STATUS_NAME);
                    146: static const String http_charset_name(HTTP_CHARSET_NAME);
1.155     paf       147: static const String http_tables_name(HTTP_TABLES_NAME);
1.154     paf       148: 
                    149: // defines
                    150: 
1.127     paf       151: #define DEFAULT_USER_AGENT "parser3"
                    152: 
1.154     paf       153: // functions
1.127     paf       154: 
1.154     paf       155: void fix_line_breaks(char *str, size_t& length) {
1.87      paf       156:        //_asm int 3;
1.154     paf       157:        const char* const eob=str+length;
                    158:        char* dest=str;
1.72      parser    159:        // fix DOS: \r\n -> \n
                    160:        // fix Macintosh: \r -> \n
1.154     paf       161:        char* bol=str;
1.137     paf       162:        while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72      parser    163:                size_t len=eol-bol;
                    164:                if(dest!=bol)
1.126     paf       165:                        memcpy(dest, bol, len); 
1.72      parser    166:                dest+=len;
1.126     paf       167:                *dest++='\n'; 
1.72      parser    168: 
1.126     paf       169:                if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72      parser    170:                        bol=eol+2;
1.154     paf       171:                        length--; 
1.126     paf       172:                } else // \r, not \n = Macintosh
1.72      parser    173:                        bol=eol+1;
                    174:        }
1.154     paf       175:        // last piece without \r
1.72      parser    176:        if(dest!=bol)
1.126     paf       177:                memcpy(dest, bol, eob-bol); 
1.154     paf       178:        str[length]=0; // terminating
1.72      parser    179: }
1.18      paf       180: 
1.154     paf       181: char* file_read_text(Request_charsets& charsets, 
                    182:                     const String& file_spec, 
                    183:                     bool fail_on_read_problem,
                    184:                     HashStringValue* params/*, HashStringValue* * out_fields*/) {
                    185:        File_read_result file=
                    186:                file_read(charsets, file_spec, true, params, fail_on_read_problem);
                    187:        return file.success?file.str:0;
1.126     paf       188: }
                    189: 
1.154     paf       190: #ifdef PA_HTTP
1.126     paf       191: //http request stuff
1.154     paf       192: 
                    193: #undef CRLF
                    194: #define CRLF "\r\n"
1.126     paf       195: 
                    196: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
                    197:     memset(addr, 0, sizeof(*addr)); 
                    198:     addr->sin_family=AF_INET;
                    199:     addr->sin_port=htons(port); 
                    200:     if(host) {
                    201:                if(struct hostent *hostIP=gethostbyname(host)) 
                    202:                        memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length); 
                    203:                else
                    204:                        return false;
                    205:     } else 
                    206:                addr->sin_addr.s_addr=INADDR_ANY;
                    207:     return true;
                    208: }
                    209: 
1.142     paf       210: static int http_read_response(String& response, int sock, bool fail_on_status_ne_200){
1.154     paf       211:        int result=0;
                    212:        size_t EOLat=0;
1.126     paf       213:        while(true) {
1.154     paf       214:                char *buf=new(PointerFreeGC) char[MAX_STRING]; 
1.126     paf       215:                ssize_t size=recv(sock, buf, MAX_STRING, 0); 
                    216:                if(size<=0)
                    217:                        break;
1.154     paf       218:                response.append_strdup(buf, size, String::L_TAINTED); 
                    219:                if(!result && (EOLat=response.pos(CRLF, 2))!=STRING_NOT_FOUND) { // checking status in first response
1.142     paf       220:                        const String& status_line=response.mid(0, (size_t)EOLat);
1.154     paf       221:                        ArrayString astatus; 
                    222:                        size_t pos_after=0;
                    223:                        status_line.split(astatus, pos_after, " "); 
                    224:                        const String& status_code=*astatus.get(1);
                    225:                        result=status_code.as_int(); 
1.142     paf       226: 
1.154     paf       227:                        if(fail_on_status_ne_200 && result!=200)
1.142     paf       228:                                throw Exception("http.status",
1.154     paf       229:                                        &status_code,
1.142     paf       230:                                        "invalid HTTP response status");
                    231:                }
                    232:        }
1.154     paf       233:        if(result)
                    234:                return result;
1.142     paf       235:        else
                    236:                throw Exception("http.response",
                    237:                        0,
1.154     paf       238:                        "bad response from host - no status found (size=%lu)", response.length()); 
1.126     paf       239: }
                    240: 
                    241: /* ********************** request *************************** */
                    242: 
                    243: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
1.145     paf       244: #      define PA_USE_ALARM
1.126     paf       245: #endif
                    246: 
1.145     paf       247: #ifdef PA_USE_ALARM
1.126     paf       248: static sigjmp_buf timeout_env;
                    249: static void timeout_handler(int sig){
                    250:     siglongjmp(timeout_env, 1); 
                    251: }
                    252: #endif
                    253: 
1.142     paf       254: static int http_request(String& response,
1.152     paf       255:                        const char* host, int port, 
                    256:                        const char* request, 
                    257:                        int timeout,
                    258:                        bool fail_on_status_ne_200) {
1.126     paf       259:        if(!host)
                    260:                throw Exception("http.host", 
1.154     paf       261:                        0, 
1.126     paf       262:                        "zero hostname");  //never
                    263: 
1.145     paf       264: #ifdef PA_USE_ALARM
1.146     paf       265:        signal(SIGALRM, timeout_handler); 
1.126     paf       266: #endif
                    267:        int sock=-1;
1.145     paf       268: #ifdef PA_USE_ALARM
                    269:        if(sigsetjmp(timeout_env, 1)) {
                    270:                // stupid gcc [2.95.4] generated bad code
                    271:                // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
                    272:                // rewritten simplier [though duplicating closesocket code]
                    273:                if(sock>=0) 
                    274:                        closesocket(sock); 
                    275:                throw Exception("http.timeout", 
                    276:                        origin_string, 
                    277:                        "timeout occured while retrieving document"); 
1.146     paf       278:                return 0; // never
1.145     paf       279:        } else {
                    280:                alarm(timeout); 
                    281: #endif
1.146     paf       282:                try {
                    283:                        int result;
1.126     paf       284:                        struct sockaddr_in dest;
1.154     paf       285:                
                    286:                        if(!set_addr(&dest, host, port))
1.126     paf       287:                                throw Exception("http.host", 
1.154     paf       288:                                        0, 
1.127     paf       289:                                        "can not resolve hostname \"%s\"", host); 
1.126     paf       290:                        
                    291:                        if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0)
                    292:                                throw Exception("http.connect", 
1.154     paf       293:                                        0, 
1.127     paf       294:                                        "can not make socket: %s (%d)", strerror(errno), errno); 
1.126     paf       295:                        if(connect(sock, (struct sockaddr *)&dest, sizeof(dest)))
                    296:                                throw Exception("http.connect", 
1.154     paf       297:                                        0, 
1.127     paf       298:                                        "can not connect to host \"%s\": %s (%d)", host, strerror(errno), errno); 
1.126     paf       299:                        size_t request_size=strlen(request);
                    300:                        if(send(sock, request, request_size, 0)!=(ssize_t)request_size)
                    301:                                throw Exception("http.connect", 
1.154     paf       302:                                        0, 
1.127     paf       303:                                        "error sending request: %s (%d)", strerror(errno), errno); 
1.126     paf       304: 
1.142     paf       305:                        result=http_read_response(response, sock, fail_on_status_ne_200); 
                    306:                        closesocket(sock); 
1.145     paf       307: #ifdef PA_USE_ALARM
1.142     paf       308:                        alarm(0)1.126     paf       309: #endif
1.147     paf       310:                        return result;
1.146     paf       311:                } catch(...) {
1.145     paf       312: #ifdef PA_USE_ALARM
1.146     paf       313:                        alarm(0)1.126     paf       314: #endif
1.146     paf       315:                        if(sock>=0) 
                    316:                                closesocket(sock); 
1.154     paf       317:                        rethrow;
1.146     paf       318:                }
1.148     paf       319: #ifdef PA_USE_ALARM
1.126     paf       320:        }
1.148     paf       321: #endif
1.126     paf       322: }
                    323: 
1.127     paf       324: #ifndef DOXYGEN
                    325: struct Http_pass_header_info {
1.154     paf       326:        Request_charsets* charsets;
1.127     paf       327:        String* request;
                    328:        bool user_agent_specified;
                    329: };
                    330: #endif
1.154     paf       331: static void http_pass_header(HashStringValue::key_type key, 
                    332:                             HashStringValue::value_type value, 
                    333:                             Http_pass_header_info *info) {
                    334:     *info->request <<key<<": "
                    335:        << attributed_meaning_to_string(*value, String::L_HTTP_HEADER, false)
                    336:        << CRLF; 
1.135     paf       337:        
1.154     paf       338:     if(String(key, String::L_TAINTED).change_case(info->charsets->source(), String::CC_UPPER)=="USER-AGENT")
                    339:        info->user_agent_specified=true;
1.126     paf       340: }
1.154     paf       341: 
                    342: 
                    343: static Charset* detect_charset(Charset& source_charset, const String& content_type_value) {
1.156     paf       344:        const String::Body CONTENT_TYPE_VALUE=
1.154     paf       345:                content_type_value.change_case(source_charset, String::CC_UPPER);
                    346:        // content-type: xxx/xxx; source_charset=WE-NEED-THIS
                    347:        // content-type: xxx/xxx; source_charset="WE-NEED-THIS"
                    348:        // content-type: xxx/xxx; source_charset="WE-NEED-THIS";
                    349:        size_t before_charseteq_pos=CONTENT_TYPE_VALUE.pos("CHARSET=");
                    350:        if(before_charseteq_pos!=STRING_NOT_FOUND) {
                    351:                size_t charset_begin=before_charseteq_pos+8/*CHARSET="*/;
                    352:                size_t open_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
                    353:                bool quoted=open_quote_pos==charset_begin;
                    354:                if(quoted)
                    355:                        charset_begin++; // skip opening '"'
                    356:                size_t charset_end=CONTENT_TYPE_VALUE.length();
                    357:                if(quoted) {
                    358:                        size_t close_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
                    359:                        if(close_quote_pos!=STRING_NOT_FOUND)
                    360:                                charset_end=close_quote_pos;
                    361:                } else {
                    362:                        size_t delim_pos=CONTENT_TYPE_VALUE.pos(';', charset_begin);
                    363:                        if(delim_pos!=STRING_NOT_FOUND)
                    364:                                charset_end=delim_pos;
                    365:                }
1.156     paf       366:                const String::Body CHARSET_NAME_BODY=
1.154     paf       367:                        CONTENT_TYPE_VALUE.mid(charset_begin, charset_end);
                    368: 
                    369:                return &charsets.get(CHARSET_NAME_BODY);
                    370:        }
                    371: 
                    372:        return 0;
                    373: }
                    374: 
                    375: 
                    376: #ifndef DOXYGEN
                    377: struct File_read_http_result {
                    378:        char *str; size_t length;
                    379:        HashStringValue* headers;
                    380: }; 
                    381: #endif
1.155     paf       382: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.154     paf       383: static File_read_http_result file_read_http(Request_charsets& charsets, 
                    384:                                            const String& file_spec, 
                    385:                                            HashStringValue *options=0) {
                    386:        File_read_http_result result;
1.126     paf       387:        char host[MAX_STRING]; 
1.129     paf       388:        const char* uri; 
1.126     paf       389:        int port;
1.154     paf       390:        const char* method=0;
1.126     paf       391:        int timeout=2;
1.142     paf       392:        bool fail_on_status_ne_200=true;
1.154     paf       393:        Value* vheaders=0;
                    394:        Charset *asked_remote_charset=0;
1.126     paf       395: 
1.127     paf       396:        if(options) {
                    397:                int valid_options=0;
1.154     paf       398:                if(Value* vmethod=options->get(http_method_name)) {
1.127     paf       399:                        valid_options++;
1.154     paf       400:                        method=vmethod->as_string().cstr();
1.127     paf       401:                }
1.154     paf       402:                if(Value* vtimeout=options->get(http_timeout_name)) {
1.127     paf       403:                        valid_options++;
                    404:                        timeout=vtimeout->as_int(); 
                    405:                }
1.154     paf       406:                if(vheaders=options->get(http_headers_name)) {
1.127     paf       407:                        valid_options++;
                    408:                }
1.154     paf       409:                if(Value* vany_status=options->get(http_any_status_name)) {
1.142     paf       410:                        valid_options++;
                    411:                        fail_on_status_ne_200=!vany_status->as_bool(); 
                    412:                }
1.154     paf       413:                if(Value* vcharset_name=options->get(http_charset_name)) {
                    414:                        valid_options++;
                    415:                        asked_remote_charset=&::charsets.get(vcharset_name->as_string().
                    416:                                change_case(charsets.source(), String::CC_UPPER));
                    417:                }
1.142     paf       418: 
1.154     paf       419:                if(valid_options!=options->count())
1.127     paf       420:                        throw Exception("parser.runtime",
                    421:                                0,
                    422:                                "invalid option passed");
1.154     paf       423:        }
                    424:        if(!asked_remote_charset) // defaulting to $request:charset
                    425:                asked_remote_charset=&charsets.source();
                    426: 
                    427:        //preparing request
                    428:        String& connect_string=*new String;
                    429:        // not in ^sql{... L_SQL ...} spirit, but closer to ^file::load one
                    430:        connect_string.append(file_spec, String::L_URI); // tainted pieces -> URI pieces
                    431: 
                    432:        const char* request_cstr;
                    433:        {
                    434:                // influence URLencoding of tainted pieces to String::L_URI lang
                    435:                Temp_client_charset temp(charsets, *asked_remote_charset);
                    436: 
                    437:                const char* connect_string_cstr=connect_string.cstr(String::L_UNSPECIFIED); 
1.126     paf       438: 
1.154     paf       439:                const char* current=connect_string_cstr;
                    440:                if(strncmp(current, "http://", 7)!=0)
                    441:                        throw Exception(0, 
                    442:                                &connect_string, 
                    443:                                "does not start with http://"); //never
                    444:                current+=7;
                    445: 
                    446:                strncpy(host, current, sizeof(host)-1);  host[sizeof(host)-1]=0;
                    447:                char* host_uri=lsplit(host, '/'); 
                    448:                uri=host_uri?current+(host_uri-1-host):"/"; 
                    449:                char* port_cstr=lsplit(host, ':'); 
                    450:                char* error_pos=0;
                    451:                port=port_cstr?strtol(port_cstr, &error_pos, 0):80;
                    452: 
                    453: 
                    454:                //making request
                    455:                String request;
                    456:                if(method)
                    457:                        request<<method;
                    458:                else
                    459:                        request<<"GET";
                    460:                request<< " "<< uri <<" HTTP/1.0" CRLF
                    461:                        "host: "<< host << CRLF; 
                    462:                bool user_agent_specified=false;
                    463:                if(vheaders && !vheaders->is_string()) { // allow empty
                    464:                        if(HashStringValue *headers=vheaders->get_hash()) {
                    465:                                Http_pass_header_info info={&charsets, &request};
                    466:                                headers->for_each(http_pass_header, &info); 
                    467:                                user_agent_specified=info.user_agent_specified;
                    468:                        } else
                    469:                                throw Exception("parser.runtime", 
                    470:                                        &connect_string,
                    471:                                        "headers param must be hash"); 
                    472:                };
                    473:                if(!user_agent_specified) // defaulting
                    474:                        request << "user-agent: " DEFAULT_USER_AGENT CRLF;
                    475:                request << CRLF; 
                    476: 
                    477:                request_cstr=request.cstr(String::L_UNSPECIFIED);
                    478:        }
                    479:        // recode those pieces which are not in String::L_URI lang 
                    480:        // [those violating HTTP standard, but widly used]
                    481:        request_cstr=Charset::transcode(
                    482:                String::C(request_cstr, strlen(request_cstr)),
                    483:                charsets.source(),
                    484:                *asked_remote_charset);
1.126     paf       485:        
                    486:        //sending request
1.154     paf       487:        String response;
1.142     paf       488:        int status_code=http_request(response,
1.154     paf       489:                host, port, request_cstr, 
1.142     paf       490:                timeout, fail_on_status_ne_200); 
1.126     paf       491:        
                    492:        //processing results    
1.154     paf       493:        size_t pos=response.pos(CRLF CRLF, 4); 
                    494:        if(pos==STRING_NOT_FOUND || pos<1) {
1.126     paf       495:                throw Exception("http.response", 
1.133     paf       496:                        &connect_string,
1.126     paf       497:                        "bad response from host - no headers found"); 
                    498:        }
1.154     paf       499:        const String& header_block=response.mid(0, pos); 
                    500:        const String& raw_body=response.mid(pos+4, response.length()); 
1.126     paf       501:        
1.154     paf       502:        ArrayString aheaders;
                    503:        result.headers=new HashStringValue;
1.155     paf       504:        VHash* vtables=new VHash;
                    505:        result.headers->put(http_tables_name, vtables);
                    506:        HashStringValue& tables=vtables->hash();
                    507: 
1.154     paf       508:        size_t pos_after=0;
                    509:        header_block.split(aheaders, pos_after, CRLF); 
1.126     paf       510:        
                    511:        //processing headers
1.154     paf       512:        size_t aheaders_count=aheaders.count();
                    513:        Charset* real_remote_charset=0; // undetected, yet
                    514:        for(size_t i=1; i<aheaders_count; i++) {
                    515:                const String& line=*aheaders.get(i);
                    516:                pos=line.pos(": ", 2); 
                    517:                if(pos==STRING_NOT_FOUND || pos<1)
1.126     paf       518:                        throw Exception("http.response", 
1.154     paf       519:                                &connect_string,
                    520:                                "bad response from host - bad header \"%s\"", line.cstr());
1.156     paf       521:                const String::Body HEADER_NAME=
1.154     paf       522:                        line.mid(0, pos).change_case(charsets.source(), String::CC_UPPER);
                    523:                const String& header_value=line.mid(pos+2, line.length());
                    524:                if(HEADER_NAME=="CONTENT-TYPE")
                    525:                        real_remote_charset=detect_charset(charsets.source(), header_value);
1.155     paf       526: 
                    527:                // tables
                    528:                {
                    529:                        Value *valready=(Value *)tables.get(HEADER_NAME);
                    530:                        bool existed=valready!=0;
                    531:                        Table *table;
                    532:                        if(existed) {
                    533:                                // second+ appearence
                    534:                                table=valready->get_table();
                    535:                        } else {
                    536:                                // first appearence
                    537:                                Table::columns_type columns =new ArrayString(1);
                    538:                                *columns+=new String("value");
                    539:                                table=new Table(columns);
                    540:                        }
                    541:                        // this string becomes next row
                    542:                        ArrayString& row=*new ArrayString(1);
                    543:                        row+=&header_value;
                    544:                        *table+=&row;
                    545:                        // not existed before? add it
                    546:                        if(!existed)
                    547:                                tables.put(HEADER_NAME, new VTable(table));
                    548:                }
                    549: 
1.154     paf       550:                result.headers->put(HEADER_NAME, new VString(header_value));
1.126     paf       551:        }
1.154     paf       552:        // defaulting to used-asked charset [it's never empty!]
                    553:        if(!real_remote_charset)
                    554:                real_remote_charset=asked_remote_charset;
1.126     paf       555: 
                    556:        // output response
1.154     paf       557:        String::C real_body=Charset::transcode(
                    558:                String::C(raw_body.cstrm()/*must be modifiable*/, raw_body.length()),
                    559:                *real_remote_charset,
                    560:                charsets.source());
                    561: 
                    562:        result.str=const_cast<char *>(real_body.str); // hacking a little
                    563:        result.length=real_body.length;
                    564:        result.headers->put(file_status_name, new VInt(status_code));
                    565:        return result;
1.34      paf       566: }
1.123     paf       567: 
1.154     paf       568: #endif
                    569: 
1.123     paf       570: #ifndef DOXYGEN
                    571: struct File_read_action_info {
1.154     paf       572:        char **data; size_t *data_size;
1.126     paf       573: }; 
1.123     paf       574: #endif
1.154     paf       575: static void file_read_action(
                    576:                             struct stat& finfo, 
                    577:                             int f, 
                    578:                             const String& file_spec, const char* fname, bool as_text, 
                    579:                             void *context) {
1.126     paf       580:        File_read_action_info& info=*static_cast<File_read_action_info *>(context); 
1.123     paf       581:        if(size_t to_read_size=(size_t)finfo.st_size) { 
1.154     paf       582:                *info.data=new(PointerFreeGC) char[to_read_size+(as_text?1:0)]; 
1.126     paf       583:                *info.data_size=(size_t)read(f, *info.data, to_read_size); 
1.123     paf       584: 
                    585:                if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126     paf       586:                        throw Exception(0, 
1.123     paf       587:                                &file_spec, 
1.160     paf       588:                                "read failed: actually read %l bytes count not in [0..%lu] valid range", 
1.126     paf       589:                                        *info.data_size, to_read_size); 
1.123     paf       590:        } else { // empty file
                    591:                if(as_text) {
1.154     paf       592:                        *info.data=new(PointerFreeGC) char[1]; 
1.123     paf       593:                        *(char*)(*info.data)=0;
                    594:                } else 
                    595:                        *info.data=0;
                    596:                *info.data_size=0;
                    597:                return;
                    598:        }
1.126     paf       599: }
1.154     paf       600: File_read_result file_read(Request_charsets& charsets, const String& file_spec, 
                    601:                           bool as_text, HashStringValue *params,
1.126     paf       602:                           bool fail_on_read_problem) {
1.154     paf       603:        File_read_result result={false};
                    604: #ifdef PA_HTTP
                    605:        if(file_spec.starts_with("http://")) {
1.126     paf       606:                // fail on read problem
1.154     paf       607:                File_read_http_result http=file_read_http(charsets, file_spec, params);
                    608:                result.success=true;
                    609:                result.str=http.str;
                    610:                result.length=http.length;
                    611:                result.headers=http.headers; 
1.126     paf       612:        } else {
1.154     paf       613: #endif
1.161     paf       614:                if(params && params->count())
                    615:                        throw Exception("parser.runtime",
                    616:                                0,
                    617:                                "invalid option passed");
                    618: 
1.154     paf       619:                File_read_action_info info={&result.str, &result.length}; 
                    620:                result.success=file_read_action_under_lock(file_spec, 
1.126     paf       621:                        "read", file_read_action, &info, 
                    622:                        as_text, fail_on_read_problem); 
1.154     paf       623: #ifdef PA_HTTP
1.126     paf       624:        }
1.154     paf       625: #endif
1.123     paf       626: 
1.154     paf       627:        if(result.success && as_text) {
1.131     paf       628:                // UTF-8 signature: EF BB BF
1.154     paf       629:                if(result.length>=3) {
                    630:                        char *in=(char *)result.str;
1.159     paf       631:                        if(strncmp(in, "\xEF\xBB\xBF", 3)==0) {
1.154     paf       632:                                result.str=in+3; result.length-=3;// skip prefix
1.131     paf       633:                        }
                    634:                }
                    635: 
1.154     paf       636:                fix_line_breaks((char *)(result.str), result.length); 
1.123     paf       637:                // note: after fixing
1.154     paf       638:                ((char*&)(result.str))[result.length]=0;
1.123     paf       639:        }
1.126     paf       640: 
                    641:        return result;
1.123     paf       642: }
                    643: 
1.154     paf       644: #ifdef PA_SAFE_MODE 
                    645: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) { 
                    646:        if(finfo.st_uid/*foreign?*/!=geteuid() 
                    647:                && finfo.st_gid/*foreign?*/!=getegid()) 
                    648:                throw Exception("parser.runtime",  
                    649:                        &file_spec,  
                    650:                        "parser is in safe mode: " 
                    651:                        "reading files of foreign group and user disabled " 
                    652:                        "[recompile parser with --disable-safe-mode configure option], " 
                    653:                        "actual filename '%s', " 
                    654:                        "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",  
                    655:                                fname, 
                    656:                                finfo.st_uid, geteuid(), 
                    657:                                finfo.st_gid, getegid()); 
                    658: } 
                    659: #endif 
1.149     paf       660: 
1.154     paf       661: bool file_read_action_under_lock(const String& file_spec, 
1.126     paf       662:                                const char* action_name, File_read_action action, void *context, 
                    663:                                bool as_text, 
1.123     paf       664:                                bool fail_on_read_problem) {
1.154     paf       665:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.33      paf       666:        int f;
                    667: 
                    668:        // first open, next stat:
1.45      paf       669:        // directory update of NTFS hard links performed on open.
1.33      paf       670:        // ex: 
                    671:        //   a.html:^test[] and b.html hardlink to a.html
                    672:        //   user inserts ! before ^test in a.html
1.126     paf       673:        //   directory entry of b.html in NTFS not updated at once, 
1.35      paf       674:        //   they delay update till open, so we would receive "!^test[" string
                    675:        //   if would do stat, next open.
1.123     paf       676:        // later: it seems, even this does not help sometimes
1.98      paf       677:     if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123     paf       678:                try {
1.162   ! paf       679:                        if(pa_lock_shared_blocking(f)!=0)
1.126     paf       680:                                throw Exception("file.lock", 
1.123     paf       681:                                                &file_spec, 
                    682:                                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       683:                                                        strerror(errno), errno, fname);
1.123     paf       684: 
1.124     paf       685:                        struct stat finfo;
                    686:                        if(stat(fname, &finfo)!=0)
                    687:                                throw Exception("file.missing", // hardly possible: we just opened it OK
                    688:                                        &file_spec, 
                    689:                                        "stat failed: %s (%d), actual filename '%s'", 
1.154     paf       690:                                                strerror(errno), errno, fname);
1.124     paf       691: 
1.140     paf       692: #ifdef PA_SAFE_MODE
1.149     paf       693:                        check_safe_mode(finfo, file_spec, fname);
1.105     paf       694: #endif
1.32      paf       695: 
1.154     paf       696:                        action(finfo, f, file_spec, fname, as_text, context); 
1.123     paf       697:                } catch(...) {
1.162   ! paf       698:                        pa_unlock(f);close(f); 
1.123     paf       699:                        if(fail_on_read_problem)
1.154     paf       700:                                rethrow;
1.123     paf       701:                        return false;                   
                    702:                } 
1.87      paf       703: 
1.162   ! paf       704:                pa_unlock(f);close(f); 
1.72      parser    705:                return true;
1.118     paf       706:     } else {
                    707:                if(fail_on_read_problem)
1.126     paf       708:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.118     paf       709:                                &file_spec, 
1.123     paf       710:                                "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       711:                                        action_name, strerror(errno), errno, fname);
1.118     paf       712:                return false;
                    713:        }
1.8       paf       714: }
                    715: 
1.63      parser    716: static void create_dir_for_file(const String& file_spec) {
                    717:        size_t pos_after=1;
1.154     paf       718:        size_t pos_before;
                    719:        while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
                    720:                mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775); 
1.63      parser    721:                pos_after=pos_before+1;
                    722:        }
                    723: }
                    724: 
1.98      paf       725: bool file_write_action_under_lock(
1.28      paf       726:                                const String& file_spec, 
1.126     paf       727:                                const char* action_name, File_write_action action, void *context, 
                    728:                                bool as_text, 
                    729:                                bool do_append, 
                    730:                                bool do_block, 
1.110     paf       731:                                bool fail_on_lock_problem) {
1.154     paf       732:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.28      paf       733:        int f;
1.80      paf       734:        if(access(fname, W_OK)!=0) // no
1.126     paf       735:                create_dir_for_file(file_spec); 
1.50      paf       736: 
1.80      paf       737:        if((f=open(fname, 
                    738:                O_CREAT|O_RDWR
                    739:                |(as_text?_O_TEXT:_O_BINARY)
1.138     paf       740:                |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162   ! paf       741:                if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126     paf       742:                        Exception e("file.lock", 
1.110     paf       743:                                &file_spec, 
                    744:                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       745:                                strerror(errno), errno, fname);
1.126     paf       746:                        close(f); 
1.110     paf       747:                        if(fail_on_lock_problem)
                    748:                                throw e;
1.98      paf       749:                        return false;
                    750:                }
1.96      paf       751: 
1.158     paf       752:                try {
1.126     paf       753:                        action(f, context); 
1.158     paf       754:                } catch(...) {
1.138     paf       755: #ifdef HAVE_FTRUNCATE
1.104     paf       756:                        if(!do_append)
1.125     paf       757:                                ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138     paf       758: #endif
1.162   ! paf       759:                        pa_unlock(f);close(f); 
1.154     paf       760:                        rethrow;
1.158     paf       761:                }
1.80      paf       762:                
1.138     paf       763: #ifdef HAVE_FTRUNCATE
1.104     paf       764:                if(!do_append)
1.125     paf       765:                        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       766: #endif
1.162   ! paf       767:                pa_unlock(f);close(f); 
1.98      paf       768:                return true;
1.80      paf       769:        } else
1.126     paf       770:                throw Exception(errno==EACCES?"file.access":0, 
1.80      paf       771:                        &file_spec, 
1.96      paf       772:                        "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       773:                                action_name, strerror(errno), errno, fname);
1.96      paf       774:        // here should be nothing, see rethrow above
                    775: }
                    776: 
                    777: #ifndef DOXYGEN
                    778: struct File_write_action_info {
1.154     paf       779:        const char* str; size_t length;
1.126     paf       780: }; 
1.96      paf       781: #endif
                    782: static void file_write_action(int f, void *context) {
1.126     paf       783:        File_write_action_info& info=*static_cast<File_write_action_info *>(context); 
1.154     paf       784:        if(info.length) {
                    785:                int written=write(f, info.str, info.length); 
1.116     paf       786:                if(written<0)
1.126     paf       787:                        throw Exception(0, 
                    788:                                0, 
                    789:                                "write failed: %s (%d)",  strerror(errno), errno); 
1.113     paf       790:        }
1.96      paf       791: }
                    792: void file_write(
                    793:                                const String& file_spec, 
1.154     paf       794:                                const char* data, size_t size, 
1.126     paf       795:                                bool as_text, 
1.96      paf       796:                                bool do_append) {
1.126     paf       797:        File_write_action_info info={data, size}; 
1.98      paf       798:        file_write_action_under_lock(
1.154     paf       799:                file_spec, 
                    800:                "write", file_write_action, &info, 
                    801:                as_text, 
                    802:                do_append); 
1.30      paf       803: }
                    804: 
1.63      parser    805: // throws nothing! [this is required in file_move & file_delete]
1.50      paf       806: static void rmdir(const String& file_spec, size_t pos_after) {
1.154     paf       807:        size_t pos_before;
                    808:        if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126     paf       809:                rmdir(file_spec, pos_before+1); 
1.50      paf       810:        
1.154     paf       811:        rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC)); 
1.50      paf       812: }
1.95      paf       813: bool file_delete(const String& file_spec, bool fail_on_read_problem) {
1.154     paf       814:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.54      parser    815:        if(unlink(fname)!=0)
1.93      paf       816:                if(fail_on_read_problem)
1.126     paf       817:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.93      paf       818:                                &file_spec, 
                    819:                                "unlink failed: %s (%d), actual filename '%s'", 
1.154     paf       820:                                        strerror(errno), errno, fname);
1.93      paf       821:                else
                    822:                        return false;
1.50      paf       823: 
1.126     paf       824:        rmdir(file_spec, 1); 
1.93      paf       825:        return true;
1.60      parser    826: }
1.95      paf       827: void file_move(const String& old_spec, const String& new_spec) {
1.154     paf       828:        const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC); 
                    829:        const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC); 
1.63      parser    830:        
1.126     paf       831:        create_dir_for_file(new_spec); 
1.63      parser    832: 
1.60      parser    833:        if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126     paf       834:                throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.60      parser    835:                        &old_spec, 
                    836:                        "rename failed: %s (%d), actual filename '%s' to '%s'", 
1.154     paf       837:                                strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63      parser    838: 
1.126     paf       839:        rmdir(old_spec, 1); 
1.31      paf       840: }
                    841: 
1.51      paf       842: 
1.126     paf       843: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118     paf       844:        struct stat lfinfo;
                    845:        bool result=stat(fname, &lfinfo)==0;
                    846:        if(afinfo)
                    847:                *afinfo=lfinfo;
                    848:        return result;
1.119     paf       849: }
                    850: 
                    851: bool entry_exists(const String& file_spec) {
1.154     paf       852:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.126     paf       853:        return entry_exists(fname, 0); 
1.118     paf       854: }
                    855: 
1.51      paf       856: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154     paf       857:        char* fname=file_spec.cstrm(String::L_FILE_SPEC); 
1.120     paf       858:        if(need_dir) {
1.126     paf       859:                size_t size=strlen(fname); 
1.120     paf       860:                while(size) {
1.126     paf       861:                        char c=fname[size-1]; 
1.120     paf       862:                        if(c=='/' || c=='\\')
                    863:                                fname[--size]=0;
                    864:                        else
                    865:                                break;
                    866:                }
                    867:        }
1.51      paf       868:        struct stat finfo;
1.118     paf       869:        if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109     paf       870:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51      paf       871:                return is_dir==need_dir;
                    872:        }
                    873:        return false;
                    874: }
1.31      paf       875: bool file_readable(const String& file_spec) {
1.126     paf       876:        return entry_readable(file_spec, false); 
1.51      paf       877: }
                    878: bool dir_readable(const String& file_spec) {
1.126     paf       879:        return entry_readable(file_spec, true); 
1.65      parser    880: }
1.154     paf       881: const String* file_readable(const String& path, const String& name) {
                    882:        String& result=*new String(path);
                    883:        result << "/"; 
                    884:        result << name;
                    885:        return file_readable(result)?&result:0;
1.43      paf       886: }
                    887: bool file_executable(const String& file_spec) {
1.154     paf       888:     return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44      paf       889: }
                    890: 
1.64      parser    891: bool file_stat(const String& file_spec, 
1.58      parser    892:                           size_t& rsize, 
1.126     paf       893:                           time_t& ratime, 
                    894:                           time_t& rmtime, 
                    895:                           time_t& rctime, 
1.64      parser    896:                           bool fail_on_read_problem) {
1.154     paf       897:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
                    898:        struct stat finfo;
1.44      paf       899:        if(stat(fname, &finfo)!=0)
1.64      parser    900:                if(fail_on_read_problem)
1.126     paf       901:                        throw Exception("file.missing", 
1.67      parser    902:                                &file_spec, 
                    903:                                "getting file size failed: %s (%d), real filename '%s'", 
1.154     paf       904:                                        strerror(errno), errno, fname);
1.64      parser    905:                else
                    906:                        return false;
1.58      parser    907:        rsize=finfo.st_size;
                    908:        ratime=finfo.st_atime;
                    909:        rmtime=finfo.st_mtime;
                    910:        rctime=finfo.st_ctime;
1.64      parser    911:        return true;
1.18      paf       912: }
                    913: 
1.126     paf       914: char* getrow(char* *row_ref, char delim) {
                    915:     char* result=*row_ref;
1.8       paf       916:     if(result) {
1.126     paf       917:                *row_ref=strchr(result, delim); 
1.8       paf       918:                if(*row_ref) 
                    919:                        *((*row_ref)++)=0; 
                    920:                else if(!*result) 
                    921:                        return 0;
                    922:     }
                    923:     return result;
                    924: }
                    925: 
1.126     paf       926: char* lsplit(char* string, char delim) {
1.23      paf       927:     if(string) {
1.126     paf       928:                char* v=strchr(string, delim); 
1.8       paf       929:                if(v) {
                    930:                        *v=0;
                    931:                        return v+1;
                    932:                }
                    933:     }
                    934:     return 0;
                    935: }
                    936: 
1.126     paf       937: char* lsplit(char* *string_ref, char delim) {
                    938:     char* result=*string_ref;
                    939:        char* next=lsplit(*string_ref, delim); 
1.8       paf       940:     *string_ref=next;
                    941:     return result;
1.9       paf       942: }
                    943: 
1.126     paf       944: char* rsplit(char* string, char delim) {
1.18      paf       945:     if(string) {
1.126     paf       946:                char* v=strrchr(string, delim); 
1.18      paf       947:                if(v) {
1.9       paf       948:                        *v=0;
                    949:                        return v+1;
                    950:                }
                    951:     }
                    952:     return NULL;       
1.10      paf       953: }
                    954: 
1.37      paf       955: /// @todo less stupid type detection
1.154     paf       956: const char* format(double value, char* fmt) {
1.126     paf       957:        char local_buf[MAX_NUMBER]; 
1.108     paf       958:        size_t size;
                    959:        
1.10      paf       960:        if(fmt)
                    961:                if(strpbrk(fmt, "diouxX"))
                    962:                        if(strpbrk(fmt, "ouxX"))
1.126     paf       963:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.10      paf       964:                        else
1.126     paf       965:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
1.10      paf       966:                else
1.126     paf       967:                        size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
1.10      paf       968:        else
1.126     paf       969:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value); 
1.10      paf       970:        
1.154     paf       971:        return pa_strdup(local_buf, size);
1.12      paf       972: }
                    973: 
1.36      paf       974: size_t stdout_write(const void *buf, size_t size) {
1.12      paf       975: #ifdef WIN32
                    976:        do{
1.154     paf       977:                int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); 
1.12      paf       978:                if(chunk_written<=0)
                    979:                        break;
                    980:                size-=chunk_written;
1.36      paf       981:                buf=((const char*)buf)+chunk_written;
1.126     paf       982:        } while(size>0); 
1.12      paf       983: 
                    984:        return size;
                    985: #else
1.126     paf       986:        return fwrite(buf, 1, size, stdout); 
1.12      paf       987: #endif
1.2       paf       988: }
1.14      paf       989: 
1.154     paf       990: char* unescape_chars(const char* cp, int len) {
                    991:        char* s=new(PointerFreeGC) char[len + 1]; 
1.14      paf       992:        enum EscapeState {
1.33      paf       993:                EscapeRest, 
                    994:                EscapeFirst, 
1.14      paf       995:                EscapeSecond
                    996:        } escapeState=EscapeRest;
                    997:        int escapedValue=0;
                    998:        int srcPos=0;
                    999:        int dstPos=0;
                   1000:        while(srcPos < len) {
1.126     paf      1001:                int ch=cp[srcPos]; 
1.14      paf      1002:                switch(escapeState) {
                   1003:                        case EscapeRest:
                   1004:                        if(ch=='%') {
                   1005:                                escapeState=EscapeFirst;
                   1006:                        } else if(ch=='+') {
1.126     paf      1007:                                s[dstPos++]=' '; 
1.14      paf      1008:                        } else {
                   1009:                                s[dstPos++]=ch; 
                   1010:                        }
                   1011:                        break;
                   1012:                        case EscapeFirst:
                   1013:                        escapedValue=hex_value[ch] << 4;        
                   1014:                        escapeState=EscapeSecond;
                   1015:                        break;
                   1016:                        case EscapeSecond:
1.126     paf      1017:                        escapedValue +=hex_value[ch]; 
1.14      paf      1018:                        s[dstPos++]=escapedValue;
                   1019:                        escapeState=EscapeRest;
                   1020:                        break;
                   1021:                }
1.126     paf      1022:                srcPos++; 
1.14      paf      1023:        }
                   1024:        s[dstPos]=0;
                   1025:        return s;
1.24      paf      1026: }
                   1027: 
                   1028: #ifdef WIN32
1.126     paf      1029: void back_slashes_to_slashes(char* s) {
1.24      paf      1030:        if(s)
                   1031:                for(; *s; s++)
                   1032:                        if(*s=='\\')
1.126     paf      1033:                                *s='/'; 
1.24      paf      1034: }
1.42      paf      1035: /*
1.126     paf      1036: void slashes_to_back_slashes(char* s) {
1.42      paf      1037:        if(s)
                   1038:                for(; *s; s++)
                   1039:                        if(*s=='/')
1.126     paf      1040:                                *s='\\'; 
1.42      paf      1041: }
                   1042: */
1.24      paf      1043: #endif
1.41      paf      1044: 
1.126     paf      1045: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41      paf      1046:        while(true) {
                   1047:                if(!(*s1)) {
                   1048:                        if(!(*s2))
                   1049:                                return true;
                   1050:                        else
                   1051:                                return !strict;
                   1052:                } else if(!(*s2))
                   1053:                        return !strict;
                   1054:                if(isalpha(*s1)) {
                   1055:                        if(tolower(*s1) !=tolower(*s2))
                   1056:                                return false;
                   1057:                } else if((*s1) !=(*s2))
                   1058:                        return false;
1.126     paf      1059:                s1++; 
                   1060:                s2++; 
1.41      paf      1061:        }
1.57      parser   1062: }
                   1063: 
1.84      paf      1064: static bool isLeap(int year) {
1.57      parser   1065:     return !(
                   1066:              (year % 4) || ((year % 400) && !(year % 100))
1.126     paf      1067:             ); 
1.57      parser   1068: }
                   1069: 
                   1070: int getMonthDays(int year, int month) {
                   1071:     int monthDays[]={
1.126     paf      1072:         31, 
                   1073:         isLeap(year) ? 29 : 28, 
                   1074:         31, 
                   1075:         30, 
                   1076:         31, 
                   1077:         30, 
                   1078:         31, 
                   1079:         31, 
                   1080:         30, 
                   1081:         31, 
                   1082:         30, 
1.57      parser   1083:         31
1.126     paf      1084:     }; 
                   1085:     return monthDays[month]; 
1.41      paf      1086: }
1.69      parser   1087: 
1.126     paf      1088: void remove_crlf(char* start, char* end) {
                   1089:        for(char* p=start; p<end; p++)
1.69      parser   1090:                switch(*p) {
1.126     paf      1091:                        case '\n': *p='|';  break;
                   1092:                        case '\r': *p=' ';  break;
1.69      parser   1093:                }
1.91      paf      1094: }
                   1095: 
                   1096: 
                   1097: /// must be last in this file
                   1098: #undef vsnprintf
1.126     paf      1099: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91      paf      1100:        if(!s)
                   1101:                return 0;
                   1102: 
                   1103:        int r;
                   1104:        // note: on win32& maybe somewhere else
                   1105:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                   1106:        --s;
                   1107: #if _MSC_VER
                   1108:        /*
                   1109:        win32: 
                   1110:        mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
                   1111: 
1.154     paf      1112:          if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91      paf      1113:        */
1.126     paf      1114:        r=_vsnprintf(b, s, f, l); 
1.91      paf      1115:        if(r<0) 
                   1116:                r=s;
                   1117: #else
1.126     paf      1118:        r=vsnprintf(b, s, f, l); 
1.91      paf      1119:        /*
                   1120:        solaris: 
                   1121:        man vsnprintf
                   1122: 
                   1123:          The snprintf() function returns  the  number  of  characters
                   1124:        formatted, that is, the number of characters that would have
                   1125:        been written to the buffer if it were large enough.  If  the
                   1126:        value  of  n  is  0  on a call to snprintf(), an unspecified
                   1127:        value less than 1 is returned.
                   1128:        */
                   1129: 
                   1130:        if(r<0)
                   1131:                r=0;
                   1132:        else if(r>s)
                   1133:                r=s;
                   1134: #endif
                   1135:        b[r]=0;
                   1136:        return r;
                   1137: }
                   1138: 
1.126     paf      1139: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91      paf      1140:        va_list l;
1.126     paf      1141:     va_start(l, f); 
                   1142:     int r=__vsnprintf(b, s, f, l); 
                   1143:     va_end(l); 
1.91      paf      1144:        return r;
1.98      paf      1145: }

E-mail: