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

1.15      paf         1: /** @file
1.16      paf         2:        Parser: commonly functions.
                      3: 
1.143     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.143.2.3! paf         8: static const char* IDENT_COMMON_C="$Date: 2003/01/24 08:19:09 $"; 
1.1       paf         9: 
                     10: #include "pa_common.h"
1.4       paf        11: #include "pa_exception.h"
1.14      paf        12: #include "pa_globals.h"
1.126     paf        13: #include "pa_hash.h"
1.143.2.3! paf        14: #include "pa_vstring.h"
1.1       paf        15: 
1.98      paf        16: #ifdef WIN32
                     17: #      include <windows.h>
1.126     paf        18: #else
                     19: #      define closesocket close
1.98      paf        20: #endif
                     21: 
1.93      paf        22: // some maybe-undefined constants
                     23: 
1.82      paf        24: #ifndef _O_TEXT
                     25: #      define _O_TEXT 0
                     26: #endif
                     27: #ifndef _O_BINARY
                     28: #      define _O_BINARY 0
1.47      paf        29: #endif
1.80      paf        30: 
1.138     paf        31: #ifdef HAVE_FTRUNCATE
                     32: #      define PA_O_TRUNC 0
                     33: #else
                     34: #      ifdef _O_TRUNC
                     35: #              define PA_O_TRUNC _O_TRUNC
                     36: #      else
                     37: #              error you must have either ftruncate function or _O_TRUNC bit declared
                     38: #      endif
                     39: #endif
                     40: 
1.93      paf        41: // locking constants
                     42: 
1.99      paf        43: #ifdef HAVE_FLOCK
                     44: 
                     45: static int lock_shared_blocking(int fd) { return flock(fd, LOCK_SH); }
                     46: static int lock_exclusive_blocking(int fd) { return flock(fd, LOCK_EX); }
                     47: static int lock_exclusive_nonblocking(int fd) { return flock(fd, LOCK_EX || LOCK_NB); }
                     48: static int unlock(int fd) { return flock(fd, LOCK_UN); }
                     49: 
1.98      paf        50: #else
1.99      paf        51: #ifdef HAVE__LOCKING
1.98      paf        52: 
1.126     paf        53: #define FLOCK(operation) lseek(fd, 0, SEEK_SET);  return _locking(fd, operation, 1)
1.99      paf        54: static int lock_shared_blocking(int fd) { FLOCK(_LK_LOCK); }
                     55: static int lock_exclusive_blocking(int fd) { FLOCK(_LK_LOCK); }
                     56: static int lock_exclusive_nonblocking(int fd) { FLOCK(_LK_NBLCK); }
                     57: static int unlock(int fd) { FLOCK(_LK_UNLCK); }
1.93      paf        58: 
1.99      paf        59: #else
                     60: #ifdef HAVE_FCNTL
1.93      paf        61: 
1.126     paf        62: #define FLOCK(cmd, arg) struct flock ls={arg, SEEK_SET};  return fcntl(fd, cmd, &ls)
1.99      paf        63: static int lock_shared_blocking(int fd) { FLOCK(F_SETLKW, F_RDLCK); }
                     64: static int lock_exclusive_blocking(int fd) { FLOCK(F_SETLKW, F_WRLCK); }
                     65: static int lock_exclusive_nonblocking(int fd) { FLOCK(F_SETLK, F_RDLCK); }
                     66: static int unlock(int fd) { FLOCK(F_SETLK, F_UNLCK); }
1.93      paf        67: 
                     68: #else
                     69: #ifdef HAVE_LOCKF
1.99      paf        70: 
1.126     paf        71: #define FLOCK(fd, operation) lseek(fd, 0, SEEK_SET);  return lockf(fd, operation, 1)
1.99      paf        72: static int lock_shared_blocking(int fd) { FLOCK(F_LOCK); } // on intel solaris man doesn't have doc on shared blocking
                     73: static int lock_exclusive_blocking(int fd) { FLOCK(F_LOCK); }
                     74: static int lock_exclusive_nonblocking(int fd) { FLOCK(F_TLOCK); }
                     75: static int unlock(int fd) { FLOCK(F_TLOCK); }
                     76: 
1.93      paf        77: #else
1.99      paf        78: 
                     79: #error unable to find file locking func
                     80: 
                     81: #endif
1.93      paf        82: #endif
                     83: #endif
                     84: #endif
                     85: 
1.127     paf        86: #define DEFAULT_USER_AGENT "parser3"
                     87: 
                     88: 
1.126     paf        89: void fix_line_breaks(char* buf, size_t& size) {
1.139     paf        90:        if(size==0)
                     91:                return;
                     92: 
1.87      paf        93:        //_asm int 3;
1.126     paf        94:        const char* const eob=buf+size;
                     95:        char* dest=buf;
1.72      parser     96:        // fix DOS: \r\n -> \n
                     97:        // fix Macintosh: \r -> \n
1.126     paf        98:        char* bol=buf;
1.137     paf        99:        while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72      parser    100:                size_t len=eol-bol;
                    101:                if(dest!=bol)
1.126     paf       102:                        memcpy(dest, bol, len); 
1.72      parser    103:                dest+=len;
1.126     paf       104:                *dest++='\n'; 
1.72      parser    105: 
1.126     paf       106:                if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72      parser    107:                        bol=eol+2;
1.126     paf       108:                        size--; 
                    109:                } else // \r, not \n = Macintosh
1.72      parser    110:                        bol=eol+1;
                    111:        }
                    112:        // last piece without \r, including terminating 0
                    113:        if(dest!=bol)
1.126     paf       114:                memcpy(dest, bol, eob-bol); 
1.72      parser    115: }
1.18      paf       116: 
1.143.2.3! paf       117: char* file_read_text(Pool& pool, Charset& charset, 
1.143.2.1  paf       118:                                         ConstStringPtr file_spec, 
1.126     paf       119:                                         bool fail_on_read_problem,
1.143.2.3! paf       120:                                         HashStringValue *params, HashStringValue** out_fields) {
1.72      parser    121:        void *result;  size_t size;
1.143.2.3! paf       122:        return file_read(pool, charset, file_spec, result, size, true, params, out_fields, fail_on_read_problem)?
1.143.2.1  paf       123:                (char *)result:0;
1.126     paf       124: }
                    125: 
                    126: //http request stuff
                    127: /* ************************ http stuff *********************** */
                    128: 
                    129: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
                    130:     memset(addr, 0, sizeof(*addr)); 
                    131:     addr->sin_family=AF_INET;
                    132:     addr->sin_port=htons(port); 
                    133:     if(host) {
                    134:                if(struct hostent *hostIP=gethostbyname(host)) 
                    135:                        memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length); 
                    136:                else
                    137:                        return false;
                    138:     } else 
                    139:                addr->sin_addr.s_addr=INADDR_ANY;
                    140:     return true;
                    141: }
                    142: 
1.143.2.1  paf       143: static int http_read_response(Pool& pool, String& response, int sock, bool fail_on_status_ne_200){
1.143.2.2  paf       144:        int result=0;
1.130     paf       145:        ssize_t EOLat=0;
1.126     paf       146:        while(true) {
1.143.2.1  paf       147:                char *buf=(char *)pool.malloc(MAX_STRING); 
1.126     paf       148:                ssize_t size=recv(sock, buf, MAX_STRING, 0); 
                    149:                if(size<=0)
                    150:                        break;
1.130     paf       151:                response.APPEND_TAINTED(buf, size, "remote HTTP server response", 0); 
1.143.2.2  paf       152:                if(!result && (EOLat=response.pos("\r\n", 2))>=0) { // checking status in first response
1.143.2.3! paf       153:                        ConstStringPtr status_line=response.mid(0, (size_t)EOLat);
        !           154:                        Array<ConstStringPtr> astatus; 
        !           155:                        status_line->split(astatus, 0, " ", 1); 
        !           156:                        ConstStringPtr status_code=astatus.get(1);
        !           157:                        result=status_code->as_int(); 
1.142     paf       158: 
1.143.2.3! paf       159:                        if(fail_on_status_ne_200 && result!=200)
1.142     paf       160:                                throw Exception("http.status",
                    161:                                        status_code,
                    162:                                        "invalid HTTP response status");
                    163:                }
                    164:        }
1.143.2.2  paf       165:        if(result)
                    166:                return result;
1.142     paf       167:        else
                    168:                throw Exception("http.response",
1.143.2.3! paf       169:                        Exception::undefined_source,
1.142     paf       170:                        "bad response from host - no status found (size=%lu)", response.size()); 
1.126     paf       171: }
                    172: 
                    173: /* ********************** request *************************** */
                    174: 
                    175: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
                    176: #      define WE_CAN_USE_ALARM
                    177: #endif
                    178: 
                    179: #ifdef WE_CAN_USE_ALARM
                    180: static sigjmp_buf timeout_env;
                    181: static void timeout_handler(int sig){
                    182:     siglongjmp(timeout_env, 1); 
                    183: }
                    184: #endif
                    185: 
1.143.2.3! paf       186: static int http_request(Pool& pool,
        !           187:                                                String& response,
        !           188:                                                ConstStringPtr origin_string, 
        !           189:                                                const char* host, int port, 
        !           190:                                                const char* request, 
        !           191:                                                int timeout,
        !           192:                                                bool fail_on_status_ne_200) {
1.126     paf       193:        if(!host)
                    194:                throw Exception("http.host", 
                    195:                        origin_string, 
                    196:                        "zero hostname");  //never
                    197: 
                    198: #ifdef WE_CAN_USE_ALARM
                    199:     signal(SIGALRM, timeout_handler); 
                    200: #endif
                    201:        int sock=-1;
                    202:        try {
1.142     paf       203:                int result;
1.126     paf       204: #ifdef WE_CAN_USE_ALARM
                    205:                if(sigsetjmp(timeout_env, 1))
                    206:                        throw Exception("http.timeout", 
                    207:                                origin_string, 
                    208:                                "timeout occured while retrieving document"); 
                    209:                else {
                    210:                        alarm(timeout); 
                    211: #endif
                    212:                        struct sockaddr_in dest;
                    213:                
                    214:                if(!set_addr(&dest, host, port))
                    215:                                throw Exception("http.host", 
                    216:                                        origin_string, 
1.127     paf       217:                                        "can not resolve hostname \"%s\"", host); 
1.126     paf       218:                        
                    219:                        if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0)
                    220:                                throw Exception("http.connect", 
                    221:                                        origin_string, 
1.127     paf       222:                                        "can not make socket: %s (%d)", strerror(errno), errno); 
1.126     paf       223:                        if(connect(sock, (struct sockaddr *)&dest, sizeof(dest)))
                    224:                                throw Exception("http.connect", 
                    225:                                        origin_string, 
1.127     paf       226:                                        "can not connect to host \"%s\": %s (%d)", host, strerror(errno), errno); 
1.126     paf       227:                        size_t request_size=strlen(request);
                    228:                        if(send(sock, request, request_size, 0)!=(ssize_t)request_size)
                    229:                                throw Exception("http.connect", 
                    230:                                        origin_string, 
1.127     paf       231:                                        "error sending request: %s (%d)", strerror(errno), errno); 
1.126     paf       232: 
1.143.2.3! paf       233:                        result=http_read_response(pool, response, sock, fail_on_status_ne_200); 
1.142     paf       234:                        closesocket(sock); 
1.126     paf       235: #ifdef WE_CAN_USE_ALARM
1.142     paf       236:                        alarm(0)1.126     paf       237:                }
                    238: #endif
1.142     paf       239:                return result;
1.126     paf       240:        } catch(...) {
                    241:                if(sock>=0) 
                    242:                        closesocket(sock); 
                    243: #ifdef WE_CAN_USE_ALARM
                    244:                alarm(0); 
                    245: #endif
                    246:                /*re*/throw;
                    247:        }
                    248: }
                    249: 
