Annotation of parser3/src/main/pa_common.C, revision 1.127
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.127 ! paf 8: static const char* IDENT_COMMON_C="$Date: 2002/11/25 14:10:52 $";
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:
343: headers.put(line->mid(0, pos), new(pool) VString(line->mid(pos+2, line->size())));
344: } else
345: throw Exception("http.response",
346: &file_spec,
347: "bad response from host - bad headers \"%s\"", header_block.cstr());
348: }
349:
350: // output response
351: data=body.cstr(); data_size=body.size();
352: if(out_fields) {
353: headers.put(*file_status_name, new(pool) VString(*status_code));
354: *out_fields=&headers;
355: }
1.34 paf 356: }
1.123 paf 357:
358: #ifndef DOXYGEN
359: struct File_read_action_info {
360: void **data; size_t *data_size;
1.126 paf 361: };
1.123 paf 362: #endif
1.126 paf 363: static void file_read_action(Pool& pool,
364: struct stat& finfo,
1.123 paf 365: int f,
1.126 paf 366: const String& file_spec, const char* fname, bool as_text,
1.123 paf 367: void *context) {
1.126 paf 368: File_read_action_info& info=*static_cast<File_read_action_info *>(context);
1.123 paf 369: if(size_t to_read_size=(size_t)finfo.st_size) {
1.126 paf 370: *info.data=pool.malloc(to_read_size+(as_text?1:0), 3);
371: *info.data_size=(size_t)read(f, *info.data, to_read_size);
1.123 paf 372:
373: if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126 paf 374: throw Exception(0,
1.123 paf 375: &file_spec,
376: "read failed: actually read %lu bytes count not in [0..%lu] valid range",
1.126 paf 377: *info.data_size, to_read_size);
1.123 paf 378: } else { // empty file
379: if(as_text) {
1.126 paf 380: *info.data=pool.malloc(1);
1.123 paf 381: *(char*)(*info.data)=0;
382: } else
383: *info.data=0;
384: *info.data_size=0;
385: return;
386: }
1.126 paf 387: }
388: bool file_read(Pool& pool, const String& file_spec,
389: void*& data, size_t& data_size,
390: bool as_text, Hash *params, Hash** out_fields,
391: bool fail_on_read_problem) {
392: bool result;
393: if(file_spec.starts_with("http://", 7)) {
394: // fail on read problem
395: file_read_http(pool, file_spec, data, data_size, params, out_fields);
396: result=true;
397: } else {
398: File_read_action_info info={&data, &data_size};
399: result=file_read_action_under_lock(pool, file_spec,
400: "read", file_read_action, &info,
401: as_text, fail_on_read_problem);
402: }
1.123 paf 403:
1.126 paf 404: if(result && as_text) {
405: fix_line_breaks((char *)(data), data_size);
1.123 paf 406: // note: after fixing
1.126 paf 407: ((char*&)(data))[data_size]=0;
1.123 paf 408: }
1.126 paf 409:
410: return result;
1.123 paf 411: }
412:
413: bool file_read_action_under_lock(Pool& pool, const String& file_spec,
1.126 paf 414: const char* action_name, File_read_action action, void *context,
415: bool as_text,
1.123 paf 416: bool fail_on_read_problem) {
1.126 paf 417: const char* fname=file_spec.cstr(String::UL_FILE_SPEC);
1.33 paf 418: int f;
419:
420: // first open, next stat:
1.45 paf 421: // directory update of NTFS hard links performed on open.
1.33 paf 422: // ex:
423: // a.html:^test[] and b.html hardlink to a.html
424: // user inserts ! before ^test in a.html
1.126 paf 425: // directory entry of b.html in NTFS not updated at once,
1.35 paf 426: // they delay update till open, so we would receive "!^test[" string
427: // if would do stat, next open.
1.123 paf 428: // later: it seems, even this does not help sometimes
1.98 paf 429: if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123 paf 430: try {
431: if(lock_shared_blocking(f)!=0)
1.126 paf 432: throw Exception("file.lock",
1.123 paf 433: &file_spec,
434: "shared lock failed: %s (%d), actual filename '%s'",
1.126 paf 435: strerror(errno), errno, fname);
1.123 paf 436:
1.124 paf 437: struct stat finfo;
438: if(stat(fname, &finfo)!=0)
439: throw Exception("file.missing", // hardly possible: we just opened it OK
440: &file_spec,
441: "stat failed: %s (%d), actual filename '%s'",
1.126 paf 442: strerror(errno), errno, fname);
1.124 paf 443:
1.105 paf 444: #ifdef NO_FOREIGN_GROUP_FILES
1.123 paf 445: if(finfo.st_gid/*foreign?*/!=getegid()) {
1.126 paf 446: throw Exception("parser.runtime",
447: &file_spec,
1.123 paf 448: "parser reading files of foreign group disabled [recompile parser without --disable-foreign-group-files configure option], actual filename '%s'",
1.126 paf 449: fname);
1.105 paf 450: #endif
1.32 paf 451:
1.126 paf 452: action(pool, finfo, f, file_spec, fname, as_text, context);
1.123 paf 453: } catch(...) {
1.126 paf 454: unlock(f);close(f);
1.123 paf 455: if(fail_on_read_problem)
456: /*re*/throw;
457: return false;
458: }
1.87 paf 459:
1.126 paf 460: unlock(f);close(f);
1.72 parser 461: return true;
1.118 paf 462: } else {
463: if(fail_on_read_problem)
1.126 paf 464: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.118 paf 465: &file_spec,
1.123 paf 466: "%s failed: %s (%d), actual filename '%s'",
1.126 paf 467: action_name, strerror(errno), errno, fname);
1.118 paf 468: return false;
469: }
1.8 paf 470: }
471:
1.63 parser 472: static void create_dir_for_file(const String& file_spec) {
473: size_t pos_after=1;
474: int pos_before;
475: while((pos_before=file_spec.pos("/", 1, pos_after))>=0) {
1.126 paf 476: mkdir(file_spec.mid(0, pos_before).cstr(String::UL_FILE_SPEC), 0775);
1.63 parser 477: pos_after=pos_before+1;
478: }
479: }
480:
1.98 paf 481: bool file_write_action_under_lock(
1.28 paf 482: const String& file_spec,
1.126 paf 483: const char* action_name, File_write_action action, void *context,
484: bool as_text,
485: bool do_append,
486: bool do_block,
1.110 paf 487: bool fail_on_lock_problem) {
1.126 paf 488: const char* fname=file_spec.cstr(String::UL_FILE_SPEC);
1.28 paf 489: int f;
1.80 paf 490: if(access(fname, W_OK)!=0) // no
1.126 paf 491: create_dir_for_file(file_spec);
1.50 paf 492:
1.80 paf 493: if((f=open(fname,
494: O_CREAT|O_RDWR
495: |(as_text?_O_TEXT:_O_BINARY)
1.122 paf 496: |(do_append?O_APPEND:0), 0664))>=0) {
1.99 paf 497: if((do_block?lock_exclusive_blocking(f):lock_exclusive_nonblocking(f))!=0) {
1.126 paf 498: Exception e("file.lock",
1.110 paf 499: &file_spec,
500: "shared lock failed: %s (%d), actual filename '%s'",
1.126 paf 501: strerror(errno), errno, fname);
502: close(f);
1.110 paf 503: if(fail_on_lock_problem)
504: throw e;
1.98 paf 505: return false;
506: }
1.96 paf 507:
508: try {
1.126 paf 509: action(f, context);
1.96 paf 510: } catch(...) {
1.104 paf 511: if(!do_append)
1.125 paf 512: ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.126 paf 513: unlock(f);close(f);
1.96 paf 514: /*re*/throw;
515: }
1.80 paf 516:
1.104 paf 517: if(!do_append)
1.125 paf 518: 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 519: unlock(f);close(f);
1.98 paf 520: return true;
1.80 paf 521: } else
1.126 paf 522: throw Exception(errno==EACCES?"file.access":0,
1.80 paf 523: &file_spec,
1.96 paf 524: "%s failed: %s (%d), actual filename '%s'",
1.126 paf 525: action_name, strerror(errno), errno, fname);
1.96 paf 526: // here should be nothing, see rethrow above
527: }
528:
529: #ifndef DOXYGEN
530: struct File_write_action_info {
531: const void *data; size_t size;
1.126 paf 532: };
1.96 paf 533: #endif
534: static void file_write_action(int f, void *context) {
1.126 paf 535: File_write_action_info& info=*static_cast<File_write_action_info *>(context);
1.113 paf 536: if(info.size) {
1.126 paf 537: int written=write(f, info.data, info.size);
1.116 paf 538: if(written<0)
1.126 paf 539: throw Exception(0,
540: 0,
541: "write failed: %s (%d)", strerror(errno), errno);
1.113 paf 542: }
1.96 paf 543: }
544: void file_write(
545: const String& file_spec,
546: const void *data, size_t size,
1.126 paf 547: bool as_text,
1.96 paf 548: bool do_append) {
1.126 paf 549: File_write_action_info info={data, size};
1.98 paf 550: file_write_action_under_lock(
1.96 paf 551: file_spec,
1.126 paf 552: "write", file_write_action, &info,
553: as_text,
554: do_append);
1.30 paf 555: }
556:
1.63 parser 557: // throws nothing! [this is required in file_move & file_delete]
1.50 paf 558: static void rmdir(const String& file_spec, size_t pos_after) {
559: int pos_before;
560: if((pos_before=file_spec.pos("/", 1, pos_after))>=0)
1.126 paf 561: rmdir(file_spec, pos_before+1);
1.50 paf 562:
1.126 paf 563: rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::UL_FILE_SPEC));
1.50 paf 564: }
1.95 paf 565: bool file_delete(const String& file_spec, bool fail_on_read_problem) {
1.126 paf 566: const char* fname=file_spec.cstr(String::UL_FILE_SPEC);
1.54 parser 567: if(unlink(fname)!=0)
1.93 paf 568: if(fail_on_read_problem)
1.126 paf 569: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.93 paf 570: &file_spec,
571: "unlink failed: %s (%d), actual filename '%s'",
1.126 paf 572: strerror(errno), errno, fname);
1.93 paf 573: else
574: return false;
1.50 paf 575:
1.126 paf 576: rmdir(file_spec, 1);
1.93 paf 577: return true;
1.60 parser 578: }
1.95 paf 579: void file_move(const String& old_spec, const String& new_spec) {
1.126 paf 580: const char* old_spec_cstr=old_spec.cstr(String::UL_FILE_SPEC);
581: const char* new_spec_cstr=new_spec.cstr(String::UL_FILE_SPEC);
1.63 parser 582:
1.126 paf 583: create_dir_for_file(new_spec);
1.63 parser 584:
1.60 parser 585: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 586: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.60 parser 587: &old_spec,
588: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.126 paf 589: strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 590:
1.126 paf 591: rmdir(old_spec, 1);
1.31 paf 592: }
593:
1.51 paf 594:
1.126 paf 595: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 596: struct stat lfinfo;
597: bool result=stat(fname, &lfinfo)==0;
598: if(afinfo)
599: *afinfo=lfinfo;
600: return result;
1.119 paf 601: }
602:
603: bool entry_exists(const String& file_spec) {
1.126 paf 604: const char* fname=file_spec.cstr(String::UL_FILE_SPEC);
605: return entry_exists(fname, 0);
1.118 paf 606: }
607:
1.51 paf 608: static bool entry_readable(const String& file_spec, bool need_dir) {
1.126 paf 609: char* fname=file_spec.cstr(String::UL_FILE_SPEC);
1.120 paf 610: if(need_dir) {
1.126 paf 611: size_t size=strlen(fname);
1.120 paf 612: while(size) {
1.126 paf 613: char c=fname[size-1];
1.120 paf 614: if(c=='/' || c=='\\')
615: fname[--size]=0;
616: else
617: break;
618: }
619: }
1.51 paf 620: struct stat finfo;
1.118 paf 621: if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109 paf 622: bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51 paf 623: return is_dir==need_dir;
624: }
625: return false;
626: }
1.31 paf 627: bool file_readable(const String& file_spec) {
1.126 paf 628: return entry_readable(file_spec, false);
1.51 paf 629: }
630: bool dir_readable(const String& file_spec) {
1.126 paf 631: return entry_readable(file_spec, true);
1.65 parser 632: }
633: String *file_readable(const String& path, const String& name) {
1.126 paf 634: String *result=new(path.pool()) String(path);
635: *result << "/";
1.65 parser 636: *result << name;
637: return file_readable(*result)?result:0;
1.43 paf 638: }
639: bool file_executable(const String& file_spec) {
1.64 parser 640: return access(file_spec.cstr(String::UL_FILE_SPEC), X_OK)==0;
1.44 paf 641: }
642:
1.64 parser 643: bool file_stat(const String& file_spec,
1.58 parser 644: size_t& rsize,
1.126 paf 645: time_t& ratime,
646: time_t& rmtime,
647: time_t& rctime,
1.64 parser 648: bool fail_on_read_problem) {
1.126 paf 649: Pool& pool=file_spec.pool();
650: const char* fname=file_spec.cstr(String::UL_FILE_SPEC);
1.44 paf 651: struct stat finfo;
652: if(stat(fname, &finfo)!=0)
1.64 parser 653: if(fail_on_read_problem)
1.126 paf 654: throw Exception("file.missing",
1.67 parser 655: &file_spec,
656: "getting file size failed: %s (%d), real filename '%s'",
1.126 paf 657: strerror(errno), errno, fname);
1.64 parser 658: else
659: return false;
1.58 parser 660: rsize=finfo.st_size;
661: ratime=finfo.st_atime;
662: rmtime=finfo.st_mtime;
663: rctime=finfo.st_ctime;
1.64 parser 664: return true;
1.18 paf 665: }
666:
1.126 paf 667: char* getrow(char* *row_ref, char delim) {
668: char* result=*row_ref;
1.8 paf 669: if(result) {
1.126 paf 670: *row_ref=strchr(result, delim);
1.8 paf 671: if(*row_ref)
672: *((*row_ref)++)=0;
673: else if(!*result)
674: return 0;
675: }
676: return result;
677: }
678:
1.126 paf 679: char* lsplit(char* string, char delim) {
1.23 paf 680: if(string) {
1.126 paf 681: char* v=strchr(string, delim);
1.8 paf 682: if(v) {
683: *v=0;
684: return v+1;
685: }
686: }
687: return 0;
688: }
689:
1.126 paf 690: char* lsplit(char* *string_ref, char delim) {
691: char* result=*string_ref;
692: char* next=lsplit(*string_ref, delim);
1.8 paf 693: *string_ref=next;
694: return result;
1.9 paf 695: }
696:
1.126 paf 697: char* rsplit(char* string, char delim) {
1.18 paf 698: if(string) {
1.126 paf 699: char* v=strrchr(string, delim);
1.18 paf 700: if(v) {
1.9 paf 701: *v=0;
702: return v+1;
703: }
704: }
705: return NULL;
1.10 paf 706: }
707:
1.37 paf 708: /// @todo less stupid type detection
1.126 paf 709: char* format(Pool& pool, double value, char* fmt) {
710: char local_buf[MAX_NUMBER];
1.108 paf 711: size_t size;
712:
1.10 paf 713: if(fmt)
714: if(strpbrk(fmt, "diouxX"))
715: if(strpbrk(fmt, "ouxX"))
1.126 paf 716: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.10 paf 717: else
1.126 paf 718: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
1.10 paf 719: else
1.126 paf 720: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
1.10 paf 721: else
1.126 paf 722: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
1.10 paf 723:
1.126 paf 724: char* pool_buf=(char *)pool.malloc(size+1, 4);
725: memcpy(pool_buf, local_buf, size+1);
1.108 paf 726: return pool_buf;
1.12 paf 727: }
728:
1.36 paf 729: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 730: #ifdef WIN32
731: do{
1.126 paf 732: int chunk_written=fwrite(buf, 1, min(8*0x400, size), stdout);
1.12 paf 733: if(chunk_written<=0)
734: break;
735: size-=chunk_written;
1.36 paf 736: buf=((const char*)buf)+chunk_written;
1.126 paf 737: } while(size>0);
1.12 paf 738:
739: return size;
740: #else
1.126 paf 741: return fwrite(buf, 1, size, stdout);
1.12 paf 742: #endif
1.2 paf 743: }
1.14 paf 744:
1.126 paf 745: char* unescape_chars(Pool& pool, const char* cp, int len) {
746: char* s=(char *)pool.malloc(len + 1, 5);
1.14 paf 747: enum EscapeState {
1.33 paf 748: EscapeRest,
749: EscapeFirst,
1.14 paf 750: EscapeSecond
751: } escapeState=EscapeRest;
752: int escapedValue=0;
753: int srcPos=0;
754: int dstPos=0;
755: while(srcPos < len) {
1.126 paf 756: int ch=cp[srcPos];
1.14 paf 757: switch(escapeState) {
758: case EscapeRest:
759: if(ch=='%') {
760: escapeState=EscapeFirst;
761: } else if(ch=='+') {
1.126 paf 762: s[dstPos++]=' ';
1.14 paf 763: } else {
764: s[dstPos++]=ch;
765: }
766: break;
767: case EscapeFirst:
768: escapedValue=hex_value[ch] << 4;
769: escapeState=EscapeSecond;
770: break;
771: case EscapeSecond:
1.126 paf 772: escapedValue +=hex_value[ch];
1.14 paf 773: s[dstPos++]=escapedValue;
774: escapeState=EscapeRest;
775: break;
776: }
1.126 paf 777: srcPos++;
1.14 paf 778: }
779: s[dstPos]=0;
780: return s;
1.24 paf 781: }
782:
783: #ifdef WIN32
1.126 paf 784: void back_slashes_to_slashes(char* s) {
1.24 paf 785: if(s)
786: for(; *s; s++)
787: if(*s=='\\')
1.126 paf 788: *s='/';
1.24 paf 789: }
1.42 paf 790: /*
1.126 paf 791: void slashes_to_back_slashes(char* s) {
1.42 paf 792: if(s)
793: for(; *s; s++)
794: if(*s=='/')
1.126 paf 795: *s='\\';
1.42 paf 796: }
797: */
1.24 paf 798: #endif
1.41 paf 799:
1.126 paf 800: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41 paf 801: while(true) {
802: if(!(*s1)) {
803: if(!(*s2))
804: return true;
805: else
806: return !strict;
807: } else if(!(*s2))
808: return !strict;
809: if(isalpha(*s1)) {
810: if(tolower(*s1) !=tolower(*s2))
811: return false;
812: } else if((*s1) !=(*s2))
813: return false;
1.126 paf 814: s1++;
815: s2++;
1.41 paf 816: }
1.57 parser 817: }
818:
1.84 paf 819: static bool isLeap(int year) {
1.57 parser 820: return !(
821: (year % 4) || ((year % 400) && !(year % 100))
1.126 paf 822: );
1.57 parser 823: }
824:
825: int getMonthDays(int year, int month) {
826: int monthDays[]={
1.126 paf 827: 31,
828: isLeap(year) ? 29 : 28,
829: 31,
830: 30,
831: 31,
832: 30,
833: 31,
834: 31,
835: 30,
836: 31,
837: 30,
1.57 parser 838: 31
1.126 paf 839: };
840: return monthDays[month];
1.41 paf 841: }
1.69 parser 842:
1.126 paf 843: void remove_crlf(char* start, char* end) {
844: for(char* p=start; p<end; p++)
1.69 parser 845: switch(*p) {
1.126 paf 846: case '\n': *p='|'; break;
847: case '\r': *p=' '; break;
1.69 parser 848: }
1.91 paf 849: }
850:
851:
852: /// must be last in this file
853: #undef vsnprintf
1.126 paf 854: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 855: if(!s)
856: return 0;
857:
858: int r;
859: // note: on win32& maybe somewhere else
860: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
861: --s;
862: #if _MSC_VER
863: /*
864: win32:
865: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
866:
867: if the number of bytes to write exceeds buffer, then count bytes are written and –1 is returned
868: */
1.126 paf 869: r=_vsnprintf(b, s, f, l);
1.91 paf 870: if(r<0)
871: r=s;
872: #else
1.126 paf 873: r=vsnprintf(b, s, f, l);
1.91 paf 874: /*
875: solaris:
876: man vsnprintf
877:
878: The snprintf() function returns the number of characters
879: formatted, that is, the number of characters that would have
880: been written to the buffer if it were large enough. If the
881: value of n is 0 on a call to snprintf(), an unspecified
882: value less than 1 is returned.
883: */
884:
885: if(r<0)
886: r=0;
887: else if(r>s)
888: r=s;
889: #endif
890: b[r]=0;
891: return r;
892: }
893:
1.126 paf 894: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 895: va_list l;
1.126 paf 896: va_start(l, f);
897: int r=__vsnprintf(b, s, f, l);
898: va_end(l);
1.91 paf 899: return r;
1.98 paf 900: }
901:
902: int pa_sleep(unsigned long secs, unsigned long usecs) {
1.126 paf 903: for (; usecs >= 1000000; ++secs, usecs -= 1000000);
1.98 paf 904:
905: #ifdef WIN32
1.126 paf 906: Sleep(secs * 1000 + usecs / 1000);
1.98 paf 907: return 0;
908: #else
909: struct timeval t;
910: t.tv_sec = secs;
911: t.tv_usec = usecs;
1.126 paf 912: return (select(0, NULL, NULL, NULL, &t) == -1 ? errno : 0);
1.98 paf 913: #endif
1.74 parser 914: }
E-mail: