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