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

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

E-mail: