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