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