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