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