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