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

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

E-mail: