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

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.157   ! paf         8: static const char* IDENT_COMMON_C="$Date: 2003/09/25 09:15:03 $"; 
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: 
                     74: static int lock_shared_blocking(int fd) { return flock(fd, LOCK_SH); }
                     75: static int lock_exclusive_blocking(int fd) { return flock(fd, LOCK_EX); }
                     76: static int lock_exclusive_nonblocking(int fd) { return flock(fd, LOCK_EX || LOCK_NB); }
                     77: static int unlock(int fd) { return flock(fd, LOCK_UN); }
                     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.99      paf        83: static int lock_shared_blocking(int fd) { FLOCK(_LK_LOCK); }
                     84: static int lock_exclusive_blocking(int fd) { FLOCK(_LK_LOCK); }
                     85: static int lock_exclusive_nonblocking(int fd) { FLOCK(_LK_NBLCK); }
                     86: static int 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.99      paf        92: static int lock_shared_blocking(int fd) { FLOCK(F_SETLKW, F_RDLCK); }
                     93: static int lock_exclusive_blocking(int fd) { FLOCK(F_SETLKW, F_WRLCK); }
                     94: static int lock_exclusive_nonblocking(int fd) { FLOCK(F_SETLK, F_RDLCK); }
                     95: static int 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.99      paf       101: static int lock_shared_blocking(int fd) { FLOCK(F_LOCK); } // on intel solaris man doesn't have doc on shared blocking
                    102: static int lock_exclusive_blocking(int fd) { FLOCK(F_LOCK); }
                    103: static int lock_exclusive_nonblocking(int fd) { FLOCK(F_TLOCK); }
                    104: static int unlock(int fd) { FLOCK(F_TLOCK); }
                    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
                    116: static int lock_shared_blocking(int fd) { return 0; }
                    117: static int lock_exclusive_blocking(int fd) { return 0; }
                    118: static int lock_exclusive_nonblocking(int fd) { return 0; }
                    119: static int unlock(int fd) { return 0; }
                    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, 
                    588:                                "read failed: actually read %lu 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
                    614:                File_read_action_info info={&result.str, &result.length}; 
                    615:                result.success=file_read_action_under_lock(file_spec, 
1.126     paf       616:                        "read", file_read_action, &info, 
                    617:                        as_text, fail_on_read_problem); 
1.154     paf       618: #ifdef PA_HTTP
1.126     paf       619:        }
1.154     paf       620: #endif
1.123     paf       621: 
1.154     paf       622:        if(result.success && as_text) {
1.131     paf       623:                // UTF-8 signature: EF BB BF
1.154     paf       624:                if(result.length>=3) {
                    625:                        char *in=(char *)result.str;
                    626:                        if(strncmp(in, "\xEB\xBB\xBF", 3)==0) {
                    627:                                result.str=in+3; result.length-=3;// skip prefix
1.131     paf       628:                        }
                    629:                }
                    630: 
1.154     paf       631:                fix_line_breaks((char *)(result.str), result.length); 
1.123     paf       632:                // note: after fixing
1.154     paf       633:                ((char*&)(result.str))[result.length]=0;
1.123     paf       634:        }
1.126     paf       635: 
                    636:        return result;
1.123     paf       637: }
                    638: 
1.154     paf       639: #ifdef PA_SAFE_MODE 
                    640: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) { 
                    641:        if(finfo.st_uid/*foreign?*/!=geteuid() 
                    642:                && finfo.st_gid/*foreign?*/!=getegid()) 
                    643:                throw Exception("parser.runtime",  
                    644:                        &file_spec,  
                    645:                        "parser is in safe mode: " 
                    646:                        "reading files of foreign group and user disabled " 
                    647:                        "[recompile parser with --disable-safe-mode configure option], " 
                    648:                        "actual filename '%s', " 
                    649:                        "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",  
                    650:                                fname, 
                    651:                                finfo.st_uid, geteuid(), 
                    652:                                finfo.st_gid, getegid()); 
                    653: } 
                    654: #endif 
1.149     paf       655: 
1.154     paf       656: bool file_read_action_under_lock(const String& file_spec, 
1.126     paf       657:                                const char* action_name, File_read_action action, void *context, 
                    658:                                bool as_text, 
1.123     paf       659:                                bool fail_on_read_problem) {
1.154     paf       660:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.33      paf       661:        int f;
                    662: 
                    663:        // first open, next stat:
1.45      paf       664:        // directory update of NTFS hard links performed on open.
1.33      paf       665:        // ex: 
                    666:        //   a.html:^test[] and b.html hardlink to a.html
                    667:        //   user inserts ! before ^test in a.html
1.126     paf       668:        //   directory entry of b.html in NTFS not updated at once, 
1.35      paf       669:        //   they delay update till open, so we would receive "!^test[" string
                    670:        //   if would do stat, next open.
1.123     paf       671:        // later: it seems, even this does not help sometimes
1.98      paf       672:     if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123     paf       673:                try {
                    674:                        if(lock_shared_blocking(f)!=0)
1.126     paf       675:                                throw Exception("file.lock", 
1.123     paf       676:                                                &file_spec, 
                    677:                                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       678:                                                        strerror(errno), errno, fname);
1.123     paf       679: 
1.124     paf       680:                        struct stat finfo;
                    681:                        if(stat(fname, &finfo)!=0)
                    682:                                throw Exception("file.missing", // hardly possible: we just opened it OK
                    683:                                        &file_spec, 
                    684:                                        "stat failed: %s (%d), actual filename '%s'", 
1.154     paf       685:                                                strerror(errno), errno, fname);
1.124     paf       686: 
1.140     paf       687: #ifdef PA_SAFE_MODE
1.149     paf       688:                        check_safe_mode(finfo, file_spec, fname);
1.105     paf       689: #endif
1.32      paf       690: 
1.154     paf       691:                        action(finfo, f, file_spec, fname, as_text, context); 
1.123     paf       692:                } catch(...) {
1.126     paf       693:                        unlock(f);close(f); 
1.123     paf       694:                        if(fail_on_read_problem)
1.154     paf       695:                                rethrow;
1.123     paf       696:                        return false;                   
                    697:                } 
1.87      paf       698: 
1.126     paf       699:                unlock(f);close(f); 
1.72      parser    700:                return true;
1.118     paf       701:     } else {
                    702:                if(fail_on_read_problem)
1.126     paf       703:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.118     paf       704:                                &file_spec, 
1.123     paf       705:                                "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       706:                                        action_name, strerror(errno), errno, fname);
1.118     paf       707:                return false;
                    708:        }
1.8       paf       709: }
                    710: 
1.63      parser    711: static void create_dir_for_file(const String& file_spec) {
                    712:        size_t pos_after=1;
1.154     paf       713:        size_t pos_before;
                    714:        while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
                    715:                mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775); 
1.63      parser    716:                pos_after=pos_before+1;
                    717:        }
                    718: }
                    719: 
1.98      paf       720: bool file_write_action_under_lock(
1.28      paf       721:                                const String& file_spec, 
1.126     paf       722:                                const char* action_name, File_write_action action, void *context, 
                    723:                                bool as_text, 
                    724:                                bool do_append, 
                    725:                                bool do_block, 
1.110     paf       726:                                bool fail_on_lock_problem) {
1.154     paf       727:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.28      paf       728:        int f;
1.80      paf       729:        if(access(fname, W_OK)!=0) // no
1.126     paf       730:                create_dir_for_file(file_spec); 
1.50      paf       731: 
1.80      paf       732:        if((f=open(fname, 
                    733:                O_CREAT|O_RDWR
                    734:                |(as_text?_O_TEXT:_O_BINARY)
1.138     paf       735:                |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.99      paf       736:                if((do_block?lock_exclusive_blocking(f):lock_exclusive_nonblocking(f))!=0) {
1.126     paf       737:                        Exception e("file.lock", 
1.110     paf       738:                                &file_spec, 
                    739:                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       740:                                strerror(errno), errno, fname);
1.126     paf       741:                        close(f); 
1.110     paf       742:                        if(fail_on_lock_problem)
                    743:                                throw e;
1.98      paf       744:                        return false;
                    745:                }
1.96      paf       746: 
1.157   ! paf       747: ///            try {
1.126     paf       748:                        action(f, context); 
1.157   ! paf       749:                /*} catch(...) {
1.138     paf       750: #ifdef HAVE_FTRUNCATE
1.104     paf       751:                        if(!do_append)
1.125     paf       752:                                ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138     paf       753: #endif
1.126     paf       754:                        unlock(f);close(f); 
1.154     paf       755:                        rethrow;
1.157   ! paf       756:                }*/
1.80      paf       757:                
1.138     paf       758: #ifdef HAVE_FTRUNCATE
1.104     paf       759:                if(!do_append)
1.125     paf       760:                        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       761: #endif
1.126     paf       762:                unlock(f);close(f); 
1.98      paf       763:                return true;
1.80      paf       764:        } else
1.126     paf       765:                throw Exception(errno==EACCES?"file.access":0, 
1.80      paf       766:                        &file_spec, 
1.96      paf       767:                        "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       768:                                action_name, strerror(errno), errno, fname);
1.96      paf       769:        // here should be nothing, see rethrow above
                    770: }
                    771: 
                    772: #ifndef DOXYGEN
                    773: struct File_write_action_info {
1.154     paf       774:        const char* str; size_t length;
1.126     paf       775: }; 
1.96      paf       776: #endif
                    777: static void file_write_action(int f, void *context) {
1.126     paf       778:        File_write_action_info& info=*static_cast<File_write_action_info *>(context); 
1.154     paf       779:        if(info.length) {
                    780:                int written=write(f, info.str, info.length); 
1.116     paf       781:                if(written<0)
1.126     paf       782:                        throw Exception(0, 
                    783:                                0, 
                    784:                                "write failed: %s (%d)",  strerror(errno), errno); 
1.113     paf       785:        }
1.96      paf       786: }
                    787: void file_write(
                    788:                                const String& file_spec, 
1.154     paf       789:                                const char* data, size_t size, 
1.126     paf       790:                                bool as_text, 
1.96      paf       791:                                bool do_append) {
1.126     paf       792:        File_write_action_info info={data, size}; 
1.98      paf       793:        file_write_action_under_lock(
1.154     paf       794:                file_spec, 
                    795:                "write", file_write_action, &info, 
                    796:                as_text, 
                    797:                do_append); 
1.30      paf       798: }
                    799: 
1.63      parser    800: // throws nothing! [this is required in file_move & file_delete]
1.50      paf       801: static void rmdir(const String& file_spec, size_t pos_after) {
1.154     paf       802:        size_t pos_before;
                    803:        if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126     paf       804:                rmdir(file_spec, pos_before+1); 
1.50      paf       805:        
1.154     paf       806:        rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC)); 
1.50      paf       807: }
1.95      paf       808: bool file_delete(const String& file_spec, bool fail_on_read_problem) {
1.154     paf       809:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.54      parser    810:        if(unlink(fname)!=0)
1.93      paf       811:                if(fail_on_read_problem)
1.126     paf       812:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.93      paf       813:                                &file_spec, 
                    814:                                "unlink failed: %s (%d), actual filename '%s'", 
1.154     paf       815:                                        strerror(errno), errno, fname);
1.93      paf       816:                else
                    817:                        return false;
1.50      paf       818: 
1.126     paf       819:        rmdir(file_spec, 1); 
1.93      paf       820:        return true;
1.60      parser    821: }
1.95      paf       822: void file_move(const String& old_spec, const String& new_spec) {
1.154     paf       823:        const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC); 
                    824:        const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC); 
1.63      parser    825:        
1.126     paf       826:        create_dir_for_file(new_spec); 
1.63      parser    827: 
1.60      parser    828:        if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126     paf       829:                throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.60      parser    830:                        &old_spec, 
                    831:                        "rename failed: %s (%d), actual filename '%s' to '%s'", 
1.154     paf       832:                                strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63      parser    833: 
1.126     paf       834:        rmdir(old_spec, 1); 
1.31      paf       835: }
                    836: 
1.51      paf       837: 
1.126     paf       838: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118     paf       839:        struct stat lfinfo;
                    840:        bool result=stat(fname, &lfinfo)==0;
                    841:        if(afinfo)
                    842:                *afinfo=lfinfo;
                    843:        return result;
1.119     paf       844: }
                    845: 
                    846: bool entry_exists(const String& file_spec) {
1.154     paf       847:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.126     paf       848:        return entry_exists(fname, 0); 
1.118     paf       849: }
                    850: 
1.51      paf       851: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154     paf       852:        char* fname=file_spec.cstrm(String::L_FILE_SPEC); 
1.120     paf       853:        if(need_dir) {
1.126     paf       854:                size_t size=strlen(fname); 
1.120     paf       855:                while(size) {
1.126     paf       856:                        char c=fname[size-1]; 
1.120     paf       857:                        if(c=='/' || c=='\\')
                    858:                                fname[--size]=0;
                    859:                        else
                    860:                                break;
                    861:                }
                    862:        }
1.51      paf       863:        struct stat finfo;
1.118     paf       864:        if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109     paf       865:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51      paf       866:                return is_dir==need_dir;
                    867:        }
                    868:        return false;
                    869: }
1.31      paf       870: bool file_readable(const String& file_spec) {
1.126     paf       871:        return entry_readable(file_spec, false); 
1.51      paf       872: }
                    873: bool dir_readable(const String& file_spec) {
1.126     paf       874:        return entry_readable(file_spec, true); 
1.65      parser    875: }
1.154     paf       876: const String* file_readable(const String& path, const String& name) {
                    877:        String& result=*new String(path);
                    878:        result << "/"; 
                    879:        result << name;
                    880:        return file_readable(result)?&result:0;
1.43      paf       881: }
                    882: bool file_executable(const String& file_spec) {
1.154     paf       883:     return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44      paf       884: }
                    885: 
1.64      parser    886: bool file_stat(const String& file_spec, 
1.58      parser    887:                           size_t& rsize, 
1.126     paf       888:                           time_t& ratime, 
                    889:                           time_t& rmtime, 
                    890:                           time_t& rctime, 
1.64      parser    891:                           bool fail_on_read_problem) {
1.154     paf       892:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
                    893:        struct stat finfo;
1.44      paf       894:        if(stat(fname, &finfo)!=0)
1.64      parser    895:                if(fail_on_read_problem)
1.126     paf       896:                        throw Exception("file.missing", 
1.67      parser    897:                                &file_spec, 
                    898:                                "getting file size failed: %s (%d), real filename '%s'", 
1.154     paf       899:                                        strerror(errno), errno, fname);
1.64      parser    900:                else
                    901:                        return false;
1.58      parser    902:        rsize=finfo.st_size;
                    903:        ratime=finfo.st_atime;
                    904:        rmtime=finfo.st_mtime;
                    905:        rctime=finfo.st_ctime;
1.64      parser    906:        return true;
1.18      paf       907: }
                    908: 
1.126     paf       909: char* getrow(char* *row_ref, char delim) {
                    910:     char* result=*row_ref;
1.8       paf       911:     if(result) {
1.126     paf       912:                *row_ref=strchr(result, delim); 
1.8       paf       913:                if(*row_ref) 
                    914:                        *((*row_ref)++)=0; 
                    915:                else if(!*result) 
                    916:                        return 0;
                    917:     }
                    918:     return result;
                    919: }
                    920: 
1.126     paf       921: char* lsplit(char* string, char delim) {
1.23      paf       922:     if(string) {
1.126     paf       923:                char* v=strchr(string, delim); 
1.8       paf       924:                if(v) {
                    925:                        *v=0;
                    926:                        return v+1;
                    927:                }
                    928:     }
                    929:     return 0;
                    930: }
                    931: 
1.126     paf       932: char* lsplit(char* *string_ref, char delim) {
                    933:     char* result=*string_ref;
                    934:        char* next=lsplit(*string_ref, delim); 
1.8       paf       935:     *string_ref=next;
                    936:     return result;
1.9       paf       937: }
                    938: 
1.126     paf       939: char* rsplit(char* string, char delim) {
1.18      paf       940:     if(string) {
1.126     paf       941:                char* v=strrchr(string, delim); 
1.18      paf       942:                if(v) {
1.9       paf       943:                        *v=0;
                    944:                        return v+1;
                    945:                }
                    946:     }
                    947:     return NULL;       
1.10      paf       948: }
                    949: 
1.37      paf       950: /// @todo less stupid type detection
1.154     paf       951: const char* format(double value, char* fmt) {
1.126     paf       952:        char local_buf[MAX_NUMBER]; 
1.108     paf       953:        size_t size;
                    954:        
1.10      paf       955:        if(fmt)
                    956:                if(strpbrk(fmt, "diouxX"))
                    957:                        if(strpbrk(fmt, "ouxX"))
1.126     paf       958:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.10      paf       959:                        else
1.126     paf       960:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
1.10      paf       961:                else
1.126     paf       962:                        size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
1.10      paf       963:        else
1.126     paf       964:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value); 
1.10      paf       965:        
1.154     paf       966:        return pa_strdup(local_buf, size);
1.12      paf       967: }
                    968: 
1.36      paf       969: size_t stdout_write(const void *buf, size_t size) {
1.12      paf       970: #ifdef WIN32
                    971:        do{
1.154     paf       972:                int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); 
1.12      paf       973:                if(chunk_written<=0)
                    974:                        break;
                    975:                size-=chunk_written;
1.36      paf       976:                buf=((const char*)buf)+chunk_written;
1.126     paf       977:        } while(size>0); 
1.12      paf       978: 
                    979:        return size;
                    980: #else
1.126     paf       981:        return fwrite(buf, 1, size, stdout); 
1.12      paf       982: #endif
1.2       paf       983: }
1.14      paf       984: 
1.154     paf       985: char* unescape_chars(const char* cp, int len) {
                    986:        char* s=new(PointerFreeGC) char[len + 1]; 
1.14      paf       987:        enum EscapeState {
1.33      paf       988:                EscapeRest, 
                    989:                EscapeFirst, 
1.14      paf       990:                EscapeSecond
                    991:        } escapeState=EscapeRest;
                    992:        int escapedValue=0;
                    993:        int srcPos=0;
                    994:        int dstPos=0;
                    995:        while(srcPos < len) {
1.126     paf       996:                int ch=cp[srcPos]; 
1.14      paf       997:                switch(escapeState) {
                    998:                        case EscapeRest:
                    999:                        if(ch=='%') {
                   1000:                                escapeState=EscapeFirst;
                   1001:                        } else if(ch=='+') {
1.126     paf      1002:                                s[dstPos++]=' '; 
1.14      paf      1003:                        } else {
                   1004:                                s[dstPos++]=ch; 
                   1005:                        }
                   1006:                        break;
                   1007:                        case EscapeFirst:
                   1008:                        escapedValue=hex_value[ch] << 4;        
                   1009:                        escapeState=EscapeSecond;
                   1010:                        break;
                   1011:                        case EscapeSecond:
1.126     paf      1012:                        escapedValue +=hex_value[ch]; 
1.14      paf      1013:                        s[dstPos++]=escapedValue;
                   1014:                        escapeState=EscapeRest;
                   1015:                        break;
                   1016:                }
1.126     paf      1017:                srcPos++; 
1.14      paf      1018:        }
                   1019:        s[dstPos]=0;
                   1020:        return s;
1.24      paf      1021: }
                   1022: 
                   1023: #ifdef WIN32
1.126     paf      1024: void back_slashes_to_slashes(char* s) {
1.24      paf      1025:        if(s)
                   1026:                for(; *s; s++)
                   1027:                        if(*s=='\\')
1.126     paf      1028:                                *s='/'; 
1.24      paf      1029: }
1.42      paf      1030: /*
1.126     paf      1031: void slashes_to_back_slashes(char* s) {
1.42      paf      1032:        if(s)
                   1033:                for(; *s; s++)
                   1034:                        if(*s=='/')
1.126     paf      1035:                                *s='\\'; 
1.42      paf      1036: }
                   1037: */
1.24      paf      1038: #endif
1.41      paf      1039: 
1.126     paf      1040: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41      paf      1041:        while(true) {
                   1042:                if(!(*s1)) {
                   1043:                        if(!(*s2))
                   1044:                                return true;
                   1045:                        else
                   1046:                                return !strict;
                   1047:                } else if(!(*s2))
                   1048:                        return !strict;
                   1049:                if(isalpha(*s1)) {
                   1050:                        if(tolower(*s1) !=tolower(*s2))
                   1051:                                return false;
                   1052:                } else if((*s1) !=(*s2))
                   1053:                        return false;
1.126     paf      1054:                s1++; 
                   1055:                s2++; 
1.41      paf      1056:        }
1.57      parser   1057: }
                   1058: 
1.84      paf      1059: static bool isLeap(int year) {
1.57      parser   1060:     return !(
                   1061:              (year % 4) || ((year % 400) && !(year % 100))
1.126     paf      1062:             ); 
1.57      parser   1063: }
                   1064: 
                   1065: int getMonthDays(int year, int month) {
                   1066:     int monthDays[]={
1.126     paf      1067:         31, 
                   1068:         isLeap(year) ? 29 : 28, 
                   1069:         31, 
                   1070:         30, 
                   1071:         31, 
                   1072:         30, 
                   1073:         31, 
                   1074:         31, 
                   1075:         30, 
                   1076:         31, 
                   1077:         30, 
1.57      parser   1078:         31
1.126     paf      1079:     }; 
                   1080:     return monthDays[month]; 
1.41      paf      1081: }
1.69      parser   1082: 
1.126     paf      1083: void remove_crlf(char* start, char* end) {
                   1084:        for(char* p=start; p<end; p++)
1.69      parser   1085:                switch(*p) {
1.126     paf      1086:                        case '\n': *p='|';  break;
                   1087:                        case '\r': *p=' ';  break;
1.69      parser   1088:                }
1.91      paf      1089: }
                   1090: 
                   1091: 
                   1092: /// must be last in this file
                   1093: #undef vsnprintf
1.126     paf      1094: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91      paf      1095:        if(!s)
                   1096:                return 0;
                   1097: 
                   1098:        int r;
                   1099:        // note: on win32& maybe somewhere else
                   1100:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                   1101:        --s;
                   1102: #if _MSC_VER
                   1103:        /*
                   1104:        win32: 
                   1105:        mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
                   1106: 
1.154     paf      1107:          if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91      paf      1108:        */
1.126     paf      1109:        r=_vsnprintf(b, s, f, l); 
1.91      paf      1110:        if(r<0) 
                   1111:                r=s;
                   1112: #else
1.126     paf      1113:        r=vsnprintf(b, s, f, l); 
1.91      paf      1114:        /*
                   1115:        solaris: 
                   1116:        man vsnprintf
                   1117: 
                   1118:          The snprintf() function returns  the  number  of  characters
                   1119:        formatted, that is, the number of characters that would have
                   1120:        been written to the buffer if it were large enough.  If  the
                   1121:        value  of  n  is  0  on a call to snprintf(), an unspecified
                   1122:        value less than 1 is returned.
                   1123:        */
                   1124: 
                   1125:        if(r<0)
                   1126:                r=0;
                   1127:        else if(r>s)
                   1128:                r=s;
                   1129: #endif
                   1130:        b[r]=0;
                   1131:        return r;
                   1132: }
                   1133: 
1.126     paf      1134: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91      paf      1135:        va_list l;
1.126     paf      1136:     va_start(l, f); 
                   1137:     int r=__vsnprintf(b, s, f, l); 
                   1138:     va_end(l); 
1.91      paf      1139:        return r;
1.98      paf      1140: }
                   1141: 
                   1142: int pa_sleep(unsigned long secs, unsigned long usecs) {
1.126     paf      1143:        for (;  usecs >= 1000000; ++secs, usecs -= 1000000); 
1.98      paf      1144: 
                   1145: #ifdef WIN32
1.126     paf      1146:        Sleep(secs * 1000 + usecs / 1000); 
1.98      paf      1147:        return 0;
                   1148: #else
                   1149:        struct timeval t;
                   1150:        t.tv_sec = secs;
                   1151:        t.tv_usec = usecs;
1.126     paf      1152:        return (select(0, NULL, NULL, NULL, &t) == -1 ? errno : 0); 
1.98      paf      1153: #endif
1.135     paf      1154: }
                   1155: 
                   1156: 

E-mail: