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