1.127     paf       250: #ifndef DOXYGEN
                    251: struct Http_pass_header_info {
1.143.2.3! paf       252:        Pool* pool;
        !           253:        Charset* charset;
1.127     paf       254:        String* request;
                    255:        bool user_agent_specified;
                    256: };
                    257: #endif
1.143.2.3! paf       258: static void http_pass_header(HashStringValue::key_type key, HashStringValue::value_type value, 
        !           259:                                                         Http_pass_header_info *info) {
        !           260:     *(info->request)<<*key<<": "
        !           261:                << *attributed_meaning_to_string(value, String::UL_HTTP_HEADER, false)
1.135     paf       262:                <<"\n"; 
                    263:        
1.143.2.3! paf       264:        if(*key->change_case(*info->pool, *info->charset, String::CC_UPPER)=="USER-AGENT")
        !           265:                info->user_agent_specified=true;
1.126     paf       266: }
1.143.2.3! paf       267: static HashStringValuePtr file_read_http(Pool& pool, Charset& charset, const String& file_spec, 
        !           268:                                        char*& data, size_t& data_size, 
        !           269:                                        HashStringValue *options=0, bool return_outfields=false) {
        !           270:        HashStringValuePtr result(0);
1.126     paf       271:        char host[MAX_STRING]; 
1.129     paf       272:        const char* uri; 
1.126     paf       273:        int port;
1.143.2.3! paf       274:        ConstCharPtr method(0);
1.126     paf       275:        int timeout=2;
1.142     paf       276:        bool fail_on_status_ne_200=true;
1.143.2.3! paf       277:        ValuePtr vheaders(0);
1.126     paf       278: 
1.143.2.3! paf       279:        StringPtr connect_string(new String());
1.133     paf       280:        // not in ^sql{... UL_SQL ...} spirit, but closer to ^file::load one
1.143.2.3! paf       281:        connect_string->append(file_spec, String::UL_URI); // tainted pieces -> URI pieces
1.133     paf       282: 
1.143.2.3! paf       283:        CharPtr connect_string_cstr=connect_string->cstr(String::UL_UNSPECIFIED); 
        !           284:        const char *current=connect_string_cstr.get();
        !           285:        if(strncmp(current, "http://", 7)!=0)
1.126     paf       286:                throw Exception(0, 
1.143.2.3! paf       287:                        connect_string, 
1.126     paf       288:                        "does not start with http://"); //never
1.143.2.3! paf       289:        current+=7;
1.126     paf       290: 
1.143.2.3! paf       291:        strncpy(host, current, sizeof(host)-1);  host[sizeof(host)-1]=0;
1.126     paf       292:        char* host_uri=lsplit(host, '/'); 
1.143.2.3! paf       293:        uri=host_uri?current+(host_uri-1-host):"/"; 
1.126     paf       294:        char* port_cstr=lsplit(host, ':'); 
                    295:        char* error_pos=0;
                    296:        port=port_cstr?strtol(port_cstr, &error_pos, 0):80;
                    297: 
1.127     paf       298:        if(options) {
                    299:                int valid_options=0;
1.143.2.3! paf       300:                if(ValuePtr vmethod=options->get(http_method_name)) {
1.127     paf       301:                        valid_options++;
1.143.2.3! paf       302:                        method=vmethod->as_string(pool)->cstr();
1.127     paf       303:                }
1.143.2.3! paf       304:                if(ValuePtr vtimeout=options->get(http_timeout_name)) {
1.127     paf       305:                        valid_options++;
                    306:                        timeout=vtimeout->as_int(); 
                    307:                }
1.143.2.3! paf       308:                if(vheaders=options->get(http_headers_name)) {
1.127     paf       309:                        valid_options++;
                    310:                }
1.143.2.3! paf       311:                if(ValuePtr vany_status=options->get(http_any_status_name)) {
1.142     paf       312:                        valid_options++;
                    313:                        fail_on_status_ne_200=!vany_status->as_bool(); 
                    314:                }
                    315: 
1.143.2.3! paf       316:                if(valid_options!=options->count())
1.127     paf       317:                        throw Exception("parser.runtime",
1.143.2.3! paf       318:                                Exception::undefined_source,
1.127     paf       319:                                "invalid option passed");
1.133     paf       320:        } 
1.126     paf       321: 
                    322:        //making request
1.143.2.3! paf       323:        String request;
        !           324:        if(method)
        !           325:                request<<method.get();
        !           326:        else
        !           327:                request<<"GET";
        !           328:        request<< " "<< uri <<" HTTP/1.0\nHost: "<< host<<"\n"; 
1.127     paf       329:        bool user_agent_specified=false;
                    330:        if(vheaders && !vheaders->is_string()) { // allow empty
1.143.2.3! paf       331:                if(HashStringValuePtr headers=vheaders->get_hash(connect_string)) {
        !           332:                        Http_pass_header_info info={&pool, &charset, &request};
1.127     paf       333:                        headers->for_each(http_pass_header, &info); 
                    334:                        user_agent_specified=info.user_agent_specified;
                    335:                } else
                    336:                        throw Exception("parser.runtime", 
1.143.2.3! paf       337:                                connect_string,
1.127     paf       338:                                "headers param must be hash"); 
                    339:        };
                    340:        if(!user_agent_specified) // defaulting
                    341:                request << "user-agent: " DEFAULT_USER_AGENT "\n";
1.126     paf       342:        request<<"\n"; 
                    343:        
                    344:        //sending request
1.143.2.3! paf       345:        String response;
        !           346:        ConstCharPtr request_cstr=request.cstr(String::UL_UNSPECIFIED);
        !           347:        int status_code=http_request(pool, response,
        !           348:                connect_string, host, port, request_cstr.get(), 
1.142     paf       349:                timeout, fail_on_status_ne_200); 
1.126     paf       350:        
                    351:        //processing results    
                    352:        int pos=response.pos("\r\n\r\n", 4); 
                    353:        if(pos<1){
                    354:                throw Exception("http.response", 
1.143.2.3! paf       355:                        connect_string,
1.126     paf       356:                        "bad response from host - no headers found"); 
                    357:        }
1.143.2.3! paf       358:        StringPtr header_block=response.mid(0, pos); 
        !           359:        StringPtr body=response.mid(pos+4, response.size()); 
1.126     paf       360:        
1.143.2.3! paf       361:        Array<ConstStringPtr> aheaders;
        !           362:        HashStringValuePtr headers(new HashStringValue); 
        !           363:        header_block->split(aheaders, 0, "\r\n", 2); 
1.126     paf       364:        
                    365:        //processing headers
1.143.2.3! paf       366:        for(int i=1; i<aheaders.count(); i++) {
        !           367:                ConstStringPtr line=aheaders.get(i);
        !           368:                pos=line->pos(": ", 2); 
        !           369:                if(pos<1)
1.126     paf       370:                        throw Exception("http.response", 
1.143.2.3! paf       371:                                connect_string,
        !           372:                                "bad response from host - bad header \"%s\"", line->cstr()); 
        !           373:                        
        !           374:                headers->put(
        !           375:                        line->mid(0, pos)->change_case(pool, charset, String::CC_UPPER), 
        !           376:                        ValuePtr(new VString(line->mid(pos+2, line->size())))); 
1.126     paf       377:        }
                    378: 
                    379:        // output response
1.143.2.3! paf       380:        data=new(pool) char[data_size=body->size()];
        !           381:        body->store_to(data, String::UL_AS_IS);
        !           382:        if(return_outfields) {
        !           383:                headers.put(file_status_name, VIntPtr<new VInt(pool, status_code)>); 
1.126     paf       384:                *out_fields=&headers;
1.141     paf       385:        }
1.143.2.3! paf       386: 
        !           387:        return result;
1.34      paf       388: }
1.123     paf       389: 
                    390: #ifndef DOXYGEN
                    391: struct File_read_action_info {
                    392:        void **data; size_t *data_size;
1.126     paf       393: }; 
1.123     paf       394: #endif
1.143.2.1  paf       395: static void file_read_action(
1.126     paf       396:                                                         struct stat& finfo, 
1.123     paf       397:                                                         int f, 
1.126     paf       398:                                                         const String& file_spec, const char* fname, bool as_text, 
1.123     paf       399:                                                         void *context) {
1.126     paf       400:        File_read_action_info& info=*static_cast<File_read_action_info *>(context); 
1.123     paf       401:        if(size_t to_read_size=(size_t)finfo.st_size) { 
1.126     paf       402:                *info.data=pool.malloc(to_read_size+(as_text?1:0), 3); 
                    403:                *info.data_size=(size_t)read(f, *info.data, to_read_size); 
1.123     paf       404: 
                    405:                if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126     paf       406:                        throw Exception(0, 
1.123     paf       407:                                &file_spec, 
                    408:                                "read failed: actually read %lu bytes count not in [0..%lu] valid range", 
1.126     paf       409:                                        *info.data_size, to_read_size); 
1.123     paf       410:        } else { // empty file
                    411:                if(as_text) {
1.126     paf       412:                        *info.data=pool.malloc(1)1.123     paf       413:                        *(char*)(*info.data)=0;
                    414:                } else 
                    415:                        *info.data=0;
                    416:                *info.data_size=0;
                    417:                return;
                    418:        }
1.126     paf       419: }
1.143.2.1  paf       420: bool file_read(ConstStringPtr file_spec, 
1.126     paf       421:                           void*& data, size_t& data_size, 
1.143.2.3! paf       422:                           bool as_text, HashStringValue *params, HashStringValue** out_fields, 
1.126     paf       423:                           bool fail_on_read_problem) {
                    424:        bool result;
                    425:        if(file_spec.starts_with("http://", 7)) {
                    426:                // fail on read problem
                    427:                file_read_http(pool, file_spec, data, data_size, params, out_fields); 
                    428:                result=true;
                    429:        } else {
                    430:                File_read_action_info info={&data, &data_size}; 
                    431:                result=file_read_action_under_lock(pool, file_spec, 
                    432:                        "read", file_read_action, &info, 
                    433:                        as_text, fail_on_read_problem); 
                    434:        }
1.123     paf       435: 
1.126     paf       436:        if(result && as_text) {
1.131     paf       437:                // UTF-8 signature: EF BB BF
                    438:                if(data_size>=3) {
                    439:                        char *in=(char *)data;
                    440:                        if((in[0] == '\xEF') && (in[1] == '\xBB') &&
                    441:                                (in[2] == '\xBF')) {
                    442:                                data=in+3; data_size-=3;// skip prefix
                    443:                        }
                    444:                }
                    445: 
1.126     paf       446:                fix_line_breaks((char *)(data), data_size); 
1.123     paf       447:                // note: after fixing
1.126     paf       448:                ((char*&)(data))[data_size]=0;
1.123     paf       449:        }
1.126     paf       450: 
                    451:        return result;
1.123     paf       452: }
                    453: 
1.143.2.1  paf       454: bool file_read_action_under_lock(const String& file_spec, 
1.126     paf       455:                                const char* action_name, File_read_action action, void *context, 
                    456:                                bool as_text, 
1.123     paf       457:                                bool fail_on_read_problem) {
1.126     paf       458:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.33      paf       459:        int f;
                    460: 
                    461:        // first open, next stat:
1.45      paf       462:        // directory update of NTFS hard links performed on open.
1.33      paf       463:        // ex: 
                    464:        //   a.html:^test[] and b.html hardlink to a.html
                    465:        //   user inserts ! before ^test in a.html
1.126     paf       466:        //   directory entry of b.html in NTFS not updated at once, 
1.35      paf       467:        //   they delay update till open, so we would receive "!^test[" string
                    468:        //   if would do stat, next open.
1.123     paf       469:        // later: it seems, even this does not help sometimes
1.98      paf       470:     if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123     paf       471:                try {
                    472:                        if(lock_shared_blocking(f)!=0)
1.126     paf       473:                                throw Exception("file.lock", 
1.123     paf       474:                                                &file_spec, 
                    475:                                                "shared lock failed: %s (%d), actual filename '%s'", 
1.126     paf       476:                                                        strerror(errno), errno, fname); 
1.123     paf       477: 
1.124     paf       478:                        struct stat finfo;
                    479:                        if(stat(fname, &finfo)!=0)
                    480:                                throw Exception("file.missing", // hardly possible: we just opened it OK
                    481:                                        &file_spec, 
                    482:                                        "stat failed: %s (%d), actual filename '%s'", 
1.126     paf       483:                                                strerror(errno), errno, fname); 
1.124     paf       484: 
1.140     paf       485: #ifdef PA_SAFE_MODE
                    486:                        if(finfo.st_uid/*foreign?*/!=geteuid()
                    487:                                && finfo.st_gid/*foreign?*/!=getegid())
1.126     paf       488:                                throw Exception("parser.runtime", 
                    489:                                        &file_spec, 
1.140     paf       490:                                        "parser is in safe mode: reading files of foreign group and user disabled [recompile parser with --disable-safe-mode configure option], actual filename '%s'", 
1.126     paf       491:                                                fname); 
1.105     paf       492: #endif
1.32      paf       493: 
1.126     paf       494:                        action(pool, finfo, f, file_spec, fname, as_text, context); 
1.123     paf       495:                } catch(...) {
1.126     paf       496:                        unlock(f);close(f); 
1.123     paf       497:                        if(fail_on_read_problem)
                    498:                                /*re*/throw;
                    499:                        return false;                   
                    500:                } 
1.87      paf       501: 
1.126     paf       502:                unlock(f);close(f); 
1.72      parser    503:                return true;
1.118     paf       504:     } else {
                    505:                if(fail_on_read_problem)
1.126     paf       506:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.118     paf       507:                                &file_spec, 
1.123     paf       508:                                "%s failed: %s (%d), actual filename '%s'", 
1.126     paf       509:                                        action_name, strerror(errno), errno, fname); 
1.118     paf       510:                return false;
                    511:        }
1.8       paf       512: }
                    513: 
1.63      parser    514: static void create_dir_for_file(const String& file_spec) {
                    515:        size_t pos_after=1;
                    516:        int pos_before;
                    517:        while((pos_before=file_spec.pos("/", 1, pos_after))>=0) {
1.126     paf       518:                mkdir(file_spec.mid(0, pos_before).cstr(String::UL_FILE_SPEC), 0775); 
1.63      parser    519:                pos_after=pos_before+1;
                    520:        }
                    521: }
                    522: 
1.98      paf       523: bool file_write_action_under_lock(
1.28      paf       524:                                const String& file_spec, 
1.126     paf       525:                                const char* action_name, File_write_action action, void *context, 
                    526:                                bool as_text, 
                    527:                                bool do_append, 
                    528:                                bool do_block, 
1.110     paf       529:                                bool fail_on_lock_problem) {
1.126     paf       530:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.28      paf       531:        int f;
1.80      paf       532:        if(access(fname, W_OK)!=0) // no
1.126     paf       533:                create_dir_for_file(file_spec); 
1.50      paf       534: 
1.80      paf       535:        if((f=open(fname, 
                    536:                O_CREAT|O_RDWR
                    537:                |(as_text?_O_TEXT:_O_BINARY)
1.138     paf       538:                |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.99      paf       539:                if((do_block?lock_exclusive_blocking(f):lock_exclusive_nonblocking(f))!=0) {
1.126     paf       540:                        Exception e("file.lock", 
1.110     paf       541:                                &file_spec, 
                    542:                                "shared lock failed: %s (%d), actual filename '%s'", 
1.126     paf       543:                                strerror(errno), errno, fname); 
                    544:                        close(f); 
1.110     paf       545:                        if(fail_on_lock_problem)
                    546:                                throw e;
1.98      paf       547:                        return false;
                    548:                }
1.96      paf       549: 
                    550:                try {
1.126     paf       551:                        action(f, context); 
1.96      paf       552:                } catch(...) {
1.138     paf       553: #ifdef HAVE_FTRUNCATE
1.104     paf       554:                        if(!do_append)
1.125     paf       555:                                ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138     paf       556: #endif
1.126     paf       557:                        unlock(f);close(f); 
1.96      paf       558:                        /*re*/throw;
                    559:                }
1.80      paf       560:                
1.138     paf       561: #ifdef HAVE_FTRUNCATE
1.104     paf       562:                if(!do_append)
1.125     paf       563:                        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       564: #endif
1.126     paf       565:                unlock(f);close(f); 
1.98      paf       566:                return true;
1.80      paf       567:        } else
1.126     paf       568:                throw Exception(errno==EACCES?"file.access":0, 
1.80      paf       569:                        &file_spec, 
1.96      paf       570:                        "%s failed: %s (%d), actual filename '%s'", 
1.126     paf       571:                                action_name, strerror(errno), errno, fname); 
1.96      paf       572:        // here should be nothing, see rethrow above
                    573: }
                    574: 
                    575: #ifndef DOXYGEN
                    576: struct File_write_action_info {
                    577:        const void *data; size_t size;
1.126     paf       578: }; 
1.96      paf       579: #endif
                    580: static void file_write_action(int f, void *context) {
1.126     paf       581:        File_write_action_info& info=*static_cast<File_write_action_info *>(context); 
1.113     paf       582:        if(info.size) {
1.126     paf       583:                int written=write(f, info.data, info.size); 
1.116     paf       584:                if(written<0)
1.126     paf       585:                        throw Exception(0, 
                    586:                                0, 
                    587:                                "write failed: %s (%d)",  strerror(errno), errno); 
1.113     paf       588:        }
1.96      paf       589: }
                    590: void file_write(
                    591:                                const String& file_spec, 
                    592:                                const void *data, size_t size, 
1.126     paf       593:                                bool as_text, 
1.96      paf       594:                                bool do_append) {
1.126     paf       595:        File_write_action_info info={data, size}; 
1.98      paf       596:        file_write_action_under_lock(
1.96      paf       597:                                file_spec, 
1.126     paf       598:                                "write", file_write_action, &info, 
                    599:                                as_text, 
                    600:                                do_append); 
1.30      paf       601: }
                    602: 
1.63      parser    603: // throws nothing! [this is required in file_move & file_delete]
1.50      paf       604: static void rmdir(const String& file_spec, size_t pos_after) {
                    605:        int pos_before;
                    606:        if((pos_before=file_spec.pos("/", 1, pos_after))>=0)
1.126     paf       607:                rmdir(file_spec, pos_before+1); 
1.50      paf       608:        
1.126     paf       609:        rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::UL_FILE_SPEC)); 
1.50      paf       610: }
1.95      paf       611: bool file_delete(const String& file_spec, bool fail_on_read_problem) {
1.126     paf       612:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.54      parser    613:        if(unlink(fname)!=0)
1.93      paf       614:                if(fail_on_read_problem)
1.126     paf       615:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.93      paf       616:                                &file_spec, 
                    617:                                "unlink failed: %s (%d), actual filename '%s'", 
1.126     paf       618:                                        strerror(errno), errno, fname); 
1.93      paf       619:                else
                    620:                        return false;
1.50      paf       621: 
1.126     paf       622:        rmdir(file_spec, 1); 
1.93      paf       623:        return true;
1.60      parser    624: }
1.95      paf       625: void file_move(const String& old_spec, const String& new_spec) {
1.126     paf       626:        const char* old_spec_cstr=old_spec.cstr(String::UL_FILE_SPEC); 
                    627:        const char* new_spec_cstr=new_spec.cstr(String::UL_FILE_SPEC); 
1.63      parser    628:        
1.126     paf       629:        create_dir_for_file(new_spec); 
1.63      parser    630: 
1.60      parser    631:        if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126     paf       632:                throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.60      parser    633:                        &old_spec, 
                    634:                        "rename failed: %s (%d), actual filename '%s' to '%s'", 
1.126     paf       635:                                strerror(errno), errno, old_spec_cstr, new_spec_cstr); 
1.63      parser    636: 
1.126     paf       637:        rmdir(old_spec, 1); 
1.31      paf       638: }
                    639: 
1.51      paf       640: 
1.126     paf       641: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118     paf       642:        struct stat lfinfo;
                    643:        bool result=stat(fname, &lfinfo)==0;
                    644:        if(afinfo)
                    645:                *afinfo=lfinfo;
                    646:        return result;
1.119     paf       647: }
                    648: 
                    649: bool entry_exists(const String& file_spec) {
1.126     paf       650:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
                    651:        return entry_exists(fname, 0); 
1.118     paf       652: }
                    653: 
1.51      paf       654: static bool entry_readable(const String& file_spec, bool need_dir) {
1.126     paf       655:     char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.120     paf       656:        if(need_dir) {
1.126     paf       657:                size_t size=strlen(fname); 
1.120     paf       658:                while(size) {
1.126     paf       659:                        char c=fname[size-1]; 
1.120     paf       660:                        if(c=='/' || c=='\\')
                    661:                                fname[--size]=0;
                    662:                        else
                    663:                                break;
                    664:                }
                    665:        }
1.51      paf       666:        struct stat finfo;
1.118     paf       667:        if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109     paf       668:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51      paf       669:                return is_dir==need_dir;
                    670:        }
                    671:        return false;
                    672: }
1.31      paf       673: bool file_readable(const String& file_spec) {
1.126     paf       674:        return entry_readable(file_spec, false); 
1.51      paf       675: }
                    676: bool dir_readable(const String& file_spec) {
1.126     paf       677:        return entry_readable(file_spec, true); 
1.65      parser    678: }
                    679: String *file_readable(const String& path, const String& name) {
1.126     paf       680:        String *result=new(path.pool()) String(path); 
                    681:        *result << "/"; 
1.65      parser    682:        *result << name;
                    683:        return file_readable(*result)?result:0;
1.43      paf       684: }
                    685: bool file_executable(const String& file_spec) {
1.64      parser    686:     return access(file_spec.cstr(String::UL_FILE_SPEC), X_OK)==0;
1.44      paf       687: }
                    688: 
1.64      parser    689: bool file_stat(const String& file_spec, 
1.58      parser    690:                           size_t& rsize, 
1.126     paf       691:                           time_t& ratime, 
                    692:                           time_t& rmtime, 
                    693:                           time_t& rctime, 
1.64      parser    694:                           bool fail_on_read_problem) {
1.126     paf       695:        Pool& pool=file_spec.pool(); 
                    696:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.44      paf       697:     struct stat finfo;
                    698:        if(stat(fname, &finfo)!=0)
1.64      parser    699:                if(fail_on_read_problem)
1.126     paf       700:                        throw Exception("file.missing", 
1.67      parser    701:                                &file_spec, 
                    702:                                "getting file size failed: %s (%d), real filename '%s'", 
1.126     paf       703:                                        strerror(errno), errno, fname); 
1.64      parser    704:                else
                    705:                        return false;
1.58      parser    706:        rsize=finfo.st_size;
                    707:        ratime=finfo.st_atime;
                    708:        rmtime=finfo.st_mtime;
                    709:        rctime=finfo.st_ctime;
1.64      parser    710:        return true;
1.18      paf       711: }
                    712: 
1.126     paf       713: char* getrow(char* *row_ref, char delim) {
                    714:     char* result=*row_ref;
1.8       paf       715:     if(result) {
1.126     paf       716:                *row_ref=strchr(result, delim); 
1.8       paf       717:                if(*row_ref) 
                    718:                        *((*row_ref)++)=0; 
                    719:                else if(!*result) 
                    720:                        return 0;
                    721:     }
                    722:     return result;
                    723: }
                    724: 
1.126     paf       725: char* lsplit(char* string, char delim) {
1.23      paf       726:     if(string) {
1.126     paf       727:                char* v=strchr(string, delim); 
1.8       paf       728:                if(v) {
                    729:                        *v=0;
                    730:                        return v+1;
                    731:                }
                    732:     }
                    733:     return 0;
                    734: }
                    735: 
1.126     paf       736: char* lsplit(char* *string_ref, char delim) {
                    737:     char* result=*string_ref;
                    738:        char* next=lsplit(*string_ref, delim); 
1.8       paf       739:     *string_ref=next;
                    740:     return result;
1.9       paf       741: }
                    742: 
1.126     paf       743: char* rsplit(char* string, char delim) {
1.18      paf       744:     if(string) {
1.126     paf       745:                char* v=strrchr(string, delim); 
1.18      paf       746:                if(v) {
1.9       paf       747:                        *v=0;
                    748:                        return v+1;
                    749:                }
                    750:     }
                    751:     return NULL;       
1.10      paf       752: }
                    753: 
1.37      paf       754: /// @todo less stupid type detection
1.143.2.1  paf       755: char* format(double value, char* fmt) {
1.126     paf       756:        char local_buf[MAX_NUMBER]; 
1.108     paf       757:        size_t size;
                    758:        
1.10      paf       759:        if(fmt)
                    760:                if(strpbrk(fmt, "diouxX"))
                    761:                        if(strpbrk(fmt, "ouxX"))
1.126     paf       762:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.10      paf       763:                        else
1.126     paf       764:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
1.10      paf       765:                else
1.126     paf       766:                        size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
1.10      paf       767:        else
1.126     paf       768:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value); 
1.10      paf       769:        
1.126     paf       770:        char* pool_buf=(char *)pool.malloc(size+1, 4); 
                    771:        memcpy(pool_buf, local_buf, size+1); 
1.108     paf       772:        return pool_buf;
1.12      paf       773: }
                    774: 
1.36      paf       775: size_t stdout_write(const void *buf, size_t size) {
1.12      paf       776: #ifdef WIN32
                    777:        do{
1.126     paf       778:                int chunk_written=fwrite(buf, 1, min(8*0x400, size), stdout); 
1.12      paf       779:                if(chunk_written<=0)
                    780:                        break;
                    781:                size-=chunk_written;
1.36      paf       782:                buf=((const char*)buf)+chunk_written;
1.126     paf       783:        } while(size>0); 
1.12      paf       784: 
                    785:        return size;
                    786: #else
1.126     paf       787:        return fwrite(buf, 1, size, stdout); 
1.12      paf       788: #endif
1.2       paf       789: }
1.14      paf       790: 
1.143.2.1  paf       791: char* unescape_chars(const char* cp, int len) {
1.126     paf       792:        char* s=(char *)pool.malloc(len + 1, 5); 
1.14      paf       793:        enum EscapeState {
1.33      paf       794:                EscapeRest, 
                    795:                EscapeFirst, 
1.14      paf       796:                EscapeSecond
                    797:        } escapeState=EscapeRest;
                    798:        int escapedValue=0;
                    799:        int srcPos=0;
                    800:        int dstPos=0;
                    801:        while(srcPos < len) {
1.126     paf       802:                int ch=cp[srcPos]; 
1.14      paf       803:                switch(escapeState) {
                    804:                        case EscapeRest:
                    805:                        if(ch=='%') {
                    806:                                escapeState=EscapeFirst;
                    807:                        } else if(ch=='+') {
1.126     paf       808:                                s[dstPos++]=' '; 
1.14      paf       809:                        } else {
                    810:                                s[dstPos++]=ch; 
                    811:                        }
                    812:                        break;
                    813:                        case EscapeFirst:
                    814:                        escapedValue=hex_value[ch] << 4;        
                    815:                        escapeState=EscapeSecond;
                    816:                        break;
                    817:                        case EscapeSecond:
1.126     paf       818:                        escapedValue +=hex_value[ch]; 
1.14      paf       819:                        s[dstPos++]=escapedValue;
                    820:                        escapeState=EscapeRest;
                    821:                        break;
                    822:                }
1.126     paf       823:                srcPos++; 
1.14      paf       824:        }
                    825:        s[dstPos]=0;
                    826:        return s;
1.24      paf       827: }
                    828: 
                    829: #ifdef WIN32
1.126     paf       830: void back_slashes_to_slashes(char* s) {
1.24      paf       831:        if(s)
                    832:                for(; *s; s++)
                    833:                        if(*s=='\\')
1.126     paf       834:                                *s='/'; 
1.24      paf       835: }
1.42      paf       836: /*
1.126     paf       837: void slashes_to_back_slashes(char* s) {
1.42      paf       838:        if(s)
                    839:                for(; *s; s++)
                    840:                        if(*s=='/')
1.126     paf       841:                                *s='\\'; 
1.42      paf       842: }
                    843: */
1.24      paf       844: #endif
1.41      paf       845: 
1.126     paf       846: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41      paf       847:        while(true) {
                    848:                if(!(*s1)) {
                    849:                        if(!(*s2))
                    850:                                return true;
                    851:                        else
                    852:                                return !strict;
                    853:                } else if(!(*s2))
                    854:                        return !strict;
                    855:                if(isalpha(*s1)) {
                    856:                        if(tolower(*s1) !=tolower(*s2))
                    857:                                return false;
                    858:                } else if((*s1) !=(*s2))
                    859:                        return false;
1.126     paf       860:                s1++; 
                    861:                s2++; 
1.41      paf       862:        }
1.57      parser    863: }
                    864: 
1.84      paf       865: static bool isLeap(int year) {
1.57      parser    866:     return !(
                    867:              (year % 4) || ((year % 400) && !(year % 100))
1.126     paf       868:             ); 
1.57      parser    869: }
                    870: 
                    871: int getMonthDays(int year, int month) {
                    872:     int monthDays[]={
1.126     paf       873:         31, 
                    874:         isLeap(year) ? 29 : 28, 
                    875:         31, 
                    876:         30, 
                    877:         31, 
                    878:         30, 
                    879:         31, 
                    880:         31, 
                    881:         30, 
                    882:         31, 
                    883:         30, 
1.57      parser    884:         31
1.126     paf       885:     }; 
                    886:     return monthDays[month]; 
1.41      paf       887: }
1.69      parser    888: 
1.126     paf       889: void remove_crlf(char* start, char* end) {
                    890:        for(char* p=start; p<end; p++)
1.69      parser    891:                switch(*p) {
1.126     paf       892:                        case '\n': *p='|';  break;
                    893:                        case '\r': *p=' ';  break;
1.69      parser    894:                }
1.91      paf       895: }
                    896: 
                    897: 
                    898: /// must be last in this file
                    899: #undef vsnprintf
1.126     paf       900: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91      paf       901:        if(!s)
                    902:                return 0;
                    903: 
                    904:        int r;
                    905:        // note: on win32& maybe somewhere else
                    906:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                    907:        --s;
                    908: #if _MSC_VER
                    909:        /*
                    910:        win32: 
                    911:        mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
                    912: 
                    913:          if the number of bytes to write exceeds buffer, then count bytes are written and –1 is returned
                    914:        */
1.126     paf       915:        r=_vsnprintf(b, s, f, l); 
1.91      paf       916:        if(r<0) 
                    917:                r=s;
                    918: #else
1.126     paf       919:        r=vsnprintf(b, s, f, l); 
1.91      paf       920:        /*
                    921:        solaris: 
                    922:        man vsnprintf
                    923: 
                    924:          The snprintf() function returns  the  number  of  characters
                    925:        formatted, that is, the number of characters that would have
                    926:        been written to the buffer if it were large enough.  If  the
                    927:        value  of  n  is  0  on a call to snprintf(), an unspecified
                    928:        value less than 1 is returned.
                    929:        */
                    930: 
                    931:        if(r<0)
                    932:                r=0;
                    933:        else if(r>s)
                    934:                r=s;
                    935: #endif
                    936:        b[r]=0;
                    937:        return r;
                    938: }
                    939: 
1.126     paf       940: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91      paf       941:        va_list l;
1.126     paf       942:     va_start(l, f); 
                    943:     int r=__vsnprintf(b, s, f, l); 
                    944:     va_end(l); 
1.91      paf       945:        return r;
1.98      paf       946: }
                    947: 
                    948: int pa_sleep(unsigned long secs, unsigned long usecs) {
1.126     paf       949:        for (;  usecs >= 1000000; ++secs, usecs -= 1000000); 
1.98      paf       950: 
                    951: #ifdef WIN32
1.126     paf       952:        Sleep(secs * 1000 + usecs / 1000); 
1.98      paf       953:        return 0;
                    954: #else
                    955:        struct timeval t;
                    956:        t.tv_sec = secs;
                    957:        t.tv_usec = usecs;
1.126     paf       958:        return (select(0, NULL, NULL, NULL, &t) == -1 ? errno : 0); 
1.98      paf       959: #endif
1.135     paf       960: }
                    961: 
                    962: 

E-mail: