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

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.131   ! paf         8: static const char* IDENT_COMMON_C="$Date: 2002/11/26 09:02:14 $"; 
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) {
1.131   ! paf       419:                // UTF-8 signature: EF BB BF
        !           420:                if(data_size>=3) {
        !           421:                        char *in=(char *)data;
        !           422:                        if((in[0] == '\xEF') && (in[1] == '\xBB') &&
        !           423:                                (in[2] == '\xBF')) {
        !           424:                                data=in+3; data_size-=3;// skip prefix
        !           425:                        }
        !           426:                }
        !           427: 
1.126     paf       428:                fix_line_breaks((char *)(data), data_size); 
1.123     paf       429:                // note: after fixing
1.126     paf       430:                ((char*&)(data))[data_size]=0;
1.123     paf       431:        }
1.126     paf       432: 
                    433:        return result;
1.123     paf       434: }
                    435: 
                    436: bool file_read_action_under_lock(Pool& pool, const String& file_spec, 
1.126     paf       437:                                const char* action_name, File_read_action action, void *context, 
                    438:                                bool as_text, 
1.123     paf       439:                                bool fail_on_read_problem) {
1.126     paf       440:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.33      paf       441:        int f;
                    442: 
                    443:        // first open, next stat:
1.45      paf       444:        // directory update of NTFS hard links performed on open.
1.33      paf       445:        // ex: 
                    446:        //   a.html:^test[] and b.html hardlink to a.html
                    447:        //   user inserts ! before ^test in a.html
1.126     paf       448:        //   directory entry of b.html in NTFS not updated at once, 
1.35      paf       449:        //   they delay update till open, so we would receive "!^test[" string
                    450:        //   if would do stat, next open.
1.123     paf       451:        // later: it seems, even this does not help sometimes
1.98      paf       452:     if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123     paf       453:                try {
                    454:                        if(lock_shared_blocking(f)!=0)
1.126     paf       455:                                throw Exception("file.lock", 
1.123     paf       456:                                                &file_spec, 
                    457:                                                "shared lock failed: %s (%d), actual filename '%s'", 
1.126     paf       458:                                                        strerror(errno), errno, fname); 
1.123     paf       459: 
1.124     paf       460:                        struct stat finfo;
                    461:                        if(stat(fname, &finfo)!=0)
                    462:                                throw Exception("file.missing", // hardly possible: we just opened it OK
                    463:                                        &file_spec, 
                    464:                                        "stat failed: %s (%d), actual filename '%s'", 
1.126     paf       465:                                                strerror(errno), errno, fname); 
1.124     paf       466: 
1.105     paf       467: #ifdef NO_FOREIGN_GROUP_FILES
1.123     paf       468:                        if(finfo.st_gid/*foreign?*/!=getegid()) {
1.126     paf       469:                                throw Exception("parser.runtime", 
                    470:                                        &file_spec, 
1.123     paf       471:                                        "parser reading files of foreign group disabled [recompile parser without --disable-foreign-group-files configure option], actual filename '%s'", 
1.126     paf       472:                                                fname); 
1.105     paf       473: #endif
1.32      paf       474: 
1.126     paf       475:                        action(pool, finfo, f, file_spec, fname, as_text, context); 
1.123     paf       476:                } catch(...) {
1.126     paf       477:                        unlock(f);close(f); 
1.123     paf       478:                        if(fail_on_read_problem)
                    479:                                /*re*/throw;
                    480:                        return false;                   
                    481:                } 
1.87      paf       482: 
1.126     paf       483:                unlock(f);close(f); 
1.72      parser    484:                return true;
1.118     paf       485:     } else {
                    486:                if(fail_on_read_problem)
1.126     paf       487:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.118     paf       488:                                &file_spec, 
1.123     paf       489:                                "%s failed: %s (%d), actual filename '%s'", 
1.126     paf       490:                                        action_name, strerror(errno), errno, fname); 
1.118     paf       491:                return false;
                    492:        }
1.8       paf       493: }
                    494: 
1.63      parser    495: static void create_dir_for_file(const String& file_spec) {
                    496:        size_t pos_after=1;
                    497:        int pos_before;
                    498:        while((pos_before=file_spec.pos("/", 1, pos_after))>=0) {
1.126     paf       499:                mkdir(file_spec.mid(0, pos_before).cstr(String::UL_FILE_SPEC), 0775); 
1.63      parser    500:                pos_after=pos_before+1;
                    501:        }
                    502: }
                    503: 
1.98      paf       504: bool file_write_action_under_lock(
1.28      paf       505:                                const String& file_spec, 
1.126     paf       506:                                const char* action_name, File_write_action action, void *context, 
                    507:                                bool as_text, 
                    508:                                bool do_append, 
                    509:                                bool do_block, 
1.110     paf       510:                                bool fail_on_lock_problem) {
1.126     paf       511:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.28      paf       512:        int f;
1.80      paf       513:        if(access(fname, W_OK)!=0) // no
1.126     paf       514:                create_dir_for_file(file_spec); 
1.50      paf       515: 
1.80      paf       516:        if((f=open(fname, 
                    517:                O_CREAT|O_RDWR
                    518:                |(as_text?_O_TEXT:_O_BINARY)
1.122     paf       519:                |(do_append?O_APPEND:0), 0664))>=0) {
1.99      paf       520:                if((do_block?lock_exclusive_blocking(f):lock_exclusive_nonblocking(f))!=0) {
1.126     paf       521:                        Exception e("file.lock", 
1.110     paf       522:                                &file_spec, 
                    523:                                "shared lock failed: %s (%d), actual filename '%s'", 
1.126     paf       524:                                strerror(errno), errno, fname); 
                    525:                        close(f); 
1.110     paf       526:                        if(fail_on_lock_problem)
                    527:                                throw e;
1.98      paf       528:                        return false;
                    529:                }
1.96      paf       530: 
                    531:                try {
1.126     paf       532:                        action(f, context); 
1.96      paf       533:                } catch(...) {
1.104     paf       534:                        if(!do_append)
1.125     paf       535:                                ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.126     paf       536:                        unlock(f);close(f); 
1.96      paf       537:                        /*re*/throw;
                    538:                }
1.80      paf       539:                
1.104     paf       540:                if(!do_append)
1.125     paf       541:                        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       542:                unlock(f);close(f); 
1.98      paf       543:                return true;
1.80      paf       544:        } else
1.126     paf       545:                throw Exception(errno==EACCES?"file.access":0, 
1.80      paf       546:                        &file_spec, 
1.96      paf       547:                        "%s failed: %s (%d), actual filename '%s'", 
1.126     paf       548:                                action_name, strerror(errno), errno, fname); 
1.96      paf       549:        // here should be nothing, see rethrow above
                    550: }
                    551: 
                    552: #ifndef DOXYGEN
                    553: struct File_write_action_info {
                    554:        const void *data; size_t size;
1.126     paf       555: }; 
1.96      paf       556: #endif
                    557: static void file_write_action(int f, void *context) {
1.126     paf       558:        File_write_action_info& info=*static_cast<File_write_action_info *>(context); 
1.113     paf       559:        if(info.size) {
1.126     paf       560:                int written=write(f, info.data, info.size); 
1.116     paf       561:                if(written<0)
1.126     paf       562:                        throw Exception(0, 
                    563:                                0, 
                    564:                                "write failed: %s (%d)",  strerror(errno), errno); 
1.113     paf       565:        }
1.96      paf       566: }
                    567: void file_write(
                    568:                                const String& file_spec, 
                    569:                                const void *data, size_t size, 
1.126     paf       570:                                bool as_text, 
1.96      paf       571:                                bool do_append) {
1.126     paf       572:        File_write_action_info info={data, size}; 
1.98      paf       573:        file_write_action_under_lock(
1.96      paf       574:                                file_spec, 
1.126     paf       575:                                "write", file_write_action, &info, 
                    576:                                as_text, 
                    577:                                do_append); 
1.30      paf       578: }
                    579: 
1.63      parser    580: // throws nothing! [this is required in file_move & file_delete]
1.50      paf       581: static void rmdir(const String& file_spec, size_t pos_after) {
                    582:        int pos_before;
                    583:        if((pos_before=file_spec.pos("/", 1, pos_after))>=0)
1.126     paf       584:                rmdir(file_spec, pos_before+1); 
1.50      paf       585:        
1.126     paf       586:        rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::UL_FILE_SPEC)); 
1.50      paf       587: }
1.95      paf       588: bool file_delete(const String& file_spec, bool fail_on_read_problem) {
1.126     paf       589:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.54      parser    590:        if(unlink(fname)!=0)
1.93      paf       591:                if(fail_on_read_problem)
1.126     paf       592:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.93      paf       593:                                &file_spec, 
                    594:                                "unlink failed: %s (%d), actual filename '%s'", 
1.126     paf       595:                                        strerror(errno), errno, fname); 
1.93      paf       596:                else
                    597:                        return false;
1.50      paf       598: 
1.126     paf       599:        rmdir(file_spec, 1); 
1.93      paf       600:        return true;
1.60      parser    601: }
1.95      paf       602: void file_move(const String& old_spec, const String& new_spec) {
1.126     paf       603:        const char* old_spec_cstr=old_spec.cstr(String::UL_FILE_SPEC); 
                    604:        const char* new_spec_cstr=new_spec.cstr(String::UL_FILE_SPEC); 
1.63      parser    605:        
1.126     paf       606:        create_dir_for_file(new_spec); 
1.63      parser    607: 
1.60      parser    608:        if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126     paf       609:                throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.60      parser    610:                        &old_spec, 
                    611:                        "rename failed: %s (%d), actual filename '%s' to '%s'", 
1.126     paf       612:                                strerror(errno), errno, old_spec_cstr, new_spec_cstr); 
1.63      parser    613: 
1.126     paf       614:        rmdir(old_spec, 1); 
1.31      paf       615: }
                    616: 
1.51      paf       617: 
1.126     paf       618: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118     paf       619:        struct stat lfinfo;
                    620:        bool result=stat(fname, &lfinfo)==0;
                    621:        if(afinfo)
                    622:                *afinfo=lfinfo;
                    623:        return result;
1.119     paf       624: }
                    625: 
                    626: bool entry_exists(const String& file_spec) {
1.126     paf       627:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
                    628:        return entry_exists(fname, 0); 
1.118     paf       629: }
                    630: 
1.51      paf       631: static bool entry_readable(const String& file_spec, bool need_dir) {
1.126     paf       632:     char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.120     paf       633:        if(need_dir) {
1.126     paf       634:                size_t size=strlen(fname); 
1.120     paf       635:                while(size) {
1.126     paf       636:                        char c=fname[size-1]; 
1.120     paf       637:                        if(c=='/' || c=='\\')
                    638:                                fname[--size]=0;
                    639:                        else
                    640:                                break;
                    641:                }
                    642:        }
1.51      paf       643:        struct stat finfo;
1.118     paf       644:        if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109     paf       645:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51      paf       646:                return is_dir==need_dir;
                    647:        }
                    648:        return false;
                    649: }
1.31      paf       650: bool file_readable(const String& file_spec) {
1.126     paf       651:        return entry_readable(file_spec, false); 
1.51      paf       652: }
                    653: bool dir_readable(const String& file_spec) {
1.126     paf       654:        return entry_readable(file_spec, true); 
1.65      parser    655: }
                    656: String *file_readable(const String& path, const String& name) {
1.126     paf       657:        String *result=new(path.pool()) String(path); 
                    658:        *result << "/"; 
1.65      parser    659:        *result << name;
                    660:        return file_readable(*result)?result:0;
1.43      paf       661: }
                    662: bool file_executable(const String& file_spec) {
1.64      parser    663:     return access(file_spec.cstr(String::UL_FILE_SPEC), X_OK)==0;
1.44      paf       664: }
                    665: 
1.64      parser    666: bool file_stat(const String& file_spec, 
1.58      parser    667:                           size_t& rsize, 
1.126     paf       668:                           time_t& ratime, 
                    669:                           time_t& rmtime, 
                    670:                           time_t& rctime, 
1.64      parser    671:                           bool fail_on_read_problem) {
1.126     paf       672:        Pool& pool=file_spec.pool(); 
                    673:        const char* fname=file_spec.cstr(String::UL_FILE_SPEC); 
1.44      paf       674:     struct stat finfo;
                    675:        if(stat(fname, &finfo)!=0)
1.64      parser    676:                if(fail_on_read_problem)
1.126     paf       677:                        throw Exception("file.missing", 
1.67      parser    678:                                &file_spec, 
                    679:                                "getting file size failed: %s (%d), real filename '%s'", 
1.126     paf       680:                                        strerror(errno), errno, fname); 
1.64      parser    681:                else
                    682:                        return false;
1.58      parser    683:        rsize=finfo.st_size;
                    684:        ratime=finfo.st_atime;
                    685:        rmtime=finfo.st_mtime;
                    686:        rctime=finfo.st_ctime;
1.64      parser    687:        return true;
1.18      paf       688: }
                    689: 
1.126     paf       690: char* getrow(char* *row_ref, char delim) {
                    691:     char* result=*row_ref;
1.8       paf       692:     if(result) {
1.126     paf       693:                *row_ref=strchr(result, delim); 
1.8       paf       694:                if(*row_ref) 
                    695:                        *((*row_ref)++)=0; 
                    696:                else if(!*result) 
                    697:                        return 0;
                    698:     }
                    699:     return result;
                    700: }
                    701: 
1.126     paf       702: char* lsplit(char* string, char delim) {
1.23      paf       703:     if(string) {
1.126     paf       704:                char* v=strchr(string, delim); 
1.8       paf       705:                if(v) {
                    706:                        *v=0;
                    707:                        return v+1;
                    708:                }
                    709:     }
                    710:     return 0;
                    711: }
                    712: 
1.126     paf       713: char* lsplit(char* *string_ref, char delim) {
                    714:     char* result=*string_ref;
                    715:        char* next=lsplit(*string_ref, delim); 
1.8       paf       716:     *string_ref=next;
                    717:     return result;
1.9       paf       718: }
                    719: 
1.126     paf       720: char* rsplit(char* string, char delim) {
1.18      paf       721:     if(string) {
1.126     paf       722:                char* v=strrchr(string, delim); 
1.18      paf       723:                if(v) {
1.9       paf       724:                        *v=0;
                    725:                        return v+1;
                    726:                }
                    727:     }
                    728:     return NULL;       
1.10      paf       729: }
                    730: 
1.37      paf       731: /// @todo less stupid type detection
1.126     paf       732: char* format(Pool& pool, double value, char* fmt) {
                    733:        char local_buf[MAX_NUMBER]; 
1.108     paf       734:        size_t size;
                    735:        
1.10      paf       736:        if(fmt)
                    737:                if(strpbrk(fmt, "diouxX"))
                    738:                        if(strpbrk(fmt, "ouxX"))
1.126     paf       739:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.10      paf       740:                        else
1.126     paf       741:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
1.10      paf       742:                else
1.126     paf       743:                        size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
1.10      paf       744:        else
1.126     paf       745:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value); 
1.10      paf       746:        
1.126     paf       747:        char* pool_buf=(char *)pool.malloc(size+1, 4); 
                    748:        memcpy(pool_buf, local_buf, size+1); 
1.108     paf       749:        return pool_buf;
1.12      paf       750: }
                    751: 
1.36      paf       752: size_t stdout_write(const void *buf, size_t size) {
1.12      paf       753: #ifdef WIN32
                    754:        do{
1.126     paf       755:                int chunk_written=fwrite(buf, 1, min(8*0x400, size), stdout); 
1.12      paf       756:                if(chunk_written<=0)
                    757:                        break;
                    758:                size-=chunk_written;
1.36      paf       759:                buf=((const char*)buf)+chunk_written;
1.126     paf       760:        } while(size>0); 
1.12      paf       761: 
                    762:        return size;
                    763: #else
1.126     paf       764:        return fwrite(buf, 1, size, stdout); 
1.12      paf       765: #endif
1.2       paf       766: }
1.14      paf       767: 
1.126     paf       768: char* unescape_chars(Pool& pool, const char* cp, int len) {
                    769:        char* s=(char *)pool.malloc(len + 1, 5); 
1.14      paf       770:        enum EscapeState {
1.33      paf       771:                EscapeRest, 
                    772:                EscapeFirst, 
1.14      paf       773:                EscapeSecond
                    774:        } escapeState=EscapeRest;
                    775:        int escapedValue=0;
                    776:        int srcPos=0;
                    777:        int dstPos=0;
                    778:        while(srcPos < len) {
1.126     paf       779:                int ch=cp[srcPos]; 
1.14      paf       780:                switch(escapeState) {
                    781:                        case EscapeRest:
                    782:                        if(ch=='%') {
                    783:                                escapeState=EscapeFirst;
                    784:                        } else if(ch=='+') {
1.126     paf       785:                                s[dstPos++]=' '; 
1.14      paf       786:                        } else {
                    787:                                s[dstPos++]=ch; 
                    788:                        }
                    789:                        break;
                    790:                        case EscapeFirst:
                    791:                        escapedValue=hex_value[ch] << 4;        
                    792:                        escapeState=EscapeSecond;
                    793:                        break;
                    794:                        case EscapeSecond:
1.126     paf       795:                        escapedValue +=hex_value[ch]; 
1.14      paf       796:                        s[dstPos++]=escapedValue;
                    797:                        escapeState=EscapeRest;
                    798:                        break;
                    799:                }
1.126     paf       800:                srcPos++; 
1.14      paf       801:        }
                    802:        s[dstPos]=0;
                    803:        return s;
1.24      paf       804: }
                    805: 
                    806: #ifdef WIN32
1.126     paf       807: void back_slashes_to_slashes(char* s) {
1.24      paf       808:        if(s)
                    809:                for(; *s; s++)
                    810:                        if(*s=='\\')
1.126     paf       811:                                *s='/'; 
1.24      paf       812: }
1.42      paf       813: /*
1.126     paf       814: void slashes_to_back_slashes(char* s) {
1.42      paf       815:        if(s)
                    816:                for(; *s; s++)
                    817:                        if(*s=='/')
1.126     paf       818:                                *s='\\'; 
1.42      paf       819: }
                    820: */
1.24      paf       821: #endif
1.41      paf       822: 
1.126     paf       823: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41      paf       824:        while(true) {
                    825:                if(!(*s1)) {
                    826:                        if(!(*s2))
                    827:                                return true;
                    828:                        else
                    829:                                return !strict;
                    830:                } else if(!(*s2))
                    831:                        return !strict;
                    832:                if(isalpha(*s1)) {
                    833:                        if(tolower(*s1) !=tolower(*s2))
                    834:                                return false;
                    835:                } else if((*s1) !=(*s2))
                    836:                        return false;
1.126     paf       837:                s1++; 
                    838:                s2++; 
1.41      paf       839:        }
1.57      parser    840: }
                    841: 
1.84      paf       842: static bool isLeap(int year) {
1.57      parser    843:     return !(
                    844:              (year % 4) || ((year % 400) && !(year % 100))
1.126     paf       845:             ); 
1.57      parser    846: }
                    847: 
                    848: int getMonthDays(int year, int month) {
                    849:     int monthDays[]={
1.126     paf       850:         31, 
                    851:         isLeap(year) ? 29 : 28, 
                    852:         31, 
                    853:         30, 
                    854:         31, 
                    855:         30, 
                    856:         31, 
                    857:         31, 
                    858:         30, 
                    859:         31, 
                    860:         30, 
1.57      parser    861:         31
1.126     paf       862:     }; 
                    863:     return monthDays[month]; 
1.41      paf       864: }
1.69      parser    865: 
1.126     paf       866: void remove_crlf(char* start, char* end) {
                    867:        for(char* p=start; p<end; p++)
1.69      parser    868:                switch(*p) {
1.126     paf       869:                        case '\n': *p='|';  break;
                    870:                        case '\r': *p=' ';  break;
1.69      parser    871:                }
1.91      paf       872: }
                    873: 
                    874: 
                    875: /// must be last in this file
                    876: #undef vsnprintf
1.126     paf       877: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91      paf       878:        if(!s)
                    879:                return 0;
                    880: 
                    881:        int r;
                    882:        // note: on win32& maybe somewhere else
                    883:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                    884:        --s;
                    885: #if _MSC_VER
                    886:        /*
                    887:        win32: 
                    888:        mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
                    889: 
                    890:          if the number of bytes to write exceeds buffer, then count bytes are written and –1 is returned
                    891:        */
1.126     paf       892:        r=_vsnprintf(b, s, f, l); 
1.91      paf       893:        if(r<0) 
                    894:                r=s;
                    895: #else
1.126     paf       896:        r=vsnprintf(b, s, f, l); 
1.91      paf       897:        /*
                    898:        solaris: 
                    899:        man vsnprintf
                    900: 
                    901:          The snprintf() function returns  the  number  of  characters
                    902:        formatted, that is, the number of characters that would have
                    903:        been written to the buffer if it were large enough.  If  the
                    904:        value  of  n  is  0  on a call to snprintf(), an unspecified
                    905:        value less than 1 is returned.
                    906:        */
                    907: 
                    908:        if(r<0)
                    909:                r=0;
                    910:        else if(r>s)
                    911:                r=s;
                    912: #endif
                    913:        b[r]=0;
                    914:        return r;
                    915: }
                    916: 
1.126     paf       917: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91      paf       918:        va_list l;
1.126     paf       919:     va_start(l, f); 
                    920:     int r=__vsnprintf(b, s, f, l); 
                    921:     va_end(l); 
1.91      paf       922:        return r;
1.98      paf       923: }
                    924: 
                    925: int pa_sleep(unsigned long secs, unsigned long usecs) {
1.126     paf       926:        for (;  usecs >= 1000000; ++secs, usecs -= 1000000); 
1.98      paf       927: 
                    928: #ifdef WIN32
1.126     paf       929:        Sleep(secs * 1000 + usecs / 1000); 
1.98      paf       930:        return 0;
                    931: #else
                    932:        struct timeval t;
                    933:        t.tv_sec = secs;
                    934:        t.tv_usec = usecs;
1.126     paf       935:        return (select(0, NULL, NULL, NULL, &t) == -1 ? errno : 0); 
1.98      paf       936: #endif
1.74      parser    937: }

E-mail: