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

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

E-mail: