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