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