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

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

E-mail: