Annotation of parser3/src/main/pa_common.C, revision 1.143.2.21.2.22
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. 2(paf 8:3): static const char* IDENT_COMMON_C="$Date: 2003/04/02 10:35:07 $";
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)
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. 1(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. 1(paf 488:3): result.str=http.str;
489:3): result.length=http.length;
2(paf 490:3): result.headers=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;
2(paf 505:3): if(strncmp(in, "\xEB\xBB\xBF", 3)==0) {
(paf 506:): result.str=in+3; result.length-=3;// skip prefix
1.131 paf 507: }
508: }
509:
1.143.2.21.2. (paf 510:): fix_line_breaks((char *)(result.str), result.length);
1.123 paf 511: // note: after fixing
1.143.2.21.2. (paf 512:): ((char*&)(result.str))[result.length]=0;
1.123 paf 513: }
1.126 paf 514:
515: return result;
1.123 paf 516: }
517:
1.143.2.21.2. (paf 518:): bool file_read_action_under_lock(const String& file_spec,
1.126 paf 519: const char* action_name, File_read_action action, void *context,
520: bool as_text,
1.123 paf 521: bool fail_on_read_problem) {
1.143.2.21.2. (paf 522:): const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.33 paf 523: int f;
524:
525: // first open, next stat:
1.45 paf 526: // directory update of NTFS hard links performed on open.
1.33 paf 527: // ex:
528: // a.html:^test[] and b.html hardlink to a.html
529: // user inserts ! before ^test in a.html
1.126 paf 530: // directory entry of b.html in NTFS not updated at once,
1.35 paf 531: // they delay update till open, so we would receive "!^test[" string
532: // if would do stat, next open.
1.123 paf 533: // later: it seems, even this does not help sometimes
1.98 paf 534: if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123 paf 535: try {
536: if(lock_shared_blocking(f)!=0)
1.126 paf 537: throw Exception("file.lock",
1.143.2.21.2. (paf 538:): &file_spec,
1.123 paf 539: "shared lock failed: %s (%d), actual filename '%s'",
1.143.2.21.2. (paf 540:): strerror(errno), errno, fname);
1.123 paf 541:
1.124 paf 542: struct stat finfo;
543: if(stat(fname, &finfo)!=0)
544: throw Exception("file.missing", // hardly possible: we just opened it OK
1.143.2.21.2. (paf 545:): &file_spec,
1.124 paf 546: "stat failed: %s (%d), actual filename '%s'",
1.143.2.21.2. (paf 547:): strerror(errno), errno, fname);
1.124 paf 548:
1.140 paf 549: #ifdef PA_SAFE_MODE
550: if(finfo.st_uid/*foreign?*/!=geteuid()
551: && finfo.st_gid/*foreign?*/!=getegid())
1.126 paf 552: throw Exception("parser.runtime",
1.143.2.21.2. (paf 553:): &file_spec,
1.140 paf 554: "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 555:): fname);
1.105 paf 556: #endif
1.32 paf 557:
1.143.2.21.2. (paf 558:): action(finfo, f, file_spec, fname, as_text, context);
1.123 paf 559: } catch(...) {
1.126 paf 560: unlock(f);close(f);
1.123 paf 561: if(fail_on_read_problem)
1.143.2.11 paf 562: rethrow;
1.123 paf 563: return false;
564: }
1.87 paf 565:
1.126 paf 566: unlock(f);close(f);
1.72 parser 567: return true;
1.118 paf 568: } else {
569: if(fail_on_read_problem)
1.126 paf 570: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.143.2.21.2. (paf 571:): &file_spec,
1.123 paf 572: "%s failed: %s (%d), actual filename '%s'",
1.143.2.21.2. (paf 573:): action_name, strerror(errno), errno, fname);
1.118 paf 574: return false;
575: }
1.8 paf 576: }
577:
1.143.2.21.2. (paf 578:): static void create_dir_for_file(const String& file_spec) {
1.63 parser 579: size_t pos_after=1;
1.143.2.21.2. 2(paf 580:3): size_t pos_before;
3(paf 581:3): while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
(paf 582:): mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775);
1.63 parser 583: pos_after=pos_before+1;
584: }
585: }
586:
1.98 paf 587: bool file_write_action_under_lock(
1.143.2.21.2. (paf 588:): const String& file_spec,
1.126 paf 589: const char* action_name, File_write_action action, void *context,
590: bool as_text,
591: bool do_append,
592: bool do_block,
1.110 paf 593: bool fail_on_lock_problem) {
1.143.2.21.2. (paf 594:): const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.28 paf 595: int f;
1.80 paf 596: if(access(fname, W_OK)!=0) // no
1.126 paf 597: create_dir_for_file(file_spec);
1.50 paf 598:
1.80 paf 599: if((f=open(fname,
600: O_CREAT|O_RDWR
601: |(as_text?_O_TEXT:_O_BINARY)
1.138 paf 602: |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.99 paf 603: if((do_block?lock_exclusive_blocking(f):lock_exclusive_nonblocking(f))!=0) {
1.126 paf 604: Exception e("file.lock",
1.143.2.21.2. (paf 605:): &file_spec,
1.110 paf 606: "shared lock failed: %s (%d), actual filename '%s'",
1.143.2.21.2. (paf 607:): strerror(errno), errno, fname);
1.126 paf 608: close(f);
1.110 paf 609: if(fail_on_lock_problem)
610: throw e;
1.98 paf 611: return false;
612: }
1.96 paf 613:
614: try {
1.126 paf 615: action(f, context);
1.96 paf 616: } catch(...) {
1.138 paf 617: #ifdef HAVE_FTRUNCATE
1.104 paf 618: if(!do_append)
1.125 paf 619: ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138 paf 620: #endif
1.126 paf 621: unlock(f);close(f);
1.143.2.11 paf 622: rethrow;
1.96 paf 623: }
1.80 paf 624:
1.138 paf 625: #ifdef HAVE_FTRUNCATE
1.104 paf 626: if(!do_append)
1.125 paf 627: 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 628: #endif
1.126 paf 629: unlock(f);close(f);
1.98 paf 630: return true;
1.80 paf 631: } else
1.126 paf 632: throw Exception(errno==EACCES?"file.access":0,
1.143.2.21.2. (paf 633:): &file_spec,
1.96 paf 634: "%s failed: %s (%d), actual filename '%s'",
1.143.2.21.2. (paf 635:): action_name, strerror(errno), errno, fname);
1.96 paf 636: // here should be nothing, see rethrow above
637: }
638:
639: #ifndef DOXYGEN
640: struct File_write_action_info {
1.143.2.21.2. (paf 641:): const char* str; size_t length;
1.126 paf 642: };
1.96 paf 643: #endif
644: static void file_write_action(int f, void *context) {
1.126 paf 645: File_write_action_info& info=*static_cast<File_write_action_info *>(context);
1.143.2.21.2. (paf 646:): if(info.length) {
647:): int written=write(f, info.str, info.length);
1.116 paf 648: if(written<0)
1.126 paf 649: throw Exception(0,
1.143.2.21.2. (paf 650:): 0,
1.126 paf 651: "write failed: %s (%d)", strerror(errno), errno);
1.113 paf 652: }
1.96 paf 653: }
654: void file_write(
1.143.2.21.2. (paf 655:): const String& file_spec,
656:): const char* data, size_t size,
1.126 paf 657: bool as_text,
1.96 paf 658: bool do_append) {
1.126 paf 659: File_write_action_info info={data, size};
1.98 paf 660: file_write_action_under_lock(
1.143.2.4 paf 661: file_spec,
662: "write", file_write_action, &info,
663: as_text,
664: do_append);
1.30 paf 665: }
666:
1.63 parser 667: // throws nothing! [this is required in file_move & file_delete]
1.143.2.21.2. (paf 668:): static void rmdir(const String& file_spec, size_t pos_after) {
2(paf 669:3): size_t pos_before;
3(paf 670:3): if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126 paf 671: rmdir(file_spec, pos_before+1);
1.50 paf 672:
1.143.2.21.2. (paf 673:): rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC));
1.50 paf 674: }
1.143.2.21.2. (paf 675:): bool file_delete(const String& file_spec, bool fail_on_read_problem) {
676:): const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.54 parser 677: if(unlink(fname)!=0)
1.93 paf 678: if(fail_on_read_problem)
1.126 paf 679: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.143.2.21.2. (paf 680:): &file_spec,
1.93 paf 681: "unlink failed: %s (%d), actual filename '%s'",
1.143.2.21.2. (paf 682:): strerror(errno), errno, fname);
1.93 paf 683: else
684: return false;
1.50 paf 685:
1.126 paf 686: rmdir(file_spec, 1);
1.93 paf 687: return true;
1.60 parser 688: }
1.143.2.21.2. (paf 689:): void file_move(const String& old_spec, const String& new_spec) {
690:): const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC);
691:): const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC);
1.63 parser 692:
1.126 paf 693: create_dir_for_file(new_spec);
1.63 parser 694:
1.60 parser 695: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 696: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.143.2.21.2. (paf 697:): &old_spec,
1.60 parser 698: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.143.2.21.2. (paf 699:): strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 700:
1.126 paf 701: rmdir(old_spec, 1);
1.31 paf 702: }
703:
1.51 paf 704:
1.126 paf 705: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 706: struct stat lfinfo;
707: bool result=stat(fname, &lfinfo)==0;
708: if(afinfo)
709: *afinfo=lfinfo;
710: return result;
1.119 paf 711: }
712:
1.143.2.21.2. (paf 713:): bool entry_exists(const String& file_spec) {
714:): const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.126 paf 715: return entry_exists(fname, 0);
1.118 paf 716: }
717:
1.143.2.21.2. (paf 718:): static bool entry_readable(const String& file_spec, bool need_dir) {
719:): char* fname=file_spec.cstrm(String::L_FILE_SPEC);
1.120 paf 720: if(need_dir) {
1.126 paf 721: size_t size=strlen(fname);
1.120 paf 722: while(size) {
1.126 paf 723: char c=fname[size-1];
1.120 paf 724: if(c=='/' || c=='\\')
725: fname[--size]=0;
726: else
727: break;
728: }
729: }
1.51 paf 730: struct stat finfo;
1.118 paf 731: if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109 paf 732: bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51 paf 733: return is_dir==need_dir;
734: }
735: return false;
736: }
1.143.2.21.2. (paf 737:): bool file_readable(const String& file_spec) {
1.126 paf 738: return entry_readable(file_spec, false);
1.51 paf 739: }
1.143.2.21.2. (paf 740:): bool dir_readable(const String& file_spec) {
1.126 paf 741: return entry_readable(file_spec, true);
1.65 parser 742: }
1.143.2.21.2. 0(paf 743:3): const String* file_readable(const String& path, const String& name) {
(paf 744:): String& result=*new String(path);
745:): result << "/";
746:): result << name;
747:): return file_readable(result)?&result:0;
1.43 paf 748: }
1.143.2.21.2. (paf 749:): bool file_executable(const String& file_spec) {
750:): return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44 paf 751: }
752:
1.143.2.21.2. (paf 753:): bool file_stat(const String& file_spec,
1.58 parser 754: size_t& rsize,
1.126 paf 755: time_t& ratime,
756: time_t& rmtime,
757: time_t& rctime,
1.64 parser 758: bool fail_on_read_problem) {
1.143.2.21.2. (paf 759:): const char* fname=file_spec.cstr(String::L_FILE_SPEC);
5(paf 760:3): struct stat finfo;
1.44 paf 761: if(stat(fname, &finfo)!=0)
1.64 parser 762: if(fail_on_read_problem)
1.126 paf 763: throw Exception("file.missing",
1.143.2.21.2. (paf 764:): &file_spec,
1.67 parser 765: "getting file size failed: %s (%d), real filename '%s'",
1.143.2.21.2. (paf 766:): strerror(errno), errno, fname);
1.64 parser 767: else
768: return false;
1.58 parser 769: rsize=finfo.st_size;
770: ratime=finfo.st_atime;
771: rmtime=finfo.st_mtime;
772: rctime=finfo.st_ctime;
1.64 parser 773: return true;
1.18 paf 774: }
775:
1.126 paf 776: char* getrow(char* *row_ref, char delim) {
777: char* result=*row_ref;
1.8 paf 778: if(result) {
1.126 paf 779: *row_ref=strchr(result, delim);
1.8 paf 780: if(*row_ref)
781: *((*row_ref)++)=0;
782: else if(!*result)
783: return 0;
784: }
785: return result;
786: }
787:
1.126 paf 788: char* lsplit(char* string, char delim) {
1.23 paf 789: if(string) {
1.126 paf 790: char* v=strchr(string, delim);
1.8 paf 791: if(v) {
792: *v=0;
793: return v+1;
794: }
795: }
796: return 0;
797: }
798:
1.126 paf 799: char* lsplit(char* *string_ref, char delim) {
800: char* result=*string_ref;
801: char* next=lsplit(*string_ref, delim);
1.8 paf 802: *string_ref=next;
803: return result;
1.9 paf 804: }
805:
1.126 paf 806: char* rsplit(char* string, char delim) {
1.18 paf 807: if(string) {
1.126 paf 808: char* v=strrchr(string, delim);
1.18 paf 809: if(v) {
1.9 paf 810: *v=0;
811: return v+1;
812: }
813: }
814: return NULL;
1.10 paf 815: }
816:
1.37 paf 817: /// @todo less stupid type detection
1.143.2.21.2. (paf 818:): const char* format(double value, char* fmt) {
1.126 paf 819: char local_buf[MAX_NUMBER];
1.108 paf 820: size_t size;
821:
1.10 paf 822: if(fmt)
823: if(strpbrk(fmt, "diouxX"))
824: if(strpbrk(fmt, "ouxX"))
1.126 paf 825: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.10 paf 826: else
1.126 paf 827: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
1.10 paf 828: else
1.126 paf 829: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
1.10 paf 830: else
1.126 paf 831: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
1.10 paf 832:
1.143.2.21.2. (paf 833:): return pa_strdup(local_buf, size);
1.12 paf 834: }
835:
1.36 paf 836: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 837: #ifdef WIN32
838: do{
1.143.2.21.2. (paf 839:): int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 840: if(chunk_written<=0)
841: break;
842: size-=chunk_written;
1.36 paf 843: buf=((const char*)buf)+chunk_written;
1.126 paf 844: } while(size>0);
1.12 paf 845:
846: return size;
847: #else
1.126 paf 848: return fwrite(buf, 1, size, stdout);
1.12 paf 849: #endif
1.2 paf 850: }
1.14 paf 851:
1.143.2.21.2. (paf 852:): char* unescape_chars(const char* cp, int len) {
853:): char* s=new(PointerFreeGC) char[len + 1];
1.14 paf 854: enum EscapeState {
1.33 paf 855: EscapeRest,
856: EscapeFirst,
1.14 paf 857: EscapeSecond
858: } escapeState=EscapeRest;
859: int escapedValue=0;
860: int srcPos=0;
861: int dstPos=0;
862: while(srcPos < len) {
1.126 paf 863: int ch=cp[srcPos];
1.14 paf 864: switch(escapeState) {
865: case EscapeRest:
866: if(ch=='%') {
867: escapeState=EscapeFirst;
868: } else if(ch=='+') {
1.126 paf 869: s[dstPos++]=' ';
1.14 paf 870: } else {
871: s[dstPos++]=ch;
872: }
873: break;
874: case EscapeFirst:
875: escapedValue=hex_value[ch] << 4;
876: escapeState=EscapeSecond;
877: break;
878: case EscapeSecond:
1.126 paf 879: escapedValue +=hex_value[ch];
1.14 paf 880: s[dstPos++]=escapedValue;
881: escapeState=EscapeRest;
882: break;
883: }
1.126 paf 884: srcPos++;
1.14 paf 885: }
886: s[dstPos]=0;
887: return s;
1.24 paf 888: }
889:
890: #ifdef WIN32
1.126 paf 891: void back_slashes_to_slashes(char* s) {
1.24 paf 892: if(s)
893: for(; *s; s++)
894: if(*s=='\\')
1.126 paf 895: *s='/';
1.24 paf 896: }
1.42 paf 897: /*
1.126 paf 898: void slashes_to_back_slashes(char* s) {
1.42 paf 899: if(s)
900: for(; *s; s++)
901: if(*s=='/')
1.126 paf 902: *s='\\';
1.42 paf 903: }
904: */
1.24 paf 905: #endif
1.41 paf 906:
1.126 paf 907: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41 paf 908: while(true) {
909: if(!(*s1)) {
910: if(!(*s2))
911: return true;
912: else
913: return !strict;
914: } else if(!(*s2))
915: return !strict;
916: if(isalpha(*s1)) {
917: if(tolower(*s1) !=tolower(*s2))
918: return false;
919: } else if((*s1) !=(*s2))
920: return false;
1.126 paf 921: s1++;
922: s2++;
1.41 paf 923: }
1.57 parser 924: }
925:
1.84 paf 926: static bool isLeap(int year) {
1.57 parser 927: return !(
928: (year % 4) || ((year % 400) && !(year % 100))
1.126 paf 929: );
1.57 parser 930: }
931:
932: int getMonthDays(int year, int month) {
933: int monthDays[]={
1.126 paf 934: 31,
935: isLeap(year) ? 29 : 28,
936: 31,
937: 30,
938: 31,
939: 30,
940: 31,
941: 31,
942: 30,
943: 31,
944: 30,
1.57 parser 945: 31
1.126 paf 946: };
947: return monthDays[month];
1.41 paf 948: }
1.69 parser 949:
1.126 paf 950: void remove_crlf(char* start, char* end) {
951: for(char* p=start; p<end; p++)
1.69 parser 952: switch(*p) {
1.126 paf 953: case '\n': *p='|'; break;
954: case '\r': *p=' '; break;
1.69 parser 955: }
1.91 paf 956: }
957:
958:
959: /// must be last in this file
960: #undef vsnprintf
1.126 paf 961: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 962: if(!s)
963: return 0;
964:
965: int r;
966: // note: on win32& maybe somewhere else
967: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
968: --s;
969: #if _MSC_VER
970: /*
971: win32:
972: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
973:
1.143.2.12 paf 974: if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91 paf 975: */
1.126 paf 976: r=_vsnprintf(b, s, f, l);
1.91 paf 977: if(r<0)
978: r=s;
979: #else
1.126 paf 980: r=vsnprintf(b, s, f, l);
1.91 paf 981: /*
982: solaris:
983: man vsnprintf
984:
985: The snprintf() function returns the number of characters
986: formatted, that is, the number of characters that would have
987: been written to the buffer if it were large enough. If the
988: value of n is 0 on a call to snprintf(), an unspecified
989: value less than 1 is returned.
990: */
991:
992: if(r<0)
993: r=0;
994: else if(r>s)
995: r=s;
996: #endif
997: b[r]=0;
998: return r;
999: }
1000:
1.126 paf 1001: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 1002: va_list l;
1.126 paf 1003: va_start(l, f);
1004: int r=__vsnprintf(b, s, f, l);
1005: va_end(l);
1.91 paf 1006: return r;
1.98 paf 1007: }
1008:
1009: int pa_sleep(unsigned long secs, unsigned long usecs) {
1.126 paf 1010: for (; usecs >= 1000000; ++secs, usecs -= 1000000);
1.98 paf 1011:
1012: #ifdef WIN32
1.126 paf 1013: Sleep(secs * 1000 + usecs / 1000);
1.98 paf 1014: return 0;
1015: #else
1016: struct timeval t;
1017: t.tv_sec = secs;
1018: t.tv_usec = usecs;
1.126 paf 1019: return (select(0, NULL, NULL, NULL, &t) == -1 ? errno : 0);
1.98 paf 1020: #endif
1.135 paf 1021: }
1022:
1023:
E-mail: