Annotation of parser3/src/main/pa_common.C, revision 1.261
1.15 paf 1: /** @file
1.16 paf 2: Parser: commonly functions.
3:
1.242 misha 4: Copyright(c) 2001-2009 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.261 ! misha 29: static const char * const IDENT_COMMON_C="$Date: 2010-06-03 02:03:21 $";
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.223 misha 37: #include "pa_request_charsets.h"
1.237 misha 38: #include "pcre.h"
1.241 misha 39: #include "pa_request.h"
1.98 paf 40:
1.93 paf 41: // some maybe-undefined constants
42:
1.82 paf 43: #ifndef _O_TEXT
44: # define _O_TEXT 0
45: #endif
46: #ifndef _O_BINARY
47: # define _O_BINARY 0
1.47 paf 48: #endif
1.80 paf 49:
1.138 paf 50: #ifdef HAVE_FTRUNCATE
51: # define PA_O_TRUNC 0
52: #else
53: # ifdef _O_TRUNC
54: # define PA_O_TRUNC _O_TRUNC
55: # else
56: # error you must have either ftruncate function or _O_TRUNC bit declared
57: # endif
1.154 paf 58: #endif
1.176 paf 59:
1.154 paf 60: // defines for globals
61:
62: #define FILE_STATUS_NAME "status"
63:
64: // globals
65:
66: const String file_status_name(FILE_STATUS_NAME);
67:
68: // functions
1.127 paf 69:
1.255 misha 70: bool capitalized(const char* s){
71: bool upper=true;
72: for(const char* c=s; *c; c++){
73: if(*c != (upper ? toupper((unsigned char)*c) : tolower((unsigned char)*c)))
74: return false;
75: upper=strchr("-_ ", *c) != 0;
76: }
77: return true;
78: }
79:
1.249 misha 80: const char* capitalize(const char* s){
1.255 misha 81: if(!s || capitalized(s))
82: return s;
83:
1.249 misha 84: char* result=pa_strdup(s);
85: if(result){
86: bool upper=true;
87: for(char* c=result; *c; c++){
88: *c=upper ? (char)toupper((unsigned char)*c) : (char)tolower((unsigned char)*c);
89: upper=strchr("-_ ", *c) != 0;
90: }
91: }
92: return (const char*)result;
93: }
94:
1.154 paf 95: void fix_line_breaks(char *str, size_t& length) {
1.87 paf 96: //_asm int 3;
1.154 paf 97: const char* const eob=str+length;
98: char* dest=str;
1.72 parser 99: // fix DOS: \r\n -> \n
100: // fix Macintosh: \r -> \n
1.154 paf 101: char* bol=str;
1.137 paf 102: while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72 parser 103: size_t len=eol-bol;
104: if(dest!=bol)
1.260 misha 105: memmove(dest, bol, len);
1.72 parser 106: dest+=len;
1.126 paf 107: *dest++='\n';
1.72 parser 108:
1.126 paf 109: if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72 parser 110: bol=eol+2;
1.154 paf 111: length--;
1.126 paf 112: } else // \r, not \n = Macintosh
1.72 parser 113: bol=eol+1;
114: }
1.154 paf 115: // last piece without \r
1.72 parser 116: if(dest!=bol)
1.260 misha 117: memmove(dest, bol, eob-bol);
1.154 paf 118: str[length]=0; // terminating
1.72 parser 119: }
1.18 paf 120:
1.154 paf 121: char* file_read_text(Request_charsets& charsets,
1.229 misha 122: const String& file_spec,
123: bool fail_on_read_problem,
1.234 misha 124: HashStringValue* params,
125: bool transcode_result) {
1.154 paf 126: File_read_result file=
1.234 misha 127: file_read(charsets, file_spec, true, params, fail_on_read_problem, 0, 0, 0, transcode_result);
1.154 paf 128: return file.success?file.str:0;
1.126 paf 129: }
130:
1.241 misha 131: char* file_load_text(Request& r,
132: const String& file_spec,
133: bool fail_on_read_problem,
134: HashStringValue* params,
135: bool transcode_result) {
136: File_read_result file=
137: file_load(r, file_spec, true, params, fail_on_read_problem, 0, 0, 0, transcode_result);
138: return file.success?file.str:0;
139: }
140:
1.206 paf 141: /// these options were handled but not checked elsewhere, now check them
1.239 misha 142: int pa_get_valid_file_options_count(HashStringValue& options) {
1.206 paf 143: int result=0;
144: if(options.get(PA_SQL_LIMIT_NAME))
145: result++;
146: if(options.get(PA_SQL_OFFSET_NAME))
147: result++;
148: if(options.get(PA_COLUMN_SEPARATOR_NAME))
149: result++;
150: if(options.get(PA_COLUMN_ENCLOSER_NAME))
151: result++;
1.223 misha 152: if(options.get(PA_CHARSET_NAME))
153: result++;
1.206 paf 154: return result;
155: }
156:
1.123 paf 157: #ifndef DOXYGEN
158: struct File_read_action_info {
1.154 paf 159: char **data; size_t *data_size;
1.188 paf 160: char* buf; size_t offset; size_t count;
1.126 paf 161: };
1.123 paf 162: #endif
1.154 paf 163: static void file_read_action(
1.229 misha 164: struct stat& finfo,
165: int f,
166: const String& file_spec, const char* /*fname*/, bool as_text,
167: void *context) {
1.126 paf 168: File_read_action_info& info=*static_cast<File_read_action_info *>(context);
1.188 paf 169: size_t to_read_size=info.count;
170: if(!to_read_size)
171: to_read_size=(size_t)finfo.st_size;
172: assert( !(info.buf && as_text) );
173: if(to_read_size) {
174: if(info.offset)
175: lseek(f, info.offset, SEEK_SET);
176: *info.data=info.buf
177: ? info.buf
1.253 misha 178: : (char *)pa_malloc_atomic(to_read_size+1);
1.126 paf 179: *info.data_size=(size_t)read(f, *info.data, to_read_size);
1.123 paf 180:
181: if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.238 misha 182: throw Exception("file.read",
1.123 paf 183: &file_spec,
1.173 paf 184: "read failed: actually read %u bytes count not in [0..%u] valid range",
1.126 paf 185: *info.data_size, to_read_size);
1.123 paf 186: } else { // empty file
1.209 paf 187: // for both, text and binary: for text we need that terminator, for binary we need nonzero pointer to be able to save such files
1.253 misha 188: *info.data=(char *)pa_malloc_atomic(1);
1.209 paf 189: *(char*)(*info.data)=0;
1.123 paf 190: *info.data_size=0;
191: return;
192: }
1.126 paf 193: }
1.241 misha 194:
1.154 paf 195: File_read_result file_read(Request_charsets& charsets, const String& file_spec,
1.229 misha 196: bool as_text, HashStringValue *params,
197: bool fail_on_read_problem,
1.234 misha 198: char* buf, size_t offset, size_t count, bool transcode_text_result) {
1.167 paf 199: File_read_result result={false, 0, 0, 0};
1.241 misha 200: if(params){
201: int valid_options=pa_get_valid_file_options_count(*params);
202: if(valid_options!=params->count())
1.224 misha 203: throw Exception(PARSER_RUNTIME,
1.203 paf 204: 0,
1.250 misha 205: INVALID_OPTION_PASSED);
1.241 misha 206: }
1.203 paf 207:
1.241 misha 208: File_read_action_info info={&result.str, &result.length, buf, offset, count};
1.161 paf 209:
1.241 misha 210: result.success=file_read_action_under_lock(file_spec,
211: "read", file_read_action, &info,
212: as_text, fail_on_read_problem);
1.223 misha 213:
1.241 misha 214: if(as_text){
215: if(result.success){
1.236 misha 216: if(result.length>=3 && strncmp(result.str, "\xEF\xBB\xBF", 3)==0){
1.240 misha 217: // skip UTF-8 signature (BOM code)
1.236 misha 218: result.str+=3;
219: result.length-=3;
220: }
221:
222: if(result.length && transcode_text_result && params){ // must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
1.240 misha 223: if(Value* vcharset_name=params->get(PA_CHARSET_NAME)){
1.236 misha 224: Charset asked_charset=::charsets.get(vcharset_name->as_string().
225: change_case(charsets.source(), String::CC_UPPER));
226:
227: String::C body=String::C(result.str, result.length);
228: body=Charset::transcode(body, asked_charset, charsets.source());
1.123 paf 229:
1.236 misha 230: result.str=const_cast<char*>(body.str); // hacking a little
231: result.length=body.length;
232: }
1.131 paf 233: }
234: }
1.241 misha 235: if(result.length)
236: fix_line_breaks(result.str, result.length);
1.123 paf 237: }
1.241 misha 238:
239: return result;
240: }
241:
242: File_read_result file_load(Request& r, const String& file_spec,
243: bool as_text, HashStringValue *params,
244: bool fail_on_read_problem,
245: char* buf, size_t offset, size_t count, bool transcode_text_result) {
246:
247: File_read_result result={false, 0, 0, 0};
248: if(file_spec.starts_with("http://")) {
249: if(offset || count)
250: throw Exception(PARSER_RUNTIME,
251: 0,
252: "offset and load options are not supported for HTTP:// file load");
253:
254: // fail on read problem
255: File_read_http_result http=pa_internal_file_read_http(r, file_spec, as_text, params, transcode_text_result);
256: result.success=true;
257: result.str=http.str;
258: result.length=http.length;
259: result.headers=http.headers;
260: } else
261: result=
262: file_read(r.charsets, file_spec, as_text, params, fail_on_read_problem, buf, offset, count, transcode_text_result);
1.126 paf 263:
264: return result;
1.123 paf 265: }
266:
1.257 pretende 267:
1.154 paf 268: #ifdef PA_SAFE_MODE
1.259 misha 269: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) {
1.154 paf 270: if(finfo.st_uid/*foreign?*/!=geteuid()
271: && finfo.st_gid/*foreign?*/!=getegid())
1.224 misha 272: throw Exception(PARSER_RUNTIME,
1.154 paf 273: &file_spec,
274: "parser is in safe mode: "
275: "reading files of foreign group and user disabled "
276: "[recompile parser with --disable-safe-mode configure option], "
277: "actual filename '%s', "
278: "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",
279: fname,
280: finfo.st_uid, geteuid(),
1.259 misha 281: finfo.st_gid, getegid());
282: }
283: #else
284: void check_safe_mode(struct stat, const String&, const char*) {
285: }
1.257 pretende 286: #endif
1.259 misha 287:
1.257 pretende 288:
1.149 paf 289:
1.154 paf 290: bool file_read_action_under_lock(const String& file_spec,
1.126 paf 291: const char* action_name, File_read_action action, void *context,
292: bool as_text,
1.123 paf 293: bool fail_on_read_problem) {
1.247 misha 294: const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.33 paf 295: int f;
296:
297: // first open, next stat:
1.45 paf 298: // directory update of NTFS hard links performed on open.
1.33 paf 299: // ex:
300: // a.html:^test[] and b.html hardlink to a.html
301: // user inserts ! before ^test in a.html
1.126 paf 302: // directory entry of b.html in NTFS not updated at once,
1.35 paf 303: // they delay update till open, so we would receive "!^test[" string
304: // if would do stat, next open.
1.123 paf 305: // later: it seems, even this does not help sometimes
1.229 misha 306: if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123 paf 307: try {
1.162 paf 308: if(pa_lock_shared_blocking(f)!=0)
1.126 paf 309: throw Exception("file.lock",
1.123 paf 310: &file_spec,
311: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 312: strerror(errno), errno, fname);
1.123 paf 313:
1.124 paf 314: struct stat finfo;
1.254 misha 315: if(fstat(f, &finfo)!=0)
1.124 paf 316: throw Exception("file.missing", // hardly possible: we just opened it OK
317: &file_spec,
318: "stat failed: %s (%d), actual filename '%s'",
1.154 paf 319: strerror(errno), errno, fname);
1.124 paf 320:
1.149 paf 321: check_safe_mode(finfo, file_spec, fname);
1.32 paf 322:
1.154 paf 323: action(finfo, f, file_spec, fname, as_text, context);
1.123 paf 324: } catch(...) {
1.162 paf 325: pa_unlock(f);close(f);
1.123 paf 326: if(fail_on_read_problem)
1.154 paf 327: rethrow;
1.123 paf 328: return false;
329: }
1.87 paf 330:
1.162 paf 331: pa_unlock(f);close(f);
1.72 parser 332: return true;
1.229 misha 333: } else {
1.118 paf 334: if(fail_on_read_problem)
1.256 misha 335: throw Exception(errno==EACCES?"file.access"
336: :(errno==ENOENT || errno==ENOTDIR || errno==ENODEV)?"file.missing":0,
1.118 paf 337: &file_spec,
1.123 paf 338: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 339: action_name, strerror(errno), errno, fname);
1.118 paf 340: return false;
341: }
1.8 paf 342: }
343:
1.202 paf 344: void create_dir_for_file(const String& file_spec) {
1.63 parser 345: size_t pos_after=1;
1.154 paf 346: size_t pos_before;
347: while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
1.247 misha 348: mkdir(file_spec.mid(0, pos_before).taint_cstr(String::L_FILE_SPEC), 0775);
1.63 parser 349: pos_after=pos_before+1;
350: }
351: }
352:
1.98 paf 353: bool file_write_action_under_lock(
1.28 paf 354: const String& file_spec,
1.225 misha 355: const char* action_name,
356: File_write_action action,
357: void *context,
1.126 paf 358: bool as_text,
359: bool do_append,
360: bool do_block,
1.110 paf 361: bool fail_on_lock_problem) {
1.247 misha 362: const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.28 paf 363: int f;
1.80 paf 364: if(access(fname, W_OK)!=0) // no
1.126 paf 365: create_dir_for_file(file_spec);
1.50 paf 366:
1.80 paf 367: if((f=open(fname,
368: O_CREAT|O_RDWR
369: |(as_text?_O_TEXT:_O_BINARY)
1.138 paf 370: |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162 paf 371: if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126 paf 372: Exception e("file.lock",
1.110 paf 373: &file_spec,
374: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 375: strerror(errno), errno, fname);
1.126 paf 376: close(f);
1.110 paf 377: if(fail_on_lock_problem)
378: throw e;
1.98 paf 379: return false;
380: }
1.96 paf 381:
1.158 paf 382: try {
1.254 misha 383: #if (defined(HAVE_FCHMOD) && defined(PA_SAFE_MODE))
384: struct stat finfo;
385: if(fstat(f, &finfo)==0 && finfo.st_mode & 0111)
386: fchmod(f, finfo.st_mode & 0666/*clear executable bits*/); // backward: ignore errors if any
387: #endif
388: action(f, context);
1.158 paf 389: } catch(...) {
1.138 paf 390: #ifdef HAVE_FTRUNCATE
1.104 paf 391: if(!do_append)
1.125 paf 392: ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138 paf 393: #endif
1.162 paf 394: pa_unlock(f);close(f);
1.154 paf 395: rethrow;
1.158 paf 396: }
1.80 paf 397:
1.138 paf 398: #ifdef HAVE_FTRUNCATE
1.104 paf 399: if(!do_append)
1.125 paf 400: 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 401: #endif
1.162 paf 402: pa_unlock(f);close(f);
1.98 paf 403: return true;
1.80 paf 404: } else
1.126 paf 405: throw Exception(errno==EACCES?"file.access":0,
1.80 paf 406: &file_spec,
1.96 paf 407: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 408: action_name, strerror(errno), errno, fname);
1.96 paf 409: // here should be nothing, see rethrow above
410: }
411:
412: #ifndef DOXYGEN
413: struct File_write_action_info {
1.250 misha 414: const char* str;
415: size_t length;
1.126 paf 416: };
1.96 paf 417: #endif
418: static void file_write_action(int f, void *context) {
1.126 paf 419: File_write_action_info& info=*static_cast<File_write_action_info *>(context);
1.154 paf 420: if(info.length) {
421: int written=write(f, info.str, info.length);
1.116 paf 422: if(written<0)
1.238 misha 423: throw Exception("file.access",
1.126 paf 424: 0,
425: "write failed: %s (%d)", strerror(errno), errno);
1.113 paf 426: }
1.96 paf 427: }
428: void file_write(
1.250 misha 429: Request_charsets& charsets,
430: const String& file_spec,
431: const char* data,
432: size_t size,
1.126 paf 433: bool as_text,
1.250 misha 434: bool do_append,
435: Charset* asked_charset) {
436:
437: if(as_text && asked_charset){
438: String::C body=String::C(data, size);
439: body=Charset::transcode(body, charsets.source(), *asked_charset);
440: data=body.str;
441: size=body.length;
442: };
443:
1.126 paf 444: File_write_action_info info={data, size};
1.225 misha 445:
1.98 paf 446: file_write_action_under_lock(
1.154 paf 447: file_spec,
1.225 misha 448: "write",
449: file_write_action,
450: &info,
1.154 paf 451: as_text,
452: do_append);
1.30 paf 453: }
454:
1.261 ! misha 455: static size_t get_dir(char* fname, size_t helper_length){
! 456: bool dir=false;
! 457: size_t pos=0;
! 458: for(pos=helper_length; pos; pos--){
! 459: char c=fname[pos-1];
! 460: if(c=='/' || c=='\\'){
! 461: fname[pos-1]=0;
! 462: dir=true;
! 463: } else if(dir) break;
! 464: }
! 465: return pos;
! 466: }
! 467:
! 468: static bool entry_readable(char* fname, bool need_dir) {
! 469: if(need_dir){
! 470: size_t size=strlen(fname);
! 471: while(size) {
! 472: char c=fname[size-1];
! 473: if(c=='/' || c=='\\')
! 474: fname[--size]=0;
! 475: else
! 476: break;
! 477: }
! 478: }
! 479:
! 480: struct stat finfo;
! 481: if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
! 482: bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
! 483: return is_dir==need_dir;
! 484: }
! 485: return false;
! 486: }
! 487:
! 488: static bool entry_readable(const String& file_spec, bool need_dir) {
! 489: return entry_readable(file_spec.taint_cstrm(String::L_FILE_SPEC), need_dir);
! 490: }
! 491:
1.63 parser 492: // throws nothing! [this is required in file_move & file_delete]
1.261 ! misha 493: static void rmdir(const String& file_spec, size_t pos_after=0) {
! 494: char* dir_spec=file_spec.taint_cstrm(String::L_FILE_SPEC);
! 495: size_t length=strlen(dir_spec);
! 496: while( (length=get_dir(dir_spec, length)) && (length > pos_after) ){
! 497: #ifdef WIN32
! 498: if(!entry_readable(dir_spec, true))
! 499: break;
! 500: DWORD attrs=GetFileAttributes(dir_spec);
! 501: if(
! 502: (attrs==INVALID_FILE_ATTRIBUTES)
! 503: || !(attrs & FILE_ATTRIBUTE_DIRECTORY)
! 504: || (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
! 505: )
! 506: break;
! 507: #endif
! 508: if( rmdir(dir_spec) )
! 509: break;
! 510: };
1.50 paf 511: }
1.239 misha 512:
1.164 paf 513: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.247 misha 514: const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.54 parser 515: if(unlink(fname)!=0)
1.164 paf 516: if(fail_on_problem)
1.126 paf 517: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.93 paf 518: &file_spec,
519: "unlink failed: %s (%d), actual filename '%s'",
1.154 paf 520: strerror(errno), errno, fname);
1.93 paf 521: else
522: return false;
1.50 paf 523:
1.126 paf 524: rmdir(file_spec, 1);
1.93 paf 525: return true;
1.60 parser 526: }
1.239 misha 527:
1.95 paf 528: void file_move(const String& old_spec, const String& new_spec) {
1.247 misha 529: const char* old_spec_cstr=old_spec.taint_cstr(String::L_FILE_SPEC);
530: const char* new_spec_cstr=new_spec.taint_cstr(String::L_FILE_SPEC);
1.63 parser 531:
1.126 paf 532: create_dir_for_file(new_spec);
1.63 parser 533:
1.60 parser 534: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 535: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.60 parser 536: &old_spec,
537: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.154 paf 538: strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 539:
1.126 paf 540: rmdir(old_spec, 1);
1.31 paf 541: }
542:
1.51 paf 543:
1.126 paf 544: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 545: struct stat lfinfo;
546: bool result=stat(fname, &lfinfo)==0;
547: if(afinfo)
548: *afinfo=lfinfo;
549: return result;
1.119 paf 550: }
551:
552: bool entry_exists(const String& file_spec) {
1.247 misha 553: const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.126 paf 554: return entry_exists(fname, 0);
1.118 paf 555: }
556:
1.215 paf 557: bool file_exist(const String& file_spec) {
1.126 paf 558: return entry_readable(file_spec, false);
1.51 paf 559: }
1.239 misha 560:
1.215 paf 561: bool dir_exists(const String& file_spec) {
1.126 paf 562: return entry_readable(file_spec, true);
1.65 parser 563: }
1.239 misha 564:
1.215 paf 565: const String* file_exist(const String& path, const String& name) {
1.154 paf 566: String& result=*new String(path);
567: result << "/";
568: result << name;
1.215 paf 569: return file_exist(result)?&result:0;
1.43 paf 570: }
1.239 misha 571:
1.43 paf 572: bool file_executable(const String& file_spec) {
1.247 misha 573: return access(file_spec.taint_cstr(String::L_FILE_SPEC), X_OK)==0;
1.44 paf 574: }
575:
1.64 parser 576: bool file_stat(const String& file_spec,
1.229 misha 577: size_t& rsize,
578: time_t& ratime,
579: time_t& rmtime,
580: time_t& rctime,
581: bool fail_on_read_problem) {
1.247 misha 582: const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.154 paf 583: struct stat finfo;
1.44 paf 584: if(stat(fname, &finfo)!=0)
1.64 parser 585: if(fail_on_read_problem)
1.126 paf 586: throw Exception("file.missing",
1.67 parser 587: &file_spec,
588: "getting file size failed: %s (%d), real filename '%s'",
1.154 paf 589: strerror(errno), errno, fname);
1.64 parser 590: else
591: return false;
1.58 parser 592: rsize=finfo.st_size;
593: ratime=finfo.st_atime;
594: rmtime=finfo.st_mtime;
595: rctime=finfo.st_ctime;
1.64 parser 596: return true;
1.18 paf 597: }
598:
1.126 paf 599: char* getrow(char* *row_ref, char delim) {
1.229 misha 600: char* result=*row_ref;
601: if(result) {
1.126 paf 602: *row_ref=strchr(result, delim);
1.8 paf 603: if(*row_ref)
604: *((*row_ref)++)=0;
605: else if(!*result)
606: return 0;
1.229 misha 607: }
608: return result;
1.8 paf 609: }
610:
1.126 paf 611: char* lsplit(char* string, char delim) {
1.229 misha 612: if(string) {
1.126 paf 613: char* v=strchr(string, delim);
1.8 paf 614: if(v) {
615: *v=0;
616: return v+1;
617: }
1.229 misha 618: }
619: return 0;
1.8 paf 620: }
621:
1.126 paf 622: char* lsplit(char* *string_ref, char delim) {
1.229 misha 623: char* result=*string_ref;
1.126 paf 624: char* next=lsplit(*string_ref, delim);
1.229 misha 625: *string_ref=next;
626: return result;
1.9 paf 627: }
628:
1.126 paf 629: char* rsplit(char* string, char delim) {
1.229 misha 630: if(string) {
1.126 paf 631: char* v=strrchr(string, delim);
1.18 paf 632: if(v) {
1.9 paf 633: *v=0;
634: return v+1;
635: }
1.229 misha 636: }
637: return NULL;
1.10 paf 638: }
639:
1.229 misha 640:
641: // format: %[flags][width][.precision]type http://msdn.microsoft.com/ru-ru/library/56e442dc(en-us,VS.80).aspx
642: // flags: '-', '+', ' ', '#', '0' http://msdn.microsoft.com/ru-ru/library/8aky45ct(en-us,VS.80).aspx
643: // width, precision: non negative decimal number
644: enum FormatType {
645: FormatInvalid,
646: FormatInt,
647: FormatUInt,
648: FormatDouble
649: };
650: FormatType format_type(char* fmt){
651: enum FormatState {
652: Percent,
653: Flags,
654: Width,
655: Precision,
656: Done
657: } state=Percent;
658:
659: FormatType result=FormatInvalid;
660:
661: char* pos=fmt;
662: while(char c=*(pos++)){
663: switch(state){
664: case Percent:
665: if(c=='%'){
666: state=Flags;
667: } else {
668: return FormatInvalid; // 1st char must be '%' only
669: }
670: break;
671: case Flags:
672: if(strchr("-+ #0", c)!=0){
673: break;
674: }
675: // go to the next step
676: case Width:
677: if(c=='.'){
678: state=Precision;
679: break;
680: }
681: // go to the next step
682: case Precision:
683: if(c>='0' && c<='9'){
684: if(state == Flags) state=Width; // no more flags
685: break;
686: } else if(c=='d' || c=='i'){
687: result=FormatInt;
688: } else if(strchr("feEgG", c)!=0){
689: result=FormatDouble;
690: } else if(strchr("uoxX", c)!=0){
691: result=FormatUInt;
692: } else {
693: return FormatInvalid; // invalid char
694: }
695: state=Done;
696: break;
697: case Done:
698: return FormatInvalid; // no chars allowed after 'type'
699: }
700: }
701: return result;
702: }
703:
704:
1.154 paf 705: const char* format(double value, char* fmt) {
1.229 misha 706: char local_buf[MAX_NUMBER];
1.235 misha 707: int size=-1;
1.229 misha 708:
709: if(fmt && strlen(fmt)){
710: switch(format_type(fmt)){
711: case FormatDouble:
712: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
713: break;
714: case FormatInt:
715: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
716: break;
717: case FormatUInt:
1.126 paf 718: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.229 misha 719: break;
720: case FormatInvalid:
721: throw Exception(PARSER_RUNTIME,
722: 0,
723: "Incorrect format string '%s' was specified.", fmt);
724: }
725: } else
726: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
727:
728: if(size < 0 || size >= MAX_NUMBER-1){ // on win32 we manually reduce max size while printing
729: throw Exception(PARSER_RUNTIME,
730: 0,
731: "Error occure white executing snprintf with format string '%s'.", fmt);
732: }
733:
1.235 misha 734: return pa_strdup(local_buf, (size_t)size);
1.12 paf 735: }
736:
1.36 paf 737: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 738: #ifdef WIN32
1.187 paf 739: size_t to_write = size;
1.12 paf 740: do{
1.154 paf 741: int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 742: if(chunk_written<=0)
743: break;
744: size-=chunk_written;
1.36 paf 745: buf=((const char*)buf)+chunk_written;
1.126 paf 746: } while(size>0);
1.12 paf 747:
1.187 paf 748: return to_write-size;
1.12 paf 749: #else
1.126 paf 750: return fwrite(buf, 1, size, stdout);
1.12 paf 751: #endif
1.2 paf 752: }
1.14 paf 753:
1.229 misha 754: enum EscapeState {
755: EscapeRest,
756: EscapeFirst,
757: EscapeSecond,
758: EscapeUnicode
759: };
760:
1.236 misha 761: // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually)
1.258 misha 762: char* unescape_chars(const char* cp, int len, Charset* charset, bool js){
1.236 misha 763: char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
1.230 misha 764: char* dst=s;
1.229 misha 765: EscapeState escapeState=EscapeRest;
766: uint escapedValue=0;
767: int srcPos=0;
1.230 misha 768: short int jsCnt=0;
1.236 misha 769: while(srcPos<len){
1.229 misha 770: uchar c=(uchar)cp[srcPos];
1.258 misha 771: if(c=='%' || (c=='\\' && js)){
1.229 misha 772: escapeState=EscapeFirst;
773: } else {
774: switch(escapeState) {
775: case EscapeRest:
1.258 misha 776: if(!js && c=='+'){
1.230 misha 777: *dst++=' ';
1.229 misha 778: } else {
1.230 misha 779: *dst++=c;
1.229 misha 780: }
781: break;
782: case EscapeFirst:
1.232 misha 783: if(charset && c=='u'){
1.229 misha 784: // escaped unicode value: %u0430
785: jsCnt=0;
786: escapedValue=0;
787: escapeState=EscapeUnicode;
788: } else {
1.231 misha 789: if(isxdigit(c)){
1.229 misha 790: escapedValue=hex_value[c] << 4;
791: escapeState=EscapeSecond;
792: } else {
1.230 misha 793: *dst++=c;
1.229 misha 794: escapeState=EscapeRest;
795: }
796: }
797: break;
798: case EscapeSecond:
1.231 misha 799: if(isxdigit(c)){
1.229 misha 800: escapedValue+=hex_value[c];
1.230 misha 801: *dst++=(char)escapedValue;
1.229 misha 802: }
803: escapeState=EscapeRest;
804: break;
805: case EscapeUnicode:
1.231 misha 806: if(isxdigit(c)){
1.229 misha 807: escapedValue=(escapedValue << 4) + hex_value[c];
808: if(++jsCnt==4){
1.230 misha 809: // transcode utf8 char to client charset (we can lost some chars here)
1.232 misha 810: charset->store_Char((XMLByte*&)dst, (XMLCh)escapedValue, '?');
1.229 misha 811: escapeState=EscapeRest;
812: }
813: } else {
814: // not full unicode value
815: escapeState=EscapeRest;
816: }
817: break;
818: }
819: }
820:
821: srcPos++;
822: }
823:
1.230 misha 824: *dst=0; // zero-termination
1.229 misha 825: return s;
826: }
1.24 paf 827:
828: #ifdef WIN32
1.126 paf 829: void back_slashes_to_slashes(char* s) {
1.24 paf 830: if(s)
831: for(; *s; s++)
832: if(*s=='\\')
1.126 paf 833: *s='/';
1.24 paf 834: }
1.42 paf 835: /*
1.126 paf 836: void slashes_to_back_slashes(char* s) {
1.42 paf 837: if(s)
838: for(; *s; s++)
839: if(*s=='/')
1.126 paf 840: *s='\\';
1.42 paf 841: }
842: */
1.24 paf 843: #endif
1.41 paf 844:
1.231 misha 845: bool StrStartFromNC(const char* str, const char* substr, bool equal){
1.41 paf 846: while(true) {
1.231 misha 847: if(!(*substr)){
848: if(!(*str))
1.41 paf 849: return true;
850: else
1.231 misha 851: return !equal;
852: }
853: if(!(*str))
854: return false;
855: if(isalpha((unsigned char)*str)) {
856: if(tolower((unsigned char)*str)!=tolower((unsigned char)*substr))
1.41 paf 857: return false;
1.231 misha 858: } else if((*str) != (*substr))
1.41 paf 859: return false;
1.231 misha 860: str++;
861: substr++;
1.41 paf 862: }
1.57 parser 863: }
864:
1.232 misha 865: size_t strpos(const char *str, const char *substr) {
866: const char *p = strstr(str, substr);
867: return (p==0)?STRING_NOT_FOUND:p-str;
868: }
869:
870: // content-type: xxx; charset=WE-NEED-THIS
871: // content-type: xxx; charset="WE-NEED-THIS"
872: // content-type: xxx; charset="WE-NEED-THIS";
1.248 misha 873: Charset* detect_charset(const char* content_type){
1.233 misha 874: if(content_type){
1.245 misha 875: char* CONTENT_TYPE=pa_strdup(content_type);
1.248 misha 876:
877: for(char *p=CONTENT_TYPE; *p; p++)
878: *p=(char)toupper((unsigned char)*p);
1.233 misha 879:
880: if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
881: begin+=8; // skip "CHARSET="
882: char* end=0;
883: if(*begin && (*begin=='"' || *begin =='\'')){
884: char quote=*begin;
885: begin++;
886: end=(char*)strchr(begin, quote);
887: }
888: if(!end)
889: end=(char*)strchr(begin, ';');
890:
1.244 misha 891: if(end)
1.233 misha 892: *end=0; // terminator
893:
1.245 misha 894: return *begin?&charsets.get(begin):0;
1.232 misha 895: }
896: }
897: return 0;
898: }
899:
900:
1.84 paf 901: static bool isLeap(int year) {
1.229 misha 902: return !(
903: (year % 4) || ((year % 400) && !(year % 100))
904: );
1.57 parser 905: }
906:
907: int getMonthDays(int year, int month) {
1.220 misha 908: static int monthDays[]={
1.229 misha 909: 31,
910: 28,
911: 31,
912: 30,
913: 31,
914: 30,
915: 31,
916: 31,
917: 30,
918: 31,
919: 30,
920: 31
921: };
1.228 misha 922: return (month == 1 /* january -- 0 */ && isLeap(year)) ? 29 : monthDays[month];
1.41 paf 923: }
1.69 parser 924:
1.226 misha 925: int remove_crlf(char* start, char* end) {
926: char* from=start;
927: char* to=start;
928: bool skip=false;
929: while(from < end){
930: switch(*from){
931: case '\n':
932: case '\r':
933: case '\t':
934: case ' ':
935: if(!skip){
936: *to=' ';
937: to++;
938: skip=true;
939: }
940: break;
941: default:
942: if(from != to)
943: *to=*from;
944: to++;
945: skip=false;
1.69 parser 946: }
1.226 misha 947: from++;
948: }
949: return to-start;
1.91 paf 950: }
951:
952:
953: /// must be last in this file
954: #undef vsnprintf
1.126 paf 955: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 956: if(!s)
957: return 0;
958:
959: int r;
960: // note: on win32& maybe somewhere else
961: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
962: --s;
1.172 paf 963:
964: // clients do not check for negative 's', feature: ignore such prints
965: if((ssize_t)s<0)
966: return 0;
967:
1.91 paf 968: #if _MSC_VER
969: /*
970: win32:
971: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
972:
1.154 paf 973: if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91 paf 974: */
1.126 paf 975: r=_vsnprintf(b, s, f, l);
1.91 paf 976: if(r<0)
977: r=s;
978: #else
1.126 paf 979: r=vsnprintf(b, s, f, l);
1.91 paf 980: /*
981: solaris:
982: man vsnprintf
983:
984: The snprintf() function returns the number of characters
985: formatted, that is, the number of characters that would have
986: been written to the buffer if it were large enough. If the
987: value of n is 0 on a call to snprintf(), an unspecified
988: value less than 1 is returned.
989: */
990:
991: if(r<0)
992: r=0;
1.167 paf 993: else if((size_t)r>s)
1.91 paf 994: r=s;
995: #endif
996: b[r]=0;
997: return r;
998: }
999:
1.126 paf 1000: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 1001: va_list l;
1.241 misha 1002: va_start(l, f);
1003: int r=__vsnprintf(b, s, f, l);
1004: va_end(l);
1.91 paf 1005: return r;
1.178 paf 1006: }
1007:
1008: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
1009: /*
1010: * Authors: Michael Zucchi <notzed@helixcode.com>
1011: * Jeffrey Stedfast <fejj@helixcode.com>
1012: *
1013: * Copyright 2000 Helix Code, Inc. (www.helixcode.com)
1014: *
1015: * This program is free software; you can redistribute it and/or modify
1016: * it under the terms of the GNU General Public License as published by
1017: * the Free Software Foundation; either version 2 of the License, or
1018: * (at your option) any later version.
1019: *
1020: * This program is distributed in the hope that it will be useful,
1021: * but WITHOUT ANY WARRANTY; without even the implied warranty of
1022: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1023: * GNU General Public License for more details.
1024: *
1025: * You should have received a copy of the GNU General Public License
1026: * along with this program; if not, write to the Free Software
1027: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
1028: *
1029: */
1030: static char *base64_alphabet =
1031: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1032:
1033: /**
1034: * g_mime_utils_base64_encode_step:
1035: * @in: input stream
1036: * @inlen: length of the input
1037: * @out: output string
1038: * @state: holds the number of bits that are stored in @save
1039: * @save: leftover bits that have not yet been encoded
1040: *
1041: * Base64 encodes a chunk of data. Performs an 'encode step', only
1042: * encodes blocks of 3 characters to the output at a time, saves
1043: * left-over state in state and save (initialise to 0 on first
1044: * invocation).
1045: *
1046: * Returns the number of bytes encoded.
1047: **/
1.252 misha 1048:
1049: #define BASE64_GROUPS_IN_LINE 19
1050:
1.178 paf 1051: static size_t
1052: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1053: {
1.186 paf 1054: register const unsigned char *inptr;
1.178 paf 1055: register unsigned char *outptr;
1056:
1057: if (inlen <= 0)
1058: return 0;
1059:
1060: inptr = in;
1061: outptr = out;
1062:
1063: if (inlen + ((unsigned char *)save)[0] > 2) {
1064: const unsigned char *inend = in + inlen - 2;
1065: register int c1 = 0, c2 = 0, c3 = 0;
1066: register int already;
1067:
1068: already = *state;
1069:
1070: switch (((char *)save)[0]) {
1071: case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
1072: case 2: c1 = ((unsigned char *)save)[1];
1073: c2 = ((unsigned char *)save)[2]; goto skip2;
1074: }
1075:
1076: /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
1077: while (inptr < inend) {
1078: c1 = *inptr++;
1079: skip1:
1080: c2 = *inptr++;
1081: skip2:
1082: c3 = *inptr++;
1083: *outptr++ = base64_alphabet [c1 >> 2];
1084: *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
1085: *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
1086: *outptr++ = base64_alphabet [c3 & 0x3f];
1087: /* this is a bit ugly ... */
1.252 misha 1088: if ((++already) >= BASE64_GROUPS_IN_LINE) {
1.178 paf 1089: *outptr++ = '\n';
1090: already = 0;
1091: }
1092: }
1093:
1094: ((unsigned char *)save)[0] = 0;
1095: inlen = 2 - (inptr - inend);
1096: *state = already;
1097: }
1098:
1099: //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
1100:
1101: if (inlen > 0) {
1102: register char *saveout;
1103:
1104: /* points to the slot for the next char to save */
1105: saveout = & (((char *)save)[1]) + ((char *)save)[0];
1106:
1107: /* inlen can only be 0 1 or 2 */
1108: switch (inlen) {
1109: case 2: *saveout++ = *inptr++;
1110: case 1: *saveout++ = *inptr++;
1111: }
1.216 paf 1112: *(char *)save = *(char *)save+(char)inlen;
1.178 paf 1113: }
1114:
1115: /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
1116: (int)((char *)save)[0],
1117: (int)((char *)save)[1],
1118: (int)((char *)save)[2]));*/
1119:
1120: return (outptr - out);
1121: }
1122:
1123: /**
1124: * g_mime_utils_base64_encode_close:
1125: * @in: input stream
1126: * @inlen: length of the input
1127: * @out: output string
1128: * @state: holds the number of bits that are stored in @save
1129: * @save: leftover bits that have not yet been encoded
1130: *
1131: * Base64 encodes the input stream to the output stream. Call this
1132: * when finished encoding data with g_mime_utils_base64_encode_step to
1133: * flush off the last little bit.
1134: *
1135: * Returns the number of bytes encoded.
1136: **/
1137: static size_t
1138: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1139: {
1140: unsigned char *outptr = out;
1141: int c1, c2;
1142:
1143: if (inlen > 0)
1144: outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
1145:
1146: c1 = ((unsigned char *)save)[1];
1147: c2 = ((unsigned char *)save)[2];
1148:
1149: switch (((unsigned char *)save)[0]) {
1150: case 2:
1151: outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
1152: goto skip;
1153: case 1:
1154: outptr[2] = '=';
1155: skip:
1156: outptr[0] = base64_alphabet [c1 >> 2];
1157: outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
1158: outptr[3] = '=';
1159: outptr += 4;
1160: break;
1161: }
1162:
1163: *outptr++ = 0;
1164:
1165: *save = 0;
1166: *state = 0;
1167:
1168: return (outptr - out);
1169: }
1170:
1.210 paf 1171: static unsigned char gmime_base64_rank[256] = {
1172: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1173: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1174: 255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
1175: 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255, 0,255,255,
1176: 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
1177: 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
1178: 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
1179: 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
1180: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1181: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1182: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1183: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1184: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1185: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1186: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1187: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1188: };
1189:
1190: /**
1191: * g_mime_utils_base64_decode_step:
1192: * @in: input stream
1193: * @inlen: max length of data to decode
1194: * @out: output stream
1195: * @state: holds the number of bits that are stored in @save
1196: * @save: leftover bits that have not yet been decoded
1197: *
1198: * Decodes a chunk of base64 encoded data.
1199: *
1200: * Returns the number of bytes decoded (which have been dumped in @out).
1201: **/
1202: size_t
1203: g_mime_utils_base64_decode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1204: {
1.213 paf 1205: const unsigned char *inptr;
1206: unsigned char *outptr;
1.210 paf 1207: const unsigned char *inend;
1.213 paf 1208: int saved;
1.210 paf 1209: unsigned char c;
1210: int i;
1211:
1212: inend = in + inlen;
1213: outptr = out;
1214:
1215: /* convert 4 base64 bytes to 3 normal bytes */
1216: saved = *save;
1217: i = *state;
1218: inptr = in;
1219: while (inptr < inend) {
1220: c = gmime_base64_rank[*inptr++];
1221: if (c != 0xff) {
1222: saved = (saved << 6) | c;
1223: i++;
1224: if (i == 4) {
1.217 paf 1225: *outptr++ = (unsigned char)(saved >> 16);
1226: *outptr++ = (unsigned char)(saved >> 8);
1227: *outptr++ = (unsigned char)(saved);
1.210 paf 1228: i = 0;
1229: }
1230: }
1231: }
1232:
1233: *save = saved;
1234: *state = i;
1235:
1236: /* quick scan back for '=' on the end somewhere */
1237: /* fortunately we can drop 1 output char for each trailing = (upto 2) */
1238: i = 2;
1239: while (inptr > in && i) {
1240: inptr--;
1241: if (gmime_base64_rank[*inptr] != 0xff) {
1242: if (*inptr == '=' && outptr > out)
1243: outptr--;
1244: i--;
1245: }
1246: }
1247:
1248: /* if i != 0 then there is a truncation error! */
1249: return (outptr - out);
1250: }
1251:
1252:
1.239 misha 1253: char* pa_base64_encode(const char *in, size_t in_size){
1.252 misha 1254: size_t new_size = ((in_size / 3 + 1) * 4);
1255: new_size += new_size / (BASE64_GROUPS_IN_LINE * 4)/*new lines*/ + 1/*zero terminator*/;
1256: char* result = new(PointerFreeGC) char[new_size];
1.178 paf 1257: int state=0;
1258: int save=0;
1.183 paf 1259: #ifndef NDEBUG
1260: size_t filled=
1261: #endif
1.251 misha 1262: g_mime_utils_base64_encode_close ((const unsigned char*)in, in_size, (unsigned char*)result, &state, &save);
1263:
1264: //throw Exception(PARSER_RUNTIME, 0, "%d %d %d", in_size, new_size, filled);
1265: assert(filled <= new_size);
1.178 paf 1266:
1267: return result;
1.98 paf 1268: }
1.210 paf 1269:
1.222 misha 1270:
1.239 misha 1271: char* pa_base64_encode(const String& file_spec){
1.222 misha 1272: unsigned char* base64=0;
1273: File_base64_action_info info={&base64};
1274:
1275: file_read_action_under_lock(file_spec,
1276: "pa_base64_encode", file_base64_file_action, &info);
1277:
1278: return (char*)base64;
1279: }
1280:
1281:
1282: static void file_base64_file_action(
1.229 misha 1283: struct stat& finfo,
1284: int f,
1285: const String&, const char* /*fname*/, bool,
1286: void *context) {
1.222 misha 1287:
1288: if(finfo.st_size) {
1289: File_base64_action_info& info=*static_cast<File_base64_action_info *>(context);
1290: *info.base64=new(PointerFreeGC) unsigned char[finfo.st_size * 2 + 6];
1291: unsigned char* base64 = *info.base64;
1292: int state=0;
1293: int save=0;
1294: int nCount;
1295: do {
1296: unsigned char buffer[FILE_BUFFER_SIZE];
1297: nCount = file_block_read(f, buffer, sizeof(buffer));
1298: if( nCount ){
1299: size_t filled=g_mime_utils_base64_encode_step ((const unsigned char*)buffer, nCount, base64, &state, &save);
1300: base64+=filled;
1301: }
1302: } while(nCount > 0);
1303: g_mime_utils_base64_encode_close (0, 0, base64, &state, &save);
1304: }
1305: }
1306:
1.239 misha 1307: void pa_base64_decode(const char *in, size_t in_size, char*& result, size_t& result_size) {
1.210 paf 1308: /* wont go to more than had (overly conservative) */
1.211 paf 1309: result=new(PointerFreeGC) char[in_size+1/*terminator*/];
1.210 paf 1310: int state=0;
1311: int save=0;
1312: result_size=
1313: g_mime_utils_base64_decode_step ((const unsigned char*)in, in_size,
1314: (unsigned char*)result, &state, &save);
1315: assert(result_size <= in_size);
1.211 paf 1316: result[result_size]=0; // for text files
1.210 paf 1317: }
1.218 misha 1318:
1319:
1.221 misha 1320: int file_block_read(const int f, unsigned char* buffer, const size_t size){
1321: int nCount = read(f, buffer, size);
1322: if (nCount < 0)
1.238 misha 1323: throw Exception("file.read",
1.221 misha 1324: 0,
1325: "read failed: %s (%d)", strerror(errno), errno);
1326: return nCount;
1327: }
1328:
1.239 misha 1329: const unsigned long pa_crc32(const char *in, size_t in_size){
1.218 misha 1330: unsigned long crc32=0xFFFFFFFF;
1.220 misha 1331:
1.240 misha 1332: InitCrc32Table();
1.239 misha 1333: for(size_t i = 0; i<in_size; i++)
1334: CalcCrc32(in[i], crc32);
1.220 misha 1335:
1.218 misha 1336: return ~crc32;
1337: }
1338:
1.239 misha 1339: const unsigned long pa_crc32(const String& file_spec){
1.218 misha 1340: unsigned long crc32=0xFFFFFFFF;
1341: file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
1342: return ~crc32;
1343: }
1344:
1345: static void file_crc32_file_action(
1.229 misha 1346: struct stat& finfo,
1347: int f,
1348: const String&, const char* /*fname*/, bool,
1.239 misha 1349: void *context) {
1.218 misha 1350: unsigned long& crc32=*static_cast<unsigned long *>(context);
1351: if(finfo.st_size) {
1352: InitCrc32Table();
1.220 misha 1353: int nCount=0;
1.218 misha 1354: do {
1.221 misha 1355: unsigned char buffer[FILE_BUFFER_SIZE];
1356: nCount = file_block_read(f, buffer, sizeof(buffer));
1.220 misha 1357: for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
1358: } while(nCount > 0);
1.218 misha 1359: }
1360: }
1361:
E-mail: