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