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