Annotation of parser3/src/main/pa_common.C, revision 1.219
1.15 paf 1: /** @file
1.16 paf 2: Parser: commonly functions.
3:
1.205 paf 4: Copyright(c) 2001-2005 ArtLebedev Group (http://www.artlebedev.com)
1.101 paf 5: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.16 paf 6:
1.210 paf 7: * BASE64 part
8: * Authors: Michael Zucchi <notzed@ximian.com>
9: * Jeffrey Stedfast <fejj@ximian.com>
10: *
11: * Copyright 2000-2004 Ximian, Inc. (www.ximian.com)
12: *
13: * This program is free software; you can redistribute it and/or modify
14: * it under the terms of the GNU General Public License as published by
15: * the Free Software Foundation; either version 2 of the License, or
16: * (at your option) any later version.
17: *
18: * This program is distributed in the hope that it will be useful,
19: * but WITHOUT ANY WARRANTY; without even the implied warranty of
20: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21: * GNU General Public License for more details.
22: *
23: * You should have received a copy of the GNU General Public License
24: * along with this program; if not, write to the Free Software
25: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
26: *
27: */
28:
1.219 ! misha 29: static const char * const IDENT_COMMON_C="$Date: 2006/11/13 13:45:17 $";
1.1 paf 30:
31: #include "pa_common.h"
1.4 paf 32: #include "pa_exception.h"
1.154 paf 33: #include "pa_hash.h"
1.14 paf 34: #include "pa_globals.h"
1.154 paf 35: #include "pa_charsets.h"
1.214 paf 36: #include "pa_http.h"
1.98 paf 37:
1.93 paf 38: // some maybe-undefined constants
39:
1.82 paf 40: #ifndef _O_TEXT
41: # define _O_TEXT 0
42: #endif
43: #ifndef _O_BINARY
44: # define _O_BINARY 0
1.47 paf 45: #endif
1.80 paf 46:
1.138 paf 47: #ifdef HAVE_FTRUNCATE
48: # define PA_O_TRUNC 0
49: #else
50: # ifdef _O_TRUNC
51: # define PA_O_TRUNC _O_TRUNC
52: # else
53: # error you must have either ftruncate function or _O_TRUNC bit declared
54: # endif
1.154 paf 55: #endif
1.176 paf 56:
1.154 paf 57: // defines for globals
58:
59: #define FILE_STATUS_NAME "status"
60:
61: // globals
62:
63: const String file_status_name(FILE_STATUS_NAME);
64:
65: // functions
1.127 paf 66:
1.154 paf 67: void fix_line_breaks(char *str, size_t& length) {
1.87 paf 68: //_asm int 3;
1.154 paf 69: const char* const eob=str+length;
70: char* dest=str;
1.72 parser 71: // fix DOS: \r\n -> \n
72: // fix Macintosh: \r -> \n
1.154 paf 73: char* bol=str;
1.137 paf 74: while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72 parser 75: size_t len=eol-bol;
76: if(dest!=bol)
1.126 paf 77: memcpy(dest, bol, len);
1.72 parser 78: dest+=len;
1.126 paf 79: *dest++='\n';
1.72 parser 80:
1.126 paf 81: if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72 parser 82: bol=eol+2;
1.154 paf 83: length--;
1.126 paf 84: } else // \r, not \n = Macintosh
1.72 parser 85: bol=eol+1;
86: }
1.154 paf 87: // last piece without \r
1.72 parser 88: if(dest!=bol)
1.126 paf 89: memcpy(dest, bol, eob-bol);
1.154 paf 90: str[length]=0; // terminating
1.72 parser 91: }
1.18 paf 92:
1.154 paf 93: char* file_read_text(Request_charsets& charsets,
94: const String& file_spec,
95: bool fail_on_read_problem,
96: HashStringValue* params/*, HashStringValue* * out_fields*/) {
97: File_read_result file=
98: file_read(charsets, file_spec, true, params, fail_on_read_problem);
99: return file.success?file.str:0;
1.126 paf 100: }
101:
1.206 paf 102: /// these options were handled but not checked elsewhere, now check them
1.214 paf 103: int pa_get_valid_file_options_count(HashStringValue& options)
1.206 paf 104: {
105: int result=0;
106: if(options.get(PA_SQL_LIMIT_NAME))
107: result++;
108: if(options.get(PA_SQL_OFFSET_NAME))
109: result++;
110: if(options.get(PA_COLUMN_SEPARATOR_NAME))
111: result++;
112: if(options.get(PA_COLUMN_ENCLOSER_NAME))
113: result++;
114: return result;
115: }
116:
1.123 paf 117: #ifndef DOXYGEN
118: struct File_read_action_info {
1.154 paf 119: char **data; size_t *data_size;
1.188 paf 120: char* buf; size_t offset; size_t count;
1.126 paf 121: };
1.123 paf 122: #endif
1.154 paf 123: static void file_read_action(
124: struct stat& finfo,
125: int f,
1.166 paf 126: const String& file_spec, const char* /*fname*/, bool as_text,
1.154 paf 127: void *context) {
1.126 paf 128: File_read_action_info& info=*static_cast<File_read_action_info *>(context);
1.188 paf 129: size_t to_read_size=info.count;
130: if(!to_read_size)
131: to_read_size=(size_t)finfo.st_size;
132: assert( !(info.buf && as_text) );
133: if(to_read_size) {
134: if(info.offset)
135: lseek(f, info.offset, SEEK_SET);
136: *info.data=info.buf
137: ? info.buf
138: : new(PointerFreeGC) char[to_read_size+(as_text?1:0)];
1.126 paf 139: *info.data_size=(size_t)read(f, *info.data, to_read_size);
1.123 paf 140:
141: if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126 paf 142: throw Exception(0,
1.123 paf 143: &file_spec,
1.173 paf 144: "read failed: actually read %u bytes count not in [0..%u] valid range",
1.126 paf 145: *info.data_size, to_read_size);
1.123 paf 146: } else { // empty file
1.209 paf 147: // for both, text and binary: for text we need that terminator, for binary we need nonzero pointer to be able to save such files
148: *info.data=new(PointerFreeGC) char[1];
149: *(char*)(*info.data)=0;
1.123 paf 150: *info.data_size=0;
151: return;
152: }
1.126 paf 153: }
1.154 paf 154: File_read_result file_read(Request_charsets& charsets, const String& file_spec,
155: bool as_text, HashStringValue *params,
1.188 paf 156: bool fail_on_read_problem,
157: char* buf, size_t offset, size_t count) {
1.167 paf 158: File_read_result result={false, 0, 0, 0};
1.154 paf 159: if(file_spec.starts_with("http://")) {
1.203 paf 160: if(offset || count)
161: throw Exception("parser.runtime",
162: 0,
163: "offset and load options are not supported for HTTP:// file load");
164:
1.126 paf 165: // fail on read problem
1.214 paf 166: File_read_http_result http=pa_internal_file_read_http(charsets, file_spec, as_text, params);
1.154 paf 167: result.success=true;
168: result.str=http.str;
169: result.length=http.length;
170: result.headers=http.headers;
1.126 paf 171: } else {
1.206 paf 172: if(params) {
1.214 paf 173: int valid_options=pa_get_valid_file_options_count(*params);
1.206 paf 174: if(valid_options!=params->count())
175: throw Exception("parser.runtime",
176: 0,
177: "invalid option passed");
178: }
1.161 paf 179:
1.188 paf 180: File_read_action_info info={&result.str, &result.length,
181: buf, offset, count};
1.154 paf 182: result.success=file_read_action_under_lock(file_spec,
1.126 paf 183: "read", file_read_action, &info,
184: as_text, fail_on_read_problem);
185: }
1.123 paf 186:
1.154 paf 187: if(result.success && as_text) {
1.131 paf 188: // UTF-8 signature: EF BB BF
1.154 paf 189: if(result.length>=3) {
190: char *in=(char *)result.str;
1.159 paf 191: if(strncmp(in, "\xEF\xBB\xBF", 3)==0) {
1.154 paf 192: result.str=in+3; result.length-=3;// skip prefix
1.131 paf 193: }
194: }
195:
1.154 paf 196: fix_line_breaks((char *)(result.str), result.length);
1.123 paf 197: }
1.126 paf 198:
199: return result;
1.123 paf 200: }
201:
1.154 paf 202: #ifdef PA_SAFE_MODE
203: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) {
204: if(finfo.st_uid/*foreign?*/!=geteuid()
205: && finfo.st_gid/*foreign?*/!=getegid())
206: throw Exception("parser.runtime",
207: &file_spec,
208: "parser is in safe mode: "
209: "reading files of foreign group and user disabled "
210: "[recompile parser with --disable-safe-mode configure option], "
211: "actual filename '%s', "
212: "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",
213: fname,
214: finfo.st_uid, geteuid(),
215: finfo.st_gid, getegid());
216: }
217: #endif
1.149 paf 218:
1.154 paf 219: bool file_read_action_under_lock(const String& file_spec,
1.126 paf 220: const char* action_name, File_read_action action, void *context,
221: bool as_text,
1.123 paf 222: bool fail_on_read_problem) {
1.154 paf 223: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.33 paf 224: int f;
225:
226: // first open, next stat:
1.45 paf 227: // directory update of NTFS hard links performed on open.
1.33 paf 228: // ex:
229: // a.html:^test[] and b.html hardlink to a.html
230: // user inserts ! before ^test in a.html
1.126 paf 231: // directory entry of b.html in NTFS not updated at once,
1.35 paf 232: // they delay update till open, so we would receive "!^test[" string
233: // if would do stat, next open.
1.123 paf 234: // later: it seems, even this does not help sometimes
1.98 paf 235: if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123 paf 236: try {
1.162 paf 237: if(pa_lock_shared_blocking(f)!=0)
1.126 paf 238: throw Exception("file.lock",
1.123 paf 239: &file_spec,
240: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 241: strerror(errno), errno, fname);
1.123 paf 242:
1.124 paf 243: struct stat finfo;
244: if(stat(fname, &finfo)!=0)
245: throw Exception("file.missing", // hardly possible: we just opened it OK
246: &file_spec,
247: "stat failed: %s (%d), actual filename '%s'",
1.154 paf 248: strerror(errno), errno, fname);
1.124 paf 249:
1.140 paf 250: #ifdef PA_SAFE_MODE
1.149 paf 251: check_safe_mode(finfo, file_spec, fname);
1.105 paf 252: #endif
1.32 paf 253:
1.154 paf 254: action(finfo, f, file_spec, fname, as_text, context);
1.123 paf 255: } catch(...) {
1.162 paf 256: pa_unlock(f);close(f);
1.123 paf 257: if(fail_on_read_problem)
1.154 paf 258: rethrow;
1.123 paf 259: return false;
260: }
1.87 paf 261:
1.162 paf 262: pa_unlock(f);close(f);
1.72 parser 263: return true;
1.118 paf 264: } else {
265: if(fail_on_read_problem)
1.126 paf 266: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.118 paf 267: &file_spec,
1.123 paf 268: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 269: action_name, strerror(errno), errno, fname);
1.118 paf 270: return false;
271: }
1.8 paf 272: }
273:
1.202 paf 274: void create_dir_for_file(const String& file_spec) {
1.63 parser 275: size_t pos_after=1;
1.154 paf 276: size_t pos_before;
277: while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
278: mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775);
1.63 parser 279: pos_after=pos_before+1;
280: }
281: }
282:
1.98 paf 283: bool file_write_action_under_lock(
1.28 paf 284: const String& file_spec,
1.126 paf 285: const char* action_name, File_write_action action, void *context,
286: bool as_text,
287: bool do_append,
288: bool do_block,
1.110 paf 289: bool fail_on_lock_problem) {
1.154 paf 290: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.28 paf 291: int f;
1.80 paf 292: if(access(fname, W_OK)!=0) // no
1.126 paf 293: create_dir_for_file(file_spec);
1.50 paf 294:
1.80 paf 295: if((f=open(fname,
296: O_CREAT|O_RDWR
297: |(as_text?_O_TEXT:_O_BINARY)
1.138 paf 298: |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162 paf 299: if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126 paf 300: Exception e("file.lock",
1.110 paf 301: &file_spec,
302: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 303: strerror(errno), errno, fname);
1.126 paf 304: close(f);
1.110 paf 305: if(fail_on_lock_problem)
306: throw e;
1.98 paf 307: return false;
308: }
1.96 paf 309:
1.158 paf 310: try {
1.126 paf 311: action(f, context);
1.158 paf 312: } catch(...) {
1.138 paf 313: #ifdef HAVE_FTRUNCATE
1.104 paf 314: if(!do_append)
1.125 paf 315: ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138 paf 316: #endif
1.162 paf 317: pa_unlock(f);close(f);
1.154 paf 318: rethrow;
1.158 paf 319: }
1.80 paf 320:
1.138 paf 321: #ifdef HAVE_FTRUNCATE
1.104 paf 322: if(!do_append)
1.125 paf 323: 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 324: #endif
1.162 paf 325: pa_unlock(f);close(f);
1.98 paf 326: return true;
1.80 paf 327: } else
1.126 paf 328: throw Exception(errno==EACCES?"file.access":0,
1.80 paf 329: &file_spec,
1.96 paf 330: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 331: action_name, strerror(errno), errno, fname);
1.96 paf 332: // here should be nothing, see rethrow above
333: }
334:
335: #ifndef DOXYGEN
336: struct File_write_action_info {
1.154 paf 337: const char* str; size_t length;
1.126 paf 338: };
1.96 paf 339: #endif
340: static void file_write_action(int f, void *context) {
1.126 paf 341: File_write_action_info& info=*static_cast<File_write_action_info *>(context);
1.154 paf 342: if(info.length) {
343: int written=write(f, info.str, info.length);
1.116 paf 344: if(written<0)
1.126 paf 345: throw Exception(0,
346: 0,
347: "write failed: %s (%d)", strerror(errno), errno);
1.113 paf 348: }
1.96 paf 349: }
350: void file_write(
351: const String& file_spec,
1.154 paf 352: const char* data, size_t size,
1.126 paf 353: bool as_text,
1.96 paf 354: bool do_append) {
1.126 paf 355: File_write_action_info info={data, size};
1.98 paf 356: file_write_action_under_lock(
1.154 paf 357: file_spec,
358: "write", file_write_action, &info,
359: as_text,
360: do_append);
1.30 paf 361: }
362:
1.63 parser 363: // throws nothing! [this is required in file_move & file_delete]
1.50 paf 364: static void rmdir(const String& file_spec, size_t pos_after) {
1.154 paf 365: size_t pos_before;
366: if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126 paf 367: rmdir(file_spec, pos_before+1);
1.50 paf 368:
1.154 paf 369: rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC));
1.50 paf 370: }
1.164 paf 371: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.154 paf 372: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.54 parser 373: if(unlink(fname)!=0)
1.164 paf 374: if(fail_on_problem)
1.126 paf 375: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.93 paf 376: &file_spec,
377: "unlink failed: %s (%d), actual filename '%s'",
1.154 paf 378: strerror(errno), errno, fname);
1.93 paf 379: else
380: return false;
1.50 paf 381:
1.126 paf 382: rmdir(file_spec, 1);
1.93 paf 383: return true;
1.60 parser 384: }
1.95 paf 385: void file_move(const String& old_spec, const String& new_spec) {
1.154 paf 386: const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC);
387: const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC);
1.63 parser 388:
1.126 paf 389: create_dir_for_file(new_spec);
1.63 parser 390:
1.60 parser 391: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 392: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.60 parser 393: &old_spec,
394: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.154 paf 395: strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 396:
1.126 paf 397: rmdir(old_spec, 1);
1.31 paf 398: }
399:
1.51 paf 400:
1.126 paf 401: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 402: struct stat lfinfo;
403: bool result=stat(fname, &lfinfo)==0;
404: if(afinfo)
405: *afinfo=lfinfo;
406: return result;
1.119 paf 407: }
408:
409: bool entry_exists(const String& file_spec) {
1.154 paf 410: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.126 paf 411: return entry_exists(fname, 0);
1.118 paf 412: }
413:
1.51 paf 414: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154 paf 415: char* fname=file_spec.cstrm(String::L_FILE_SPEC);
1.120 paf 416: if(need_dir) {
1.126 paf 417: size_t size=strlen(fname);
1.120 paf 418: while(size) {
1.126 paf 419: char c=fname[size-1];
1.120 paf 420: if(c=='/' || c=='\\')
421: fname[--size]=0;
422: else
423: break;
424: }
425: }
1.51 paf 426: struct stat finfo;
1.118 paf 427: if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109 paf 428: bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51 paf 429: return is_dir==need_dir;
430: }
431: return false;
432: }
1.215 paf 433: bool file_exist(const String& file_spec) {
1.126 paf 434: return entry_readable(file_spec, false);
1.51 paf 435: }
1.215 paf 436: bool dir_exists(const String& file_spec) {
1.126 paf 437: return entry_readable(file_spec, true);
1.65 parser 438: }
1.215 paf 439: const String* file_exist(const String& path, const String& name) {
1.154 paf 440: String& result=*new String(path);
441: result << "/";
442: result << name;
1.215 paf 443: return file_exist(result)?&result:0;
1.43 paf 444: }
445: bool file_executable(const String& file_spec) {
1.154 paf 446: return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44 paf 447: }
448:
1.64 parser 449: bool file_stat(const String& file_spec,
1.58 parser 450: size_t& rsize,
1.126 paf 451: time_t& ratime,
452: time_t& rmtime,
453: time_t& rctime,
1.64 parser 454: bool fail_on_read_problem) {
1.154 paf 455: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
456: struct stat finfo;
1.44 paf 457: if(stat(fname, &finfo)!=0)
1.64 parser 458: if(fail_on_read_problem)
1.126 paf 459: throw Exception("file.missing",
1.67 parser 460: &file_spec,
461: "getting file size failed: %s (%d), real filename '%s'",
1.154 paf 462: strerror(errno), errno, fname);
1.64 parser 463: else
464: return false;
1.58 parser 465: rsize=finfo.st_size;
466: ratime=finfo.st_atime;
467: rmtime=finfo.st_mtime;
468: rctime=finfo.st_ctime;
1.64 parser 469: return true;
1.18 paf 470: }
471:
1.126 paf 472: char* getrow(char* *row_ref, char delim) {
473: char* result=*row_ref;
1.8 paf 474: if(result) {
1.126 paf 475: *row_ref=strchr(result, delim);
1.8 paf 476: if(*row_ref)
477: *((*row_ref)++)=0;
478: else if(!*result)
479: return 0;
480: }
481: return result;
482: }
483:
1.126 paf 484: char* lsplit(char* string, char delim) {
1.23 paf 485: if(string) {
1.126 paf 486: char* v=strchr(string, delim);
1.8 paf 487: if(v) {
488: *v=0;
489: return v+1;
490: }
491: }
492: return 0;
493: }
494:
1.126 paf 495: char* lsplit(char* *string_ref, char delim) {
496: char* result=*string_ref;
497: char* next=lsplit(*string_ref, delim);
1.8 paf 498: *string_ref=next;
499: return result;
1.9 paf 500: }
501:
1.126 paf 502: char* rsplit(char* string, char delim) {
1.18 paf 503: if(string) {
1.126 paf 504: char* v=strrchr(string, delim);
1.18 paf 505: if(v) {
1.9 paf 506: *v=0;
507: return v+1;
508: }
509: }
510: return NULL;
1.10 paf 511: }
512:
1.37 paf 513: /// @todo less stupid type detection
1.154 paf 514: const char* format(double value, char* fmt) {
1.126 paf 515: char local_buf[MAX_NUMBER];
1.108 paf 516: size_t size;
517:
1.10 paf 518: if(fmt)
519: if(strpbrk(fmt, "diouxX"))
520: if(strpbrk(fmt, "ouxX"))
1.126 paf 521: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.10 paf 522: else
1.126 paf 523: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
1.10 paf 524: else
1.126 paf 525: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
1.10 paf 526: else
1.126 paf 527: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
1.10 paf 528:
1.154 paf 529: return pa_strdup(local_buf, size);
1.12 paf 530: }
531:
1.36 paf 532: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 533: #ifdef WIN32
1.187 paf 534: size_t to_write = size;
1.12 paf 535: do{
1.154 paf 536: int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 537: if(chunk_written<=0)
538: break;
539: size-=chunk_written;
1.36 paf 540: buf=((const char*)buf)+chunk_written;
1.126 paf 541: } while(size>0);
1.12 paf 542:
1.187 paf 543: return to_write-size;
1.12 paf 544: #else
1.126 paf 545: return fwrite(buf, 1, size, stdout);
1.12 paf 546: #endif
1.2 paf 547: }
1.14 paf 548:
1.154 paf 549: char* unescape_chars(const char* cp, int len) {
550: char* s=new(PointerFreeGC) char[len + 1];
1.14 paf 551: enum EscapeState {
1.33 paf 552: EscapeRest,
553: EscapeFirst,
1.14 paf 554: EscapeSecond
555: } escapeState=EscapeRest;
1.216 paf 556: uint escapedValue=0;
1.14 paf 557: int srcPos=0;
558: int dstPos=0;
559: while(srcPos < len) {
1.193 paf 560: uchar ch=(uchar)cp[srcPos];
1.14 paf 561: switch(escapeState) {
562: case EscapeRest:
563: if(ch=='%') {
564: escapeState=EscapeFirst;
565: } else if(ch=='+') {
1.126 paf 566: s[dstPos++]=' ';
1.14 paf 567: } else {
568: s[dstPos++]=ch;
569: }
570: break;
571: case EscapeFirst:
1.216 paf 572: escapedValue=hex_value[ch] << 4;
1.14 paf 573: escapeState=EscapeSecond;
574: break;
575: case EscapeSecond:
1.126 paf 576: escapedValue +=hex_value[ch];
1.216 paf 577: s[dstPos++]=(char)escapedValue;
1.14 paf 578: escapeState=EscapeRest;
579: break;
580: }
1.126 paf 581: srcPos++;
1.14 paf 582: }
583: s[dstPos]=0;
584: return s;
1.24 paf 585: }
586:
587: #ifdef WIN32
1.126 paf 588: void back_slashes_to_slashes(char* s) {
1.24 paf 589: if(s)
590: for(; *s; s++)
591: if(*s=='\\')
1.126 paf 592: *s='/';
1.24 paf 593: }
1.42 paf 594: /*
1.126 paf 595: void slashes_to_back_slashes(char* s) {
1.42 paf 596: if(s)
597: for(; *s; s++)
598: if(*s=='/')
1.126 paf 599: *s='\\';
1.42 paf 600: }
601: */
1.24 paf 602: #endif
1.41 paf 603:
1.126 paf 604: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41 paf 605: while(true) {
606: if(!(*s1)) {
607: if(!(*s2))
608: return true;
609: else
610: return !strict;
611: } else if(!(*s2))
612: return !strict;
1.189 paf 613: if(isalpha((unsigned char)*s1)) {
1.190 paf 614: if(tolower((unsigned char)*s1) !=tolower((unsigned char)*s2))
1.41 paf 615: return false;
616: } else if((*s1) !=(*s2))
617: return false;
1.126 paf 618: s1++;
619: s2++;
1.41 paf 620: }
1.57 parser 621: }
622:
1.84 paf 623: static bool isLeap(int year) {
1.57 parser 624: return !(
625: (year % 4) || ((year % 400) && !(year % 100))
1.126 paf 626: );
1.57 parser 627: }
628:
629: int getMonthDays(int year, int month) {
630: int monthDays[]={
1.126 paf 631: 31,
632: isLeap(year) ? 29 : 28,
633: 31,
634: 30,
635: 31,
636: 30,
637: 31,
638: 31,
639: 30,
640: 31,
641: 30,
1.57 parser 642: 31
1.126 paf 643: };
644: return monthDays[month];
1.41 paf 645: }
1.69 parser 646:
1.126 paf 647: void remove_crlf(char* start, char* end) {
648: for(char* p=start; p<end; p++)
1.69 parser 649: switch(*p) {
1.126 paf 650: case '\n': *p='|'; break;
651: case '\r': *p=' '; break;
1.69 parser 652: }
1.91 paf 653: }
654:
655:
656: /// must be last in this file
657: #undef vsnprintf
1.126 paf 658: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 659: if(!s)
660: return 0;
661:
662: int r;
663: // note: on win32& maybe somewhere else
664: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
665: --s;
1.172 paf 666:
667: // clients do not check for negative 's', feature: ignore such prints
668: if((ssize_t)s<0)
669: return 0;
670:
1.91 paf 671: #if _MSC_VER
672: /*
673: win32:
674: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
675:
1.154 paf 676: if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91 paf 677: */
1.126 paf 678: r=_vsnprintf(b, s, f, l);
1.91 paf 679: if(r<0)
680: r=s;
681: #else
1.126 paf 682: r=vsnprintf(b, s, f, l);
1.91 paf 683: /*
684: solaris:
685: man vsnprintf
686:
687: The snprintf() function returns the number of characters
688: formatted, that is, the number of characters that would have
689: been written to the buffer if it were large enough. If the
690: value of n is 0 on a call to snprintf(), an unspecified
691: value less than 1 is returned.
692: */
693:
694: if(r<0)
695: r=0;
1.167 paf 696: else if((size_t)r>s)
1.91 paf 697: r=s;
698: #endif
699: b[r]=0;
700: return r;
701: }
702:
1.126 paf 703: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 704: va_list l;
1.126 paf 705: va_start(l, f);
706: int r=__vsnprintf(b, s, f, l);
707: va_end(l);
1.91 paf 708: return r;
1.178 paf 709: }
710:
711: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
712: /*
713: * Authors: Michael Zucchi <notzed@helixcode.com>
714: * Jeffrey Stedfast <fejj@helixcode.com>
715: *
716: * Copyright 2000 Helix Code, Inc. (www.helixcode.com)
717: *
718: * This program is free software; you can redistribute it and/or modify
719: * it under the terms of the GNU General Public License as published by
720: * the Free Software Foundation; either version 2 of the License, or
721: * (at your option) any later version.
722: *
723: * This program is distributed in the hope that it will be useful,
724: * but WITHOUT ANY WARRANTY; without even the implied warranty of
725: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
726: * GNU General Public License for more details.
727: *
728: * You should have received a copy of the GNU General Public License
729: * along with this program; if not, write to the Free Software
730: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
731: *
732: */
733: static char *base64_alphabet =
734: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
735:
736: /**
737: * g_mime_utils_base64_encode_step:
738: * @in: input stream
739: * @inlen: length of the input
740: * @out: output string
741: * @state: holds the number of bits that are stored in @save
742: * @save: leftover bits that have not yet been encoded
743: *
744: * Base64 encodes a chunk of data. Performs an 'encode step', only
745: * encodes blocks of 3 characters to the output at a time, saves
746: * left-over state in state and save (initialise to 0 on first
747: * invocation).
748: *
749: * Returns the number of bytes encoded.
750: **/
751: static size_t
752: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
753: {
1.186 paf 754: register const unsigned char *inptr;
1.178 paf 755: register unsigned char *outptr;
756:
757: if (inlen <= 0)
758: return 0;
759:
760: inptr = in;
761: outptr = out;
762:
763: if (inlen + ((unsigned char *)save)[0] > 2) {
764: const unsigned char *inend = in + inlen - 2;
765: register int c1 = 0, c2 = 0, c3 = 0;
766: register int already;
767:
768: already = *state;
769:
770: switch (((char *)save)[0]) {
771: case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
772: case 2: c1 = ((unsigned char *)save)[1];
773: c2 = ((unsigned char *)save)[2]; goto skip2;
774: }
775:
776: /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
777: while (inptr < inend) {
778: c1 = *inptr++;
779: skip1:
780: c2 = *inptr++;
781: skip2:
782: c3 = *inptr++;
783: *outptr++ = base64_alphabet [c1 >> 2];
784: *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
785: *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
786: *outptr++ = base64_alphabet [c3 & 0x3f];
787: /* this is a bit ugly ... */
788: if ((++already) >= 19) {
789: *outptr++ = '\n';
790: already = 0;
791: }
792: }
793:
794: ((unsigned char *)save)[0] = 0;
795: inlen = 2 - (inptr - inend);
796: *state = already;
797: }
798:
799: //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
800:
801: if (inlen > 0) {
802: register char *saveout;
803:
804: /* points to the slot for the next char to save */
805: saveout = & (((char *)save)[1]) + ((char *)save)[0];
806:
807: /* inlen can only be 0 1 or 2 */
808: switch (inlen) {
809: case 2: *saveout++ = *inptr++;
810: case 1: *saveout++ = *inptr++;
811: }
1.216 paf 812: *(char *)save = *(char *)save+(char)inlen;
1.178 paf 813: }
814:
815: /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
816: (int)((char *)save)[0],
817: (int)((char *)save)[1],
818: (int)((char *)save)[2]));*/
819:
820: return (outptr - out);
821: }
822:
823: /**
824: * g_mime_utils_base64_encode_close:
825: * @in: input stream
826: * @inlen: length of the input
827: * @out: output string
828: * @state: holds the number of bits that are stored in @save
829: * @save: leftover bits that have not yet been encoded
830: *
831: * Base64 encodes the input stream to the output stream. Call this
832: * when finished encoding data with g_mime_utils_base64_encode_step to
833: * flush off the last little bit.
834: *
835: * Returns the number of bytes encoded.
836: **/
837: static size_t
838: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
839: {
840: unsigned char *outptr = out;
841: int c1, c2;
842:
843: if (inlen > 0)
844: outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
845:
846: c1 = ((unsigned char *)save)[1];
847: c2 = ((unsigned char *)save)[2];
848:
849: switch (((unsigned char *)save)[0]) {
850: case 2:
851: outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
852: goto skip;
853: case 1:
854: outptr[2] = '=';
855: skip:
856: outptr[0] = base64_alphabet [c1 >> 2];
857: outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
858: outptr[3] = '=';
859: outptr += 4;
860: break;
861: }
862:
863: *outptr++ = 0;
864:
865: *save = 0;
866: *state = 0;
867:
868: return (outptr - out);
869: }
870:
1.210 paf 871: static unsigned char gmime_base64_rank[256] = {
872: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
873: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
874: 255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
875: 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255, 0,255,255,
876: 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
877: 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
878: 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
879: 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
880: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
881: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
882: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
883: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
884: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
885: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
886: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
887: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
888: };
889:
890: /**
891: * g_mime_utils_base64_decode_step:
892: * @in: input stream
893: * @inlen: max length of data to decode
894: * @out: output stream
895: * @state: holds the number of bits that are stored in @save
896: * @save: leftover bits that have not yet been decoded
897: *
898: * Decodes a chunk of base64 encoded data.
899: *
900: * Returns the number of bytes decoded (which have been dumped in @out).
901: **/
902: size_t
903: g_mime_utils_base64_decode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
904: {
1.213 paf 905: const unsigned char *inptr;
906: unsigned char *outptr;
1.210 paf 907: const unsigned char *inend;
1.213 paf 908: int saved;
1.210 paf 909: unsigned char c;
910: int i;
911:
912: inend = in + inlen;
913: outptr = out;
914:
915: /* convert 4 base64 bytes to 3 normal bytes */
916: saved = *save;
917: i = *state;
918: inptr = in;
919: while (inptr < inend) {
920: c = gmime_base64_rank[*inptr++];
921: if (c != 0xff) {
922: saved = (saved << 6) | c;
923: i++;
924: if (i == 4) {
1.217 paf 925: *outptr++ = (unsigned char)(saved >> 16);
926: *outptr++ = (unsigned char)(saved >> 8);
927: *outptr++ = (unsigned char)(saved);
1.210 paf 928: i = 0;
929: }
930: }
931: }
932:
933: *save = saved;
934: *state = i;
935:
936: /* quick scan back for '=' on the end somewhere */
937: /* fortunately we can drop 1 output char for each trailing = (upto 2) */
938: i = 2;
939: while (inptr > in && i) {
940: inptr--;
941: if (gmime_base64_rank[*inptr] != 0xff) {
942: if (*inptr == '=' && outptr > out)
943: outptr--;
944: i--;
945: }
946: }
947:
948: /* if i != 0 then there is a truncation error! */
949: return (outptr - out);
950: }
951:
952:
953: char* pa_base64_encode(const char *in, size_t in_size)
1.178 paf 954: {
955: /* wont go to more than 2x size (overly conservative) */
1.210 paf 956: char* result=new(PointerFreeGC) char[in_size * 2 + 6];
1.178 paf 957: int state=0;
958: int save=0;
1.183 paf 959: #ifndef NDEBUG
960: size_t filled=
961: #endif
1.210 paf 962: g_mime_utils_base64_encode_close ((const unsigned char*)in, in_size,
1.178 paf 963: (unsigned char*)result, &state, &save);
1.210 paf 964: assert(filled <= in_size * 2 + 6);
1.178 paf 965:
966: return result;
1.98 paf 967: }
1.210 paf 968:
1.211 paf 969: void pa_base64_decode(const char *in, size_t in_size, char*& result, size_t& result_size)
1.210 paf 970: {
971: /* wont go to more than had (overly conservative) */
1.211 paf 972: result=new(PointerFreeGC) char[in_size+1/*terminator*/];
1.210 paf 973: int state=0;
974: int save=0;
975: result_size=
976: g_mime_utils_base64_decode_step ((const unsigned char*)in, in_size,
977: (unsigned char*)result, &state, &save);
978: assert(result_size <= in_size);
1.211 paf 979: result[result_size]=0; // for text files
1.210 paf 980: }
1.218 misha 981:
982:
983: const unsigned long pa_crc32(const char *in, size_t in_size)
984: {
985: unsigned long crc32=0xFFFFFFFF;
986: if(in_size){
987: InitCrc32Table();
988: for(size_t i = 0; i < in_size; i++) CalcCrc32(in[i], crc32);
989: }
990: return ~crc32;
991: }
992:
993: const unsigned long pa_crc32(const String& file_spec)
994: {
995: unsigned long crc32=0xFFFFFFFF;
996: file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
997: return ~crc32;
998: }
999:
1000: static void file_crc32_file_action(
1001: struct stat& finfo,
1002: int f,
1.219 ! misha 1003: const String&, const char* /*fname*/, bool,
1.218 misha 1004: void *context)
1005: {
1006: unsigned long& crc32=*static_cast<unsigned long *>(context);
1007: if(finfo.st_size) {
1008: InitCrc32Table();
1009: size_t nCount=0;
1010: do {
1.219 ! misha 1011: char buffer[FILE_BUFFER_SIZE];
1.218 misha 1012: nCount = read(f, buffer, sizeof(buffer));
1013: for(size_t i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
1014: } while(nCount);
1015: }
1016: }
1017:
1018:
E-mail: