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