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