Annotation of parser3/src/main/pa_common.C, revision 1.267
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.267 ! moko 39: volatile const char * IDENT_PA_COMMON_C="$Id: 2012-03-08 21:19:38 $" IDENT_PA_COMMON_H IDENT_PA_HASH_H IDENT_PA_ARRAY_H IDENT_PA_STACK_H;
! 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.164 paf 512: bool file_delete(const String& file_spec, bool fail_on_problem) {
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.126 paf 523: rmdir(file_spec, 1);
1.93 paf 524: return true;
1.60 parser 525: }
1.239 misha 526:
1.95 paf 527: void file_move(const String& old_spec, const String& new_spec) {
1.247 misha 528: const char* old_spec_cstr=old_spec.taint_cstr(String::L_FILE_SPEC);
529: const char* new_spec_cstr=new_spec.taint_cstr(String::L_FILE_SPEC);
1.63 parser 530:
1.126 paf 531: create_dir_for_file(new_spec);
1.63 parser 532:
1.60 parser 533: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 534: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.60 parser 535: &old_spec,
536: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.154 paf 537: strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 538:
1.126 paf 539: rmdir(old_spec, 1);
1.31 paf 540: }
541:
1.51 paf 542:
1.126 paf 543: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 544: struct stat lfinfo;
545: bool result=stat(fname, &lfinfo)==0;
546: if(afinfo)
547: *afinfo=lfinfo;
548: return result;
1.119 paf 549: }
550:
551: bool entry_exists(const String& file_spec) {
1.247 misha 552: const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.126 paf 553: return entry_exists(fname, 0);
1.118 paf 554: }
555:
1.215 paf 556: bool file_exist(const String& file_spec) {
1.126 paf 557: return entry_readable(file_spec, false);
1.51 paf 558: }
1.239 misha 559:
1.215 paf 560: bool dir_exists(const String& file_spec) {
1.126 paf 561: return entry_readable(file_spec, true);
1.65 parser 562: }
1.239 misha 563:
1.215 paf 564: const String* file_exist(const String& path, const String& name) {
1.154 paf 565: String& result=*new String(path);
566: result << "/";
567: result << name;
1.215 paf 568: return file_exist(result)?&result:0;
1.43 paf 569: }
1.239 misha 570:
1.43 paf 571: bool file_executable(const String& file_spec) {
1.247 misha 572: return access(file_spec.taint_cstr(String::L_FILE_SPEC), X_OK)==0;
1.44 paf 573: }
574:
1.64 parser 575: bool file_stat(const String& file_spec,
1.229 misha 576: size_t& rsize,
577: time_t& ratime,
578: time_t& rmtime,
579: time_t& rctime,
580: bool fail_on_read_problem) {
1.247 misha 581: const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC);
1.154 paf 582: struct stat finfo;
1.44 paf 583: if(stat(fname, &finfo)!=0)
1.64 parser 584: if(fail_on_read_problem)
1.126 paf 585: throw Exception("file.missing",
1.67 parser 586: &file_spec,
587: "getting file size failed: %s (%d), real filename '%s'",
1.154 paf 588: strerror(errno), errno, fname);
1.64 parser 589: else
590: return false;
1.58 parser 591: rsize=finfo.st_size;
592: ratime=finfo.st_atime;
593: rmtime=finfo.st_mtime;
594: rctime=finfo.st_ctime;
1.64 parser 595: return true;
1.18 paf 596: }
597:
1.126 paf 598: char* getrow(char* *row_ref, char delim) {
1.229 misha 599: char* result=*row_ref;
600: if(result) {
1.126 paf 601: *row_ref=strchr(result, delim);
1.8 paf 602: if(*row_ref)
603: *((*row_ref)++)=0;
604: else if(!*result)
605: return 0;
1.229 misha 606: }
607: return result;
1.8 paf 608: }
609:
1.126 paf 610: char* lsplit(char* string, char delim) {
1.229 misha 611: if(string) {
1.126 paf 612: char* v=strchr(string, delim);
1.8 paf 613: if(v) {
614: *v=0;
615: return v+1;
616: }
1.229 misha 617: }
618: return 0;
1.8 paf 619: }
620:
1.126 paf 621: char* lsplit(char* *string_ref, char delim) {
1.229 misha 622: char* result=*string_ref;
1.126 paf 623: char* next=lsplit(*string_ref, delim);
1.229 misha 624: *string_ref=next;
625: return result;
1.9 paf 626: }
627:
1.126 paf 628: char* rsplit(char* string, char delim) {
1.229 misha 629: if(string) {
1.126 paf 630: char* v=strrchr(string, delim);
1.18 paf 631: if(v) {
1.9 paf 632: *v=0;
633: return v+1;
634: }
1.229 misha 635: }
636: return NULL;
1.10 paf 637: }
638:
1.229 misha 639:
640: // format: %[flags][width][.precision]type http://msdn.microsoft.com/ru-ru/library/56e442dc(en-us,VS.80).aspx
641: // flags: '-', '+', ' ', '#', '0' http://msdn.microsoft.com/ru-ru/library/8aky45ct(en-us,VS.80).aspx
642: // width, precision: non negative decimal number
643: enum FormatType {
644: FormatInvalid,
645: FormatInt,
646: FormatUInt,
647: FormatDouble
648: };
649: FormatType format_type(char* fmt){
650: enum FormatState {
651: Percent,
652: Flags,
653: Width,
654: Precision,
655: Done
656: } state=Percent;
657:
658: FormatType result=FormatInvalid;
659:
660: char* pos=fmt;
661: while(char c=*(pos++)){
662: switch(state){
663: case Percent:
664: if(c=='%'){
665: state=Flags;
666: } else {
667: return FormatInvalid; // 1st char must be '%' only
668: }
669: break;
670: case Flags:
671: if(strchr("-+ #0", c)!=0){
672: break;
673: }
674: // go to the next step
675: case Width:
676: if(c=='.'){
677: state=Precision;
678: break;
679: }
680: // go to the next step
681: case Precision:
682: if(c>='0' && c<='9'){
683: if(state == Flags) state=Width; // no more flags
684: break;
685: } else if(c=='d' || c=='i'){
686: result=FormatInt;
687: } else if(strchr("feEgG", c)!=0){
688: result=FormatDouble;
689: } else if(strchr("uoxX", c)!=0){
690: result=FormatUInt;
691: } else {
692: return FormatInvalid; // invalid char
693: }
694: state=Done;
695: break;
696: case Done:
697: return FormatInvalid; // no chars allowed after 'type'
698: }
699: }
700: return result;
701: }
702:
703:
1.154 paf 704: const char* format(double value, char* fmt) {
1.229 misha 705: char local_buf[MAX_NUMBER];
1.235 misha 706: int size=-1;
1.229 misha 707:
708: if(fmt && strlen(fmt)){
709: switch(format_type(fmt)){
710: case FormatDouble:
711: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
712: break;
713: case FormatInt:
714: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
715: break;
716: case FormatUInt:
1.126 paf 717: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.229 misha 718: break;
719: case FormatInvalid:
720: throw Exception(PARSER_RUNTIME,
721: 0,
722: "Incorrect format string '%s' was specified.", fmt);
723: }
724: } else
725: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
726:
727: if(size < 0 || size >= MAX_NUMBER-1){ // on win32 we manually reduce max size while printing
728: throw Exception(PARSER_RUNTIME,
729: 0,
730: "Error occure white executing snprintf with format string '%s'.", fmt);
731: }
732:
1.235 misha 733: return pa_strdup(local_buf, (size_t)size);
1.12 paf 734: }
735:
1.36 paf 736: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 737: #ifdef WIN32
1.187 paf 738: size_t to_write = size;
1.12 paf 739: do{
1.154 paf 740: int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 741: if(chunk_written<=0)
742: break;
743: size-=chunk_written;
1.36 paf 744: buf=((const char*)buf)+chunk_written;
1.126 paf 745: } while(size>0);
1.12 paf 746:
1.187 paf 747: return to_write-size;
1.12 paf 748: #else
1.126 paf 749: return fwrite(buf, 1, size, stdout);
1.12 paf 750: #endif
1.2 paf 751: }
1.14 paf 752:
1.229 misha 753: enum EscapeState {
754: EscapeRest,
755: EscapeFirst,
756: EscapeSecond,
757: EscapeUnicode
758: };
759:
1.236 misha 760: // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually)
1.258 misha 761: char* unescape_chars(const char* cp, int len, Charset* charset, bool js){
1.236 misha 762: char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
1.230 misha 763: char* dst=s;
1.229 misha 764: EscapeState escapeState=EscapeRest;
765: uint escapedValue=0;
766: int srcPos=0;
1.230 misha 767: short int jsCnt=0;
1.236 misha 768: while(srcPos<len){
1.229 misha 769: uchar c=(uchar)cp[srcPos];
1.258 misha 770: if(c=='%' || (c=='\\' && js)){
1.229 misha 771: escapeState=EscapeFirst;
772: } else {
773: switch(escapeState) {
774: case EscapeRest:
1.258 misha 775: if(!js && c=='+'){
1.230 misha 776: *dst++=' ';
1.229 misha 777: } else {
1.230 misha 778: *dst++=c;
1.229 misha 779: }
780: break;
781: case EscapeFirst:
1.232 misha 782: if(charset && c=='u'){
1.229 misha 783: // escaped unicode value: %u0430
784: jsCnt=0;
785: escapedValue=0;
786: escapeState=EscapeUnicode;
787: } else {
1.231 misha 788: if(isxdigit(c)){
1.229 misha 789: escapedValue=hex_value[c] << 4;
790: escapeState=EscapeSecond;
791: } else {
1.230 misha 792: *dst++=c;
1.229 misha 793: escapeState=EscapeRest;
794: }
795: }
796: break;
797: case EscapeSecond:
1.231 misha 798: if(isxdigit(c)){
1.229 misha 799: escapedValue+=hex_value[c];
1.230 misha 800: *dst++=(char)escapedValue;
1.229 misha 801: }
802: escapeState=EscapeRest;
803: break;
804: case EscapeUnicode:
1.231 misha 805: if(isxdigit(c)){
1.229 misha 806: escapedValue=(escapedValue << 4) + hex_value[c];
807: if(++jsCnt==4){
1.230 misha 808: // transcode utf8 char to client charset (we can lost some chars here)
1.232 misha 809: charset->store_Char((XMLByte*&)dst, (XMLCh)escapedValue, '?');
1.229 misha 810: escapeState=EscapeRest;
811: }
812: } else {
813: // not full unicode value
814: escapeState=EscapeRest;
815: }
816: break;
817: }
818: }
819:
820: srcPos++;
821: }
822:
1.230 misha 823: *dst=0; // zero-termination
1.229 misha 824: return s;
825: }
1.24 paf 826:
827: #ifdef WIN32
1.126 paf 828: void back_slashes_to_slashes(char* s) {
1.24 paf 829: if(s)
830: for(; *s; s++)
831: if(*s=='\\')
1.126 paf 832: *s='/';
1.24 paf 833: }
1.42 paf 834: /*
1.126 paf 835: void slashes_to_back_slashes(char* s) {
1.42 paf 836: if(s)
837: for(; *s; s++)
838: if(*s=='/')
1.126 paf 839: *s='\\';
1.42 paf 840: }
841: */
1.24 paf 842: #endif
1.41 paf 843:
1.231 misha 844: bool StrStartFromNC(const char* str, const char* substr, bool equal){
1.41 paf 845: while(true) {
1.231 misha 846: if(!(*substr)){
847: if(!(*str))
1.41 paf 848: return true;
849: else
1.231 misha 850: return !equal;
851: }
852: if(!(*str))
853: return false;
854: if(isalpha((unsigned char)*str)) {
855: if(tolower((unsigned char)*str)!=tolower((unsigned char)*substr))
1.41 paf 856: return false;
1.231 misha 857: } else if((*str) != (*substr))
1.41 paf 858: return false;
1.231 misha 859: str++;
860: substr++;
1.41 paf 861: }
1.57 parser 862: }
863:
1.232 misha 864: size_t strpos(const char *str, const char *substr) {
865: const char *p = strstr(str, substr);
866: return (p==0)?STRING_NOT_FOUND:p-str;
867: }
868:
869: // content-type: xxx; charset=WE-NEED-THIS
870: // content-type: xxx; charset="WE-NEED-THIS"
871: // content-type: xxx; charset="WE-NEED-THIS";
1.248 misha 872: Charset* detect_charset(const char* content_type){
1.233 misha 873: if(content_type){
1.245 misha 874: char* CONTENT_TYPE=pa_strdup(content_type);
1.248 misha 875:
876: for(char *p=CONTENT_TYPE; *p; p++)
877: *p=(char)toupper((unsigned char)*p);
1.233 misha 878:
879: if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
880: begin+=8; // skip "CHARSET="
881: char* end=0;
882: if(*begin && (*begin=='"' || *begin =='\'')){
883: char quote=*begin;
884: begin++;
885: end=(char*)strchr(begin, quote);
886: }
887: if(!end)
888: end=(char*)strchr(begin, ';');
889:
1.244 misha 890: if(end)
1.233 misha 891: *end=0; // terminator
892:
1.245 misha 893: return *begin?&charsets.get(begin):0;
1.232 misha 894: }
895: }
896: return 0;
897: }
898:
899:
1.84 paf 900: static bool isLeap(int year) {
1.229 misha 901: return !(
902: (year % 4) || ((year % 400) && !(year % 100))
903: );
1.57 parser 904: }
905:
906: int getMonthDays(int year, int month) {
1.220 misha 907: static int monthDays[]={
1.229 misha 908: 31,
909: 28,
910: 31,
911: 30,
912: 31,
913: 30,
914: 31,
915: 31,
916: 30,
917: 31,
918: 30,
919: 31
920: };
1.228 misha 921: return (month == 1 /* january -- 0 */ && isLeap(year)) ? 29 : monthDays[month];
1.41 paf 922: }
1.69 parser 923:
1.226 misha 924: int remove_crlf(char* start, char* end) {
925: char* from=start;
926: char* to=start;
927: bool skip=false;
928: while(from < end){
929: switch(*from){
930: case '\n':
931: case '\r':
932: case '\t':
933: case ' ':
934: if(!skip){
935: *to=' ';
936: to++;
937: skip=true;
938: }
939: break;
940: default:
941: if(from != to)
942: *to=*from;
943: to++;
944: skip=false;
1.69 parser 945: }
1.226 misha 946: from++;
947: }
948: return to-start;
1.91 paf 949: }
950:
951:
952: /// must be last in this file
953: #undef vsnprintf
1.126 paf 954: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 955: if(!s)
956: return 0;
957:
958: int r;
959: // note: on win32& maybe somewhere else
960: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
961: --s;
1.172 paf 962:
963: // clients do not check for negative 's', feature: ignore such prints
964: if((ssize_t)s<0)
965: return 0;
966:
1.91 paf 967: #if _MSC_VER
968: /*
969: win32:
970: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
971:
1.154 paf 972: if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91 paf 973: */
1.126 paf 974: r=_vsnprintf(b, s, f, l);
1.91 paf 975: if(r<0)
976: r=s;
977: #else
1.126 paf 978: r=vsnprintf(b, s, f, l);
1.91 paf 979: /*
980: solaris:
981: man vsnprintf
982:
983: The snprintf() function returns the number of characters
984: formatted, that is, the number of characters that would have
985: been written to the buffer if it were large enough. If the
986: value of n is 0 on a call to snprintf(), an unspecified
987: value less than 1 is returned.
988: */
989:
990: if(r<0)
991: r=0;
1.167 paf 992: else if((size_t)r>s)
1.91 paf 993: r=s;
994: #endif
995: b[r]=0;
996: return r;
997: }
998:
1.126 paf 999: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 1000: va_list l;
1.241 misha 1001: va_start(l, f);
1002: int r=__vsnprintf(b, s, f, l);
1003: va_end(l);
1.91 paf 1004: return r;
1.178 paf 1005: }
1006:
1007: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
1008: /*
1009: * Authors: Michael Zucchi <notzed@helixcode.com>
1010: * Jeffrey Stedfast <fejj@helixcode.com>
1011: *
1012: * Copyright 2000 Helix Code, Inc. (www.helixcode.com)
1013: *
1014: * This program is free software; you can redistribute it and/or modify
1015: * it under the terms of the GNU General Public License as published by
1016: * the Free Software Foundation; either version 2 of the License, or
1017: * (at your option) any later version.
1018: *
1019: * This program is distributed in the hope that it will be useful,
1020: * but WITHOUT ANY WARRANTY; without even the implied warranty of
1021: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1022: * GNU General Public License for more details.
1023: *
1024: * You should have received a copy of the GNU General Public License
1025: * along with this program; if not, write to the Free Software
1026: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
1027: *
1028: */
1029: static char *base64_alphabet =
1030: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1031:
1032: /**
1033: * g_mime_utils_base64_encode_step:
1034: * @in: input stream
1035: * @inlen: length of the input
1036: * @out: output string
1037: * @state: holds the number of bits that are stored in @save
1038: * @save: leftover bits that have not yet been encoded
1039: *
1040: * Base64 encodes a chunk of data. Performs an 'encode step', only
1041: * encodes blocks of 3 characters to the output at a time, saves
1042: * left-over state in state and save (initialise to 0 on first
1043: * invocation).
1044: *
1045: * Returns the number of bytes encoded.
1046: **/
1.252 misha 1047:
1048: #define BASE64_GROUPS_IN_LINE 19
1049:
1.178 paf 1050: static size_t
1051: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1052: {
1.186 paf 1053: register const unsigned char *inptr;
1.178 paf 1054: register unsigned char *outptr;
1055:
1056: if (inlen <= 0)
1057: return 0;
1058:
1059: inptr = in;
1060: outptr = out;
1061:
1062: if (inlen + ((unsigned char *)save)[0] > 2) {
1063: const unsigned char *inend = in + inlen - 2;
1064: register int c1 = 0, c2 = 0, c3 = 0;
1065: register int already;
1066:
1067: already = *state;
1068:
1069: switch (((char *)save)[0]) {
1070: case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
1071: case 2: c1 = ((unsigned char *)save)[1];
1072: c2 = ((unsigned char *)save)[2]; goto skip2;
1073: }
1074:
1075: /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
1076: while (inptr < inend) {
1077: c1 = *inptr++;
1078: skip1:
1079: c2 = *inptr++;
1080: skip2:
1081: c3 = *inptr++;
1082: *outptr++ = base64_alphabet [c1 >> 2];
1083: *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
1084: *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
1085: *outptr++ = base64_alphabet [c3 & 0x3f];
1086: /* this is a bit ugly ... */
1.252 misha 1087: if ((++already) >= BASE64_GROUPS_IN_LINE) {
1.178 paf 1088: *outptr++ = '\n';
1089: already = 0;
1090: }
1091: }
1092:
1093: ((unsigned char *)save)[0] = 0;
1094: inlen = 2 - (inptr - inend);
1095: *state = already;
1096: }
1097:
1098: //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
1099:
1100: if (inlen > 0) {
1101: register char *saveout;
1102:
1103: /* points to the slot for the next char to save */
1104: saveout = & (((char *)save)[1]) + ((char *)save)[0];
1105:
1106: /* inlen can only be 0 1 or 2 */
1107: switch (inlen) {
1108: case 2: *saveout++ = *inptr++;
1109: case 1: *saveout++ = *inptr++;
1110: }
1.216 paf 1111: *(char *)save = *(char *)save+(char)inlen;
1.178 paf 1112: }
1113:
1114: /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
1115: (int)((char *)save)[0],
1116: (int)((char *)save)[1],
1117: (int)((char *)save)[2]));*/
1118:
1119: return (outptr - out);
1120: }
1121:
1122: /**
1123: * g_mime_utils_base64_encode_close:
1124: * @in: input stream
1125: * @inlen: length of the input
1126: * @out: output string
1127: * @state: holds the number of bits that are stored in @save
1128: * @save: leftover bits that have not yet been encoded
1129: *
1130: * Base64 encodes the input stream to the output stream. Call this
1131: * when finished encoding data with g_mime_utils_base64_encode_step to
1132: * flush off the last little bit.
1133: *
1134: * Returns the number of bytes encoded.
1135: **/
1136: static size_t
1137: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1138: {
1139: unsigned char *outptr = out;
1140: int c1, c2;
1141:
1142: if (inlen > 0)
1143: outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
1144:
1145: c1 = ((unsigned char *)save)[1];
1146: c2 = ((unsigned char *)save)[2];
1147:
1148: switch (((unsigned char *)save)[0]) {
1149: case 2:
1150: outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
1151: goto skip;
1152: case 1:
1153: outptr[2] = '=';
1154: skip:
1155: outptr[0] = base64_alphabet [c1 >> 2];
1156: outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
1157: outptr[3] = '=';
1158: outptr += 4;
1159: break;
1160: }
1161:
1162: *outptr++ = 0;
1163:
1164: *save = 0;
1165: *state = 0;
1166:
1167: return (outptr - out);
1168: }
1169:
1.210 paf 1170: static unsigned char gmime_base64_rank[256] = {
1.266 misha 1171: 255,255,255,255,255,255,255,255,255,254,254,255,255,254,255,255,
1.210 paf 1172: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1.266 misha 1173: 254,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
1.210 paf 1174: 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255, 0,255,255,
1175: 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
1176: 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
1177: 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
1178: 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
1179: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1180: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1181: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1182: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1183: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1184: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1185: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1186: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1187: };
1188:
1189: /**
1190: * g_mime_utils_base64_decode_step:
1191: * @in: input stream
1192: * @inlen: max length of data to decode
1193: * @out: output stream
1194: * @state: holds the number of bits that are stored in @save
1195: * @save: leftover bits that have not yet been decoded
1.266 misha 1196: * @strict: only base64 and whitespace chars are allowed
1.210 paf 1197: *
1198: * Decodes a chunk of base64 encoded data.
1199: *
1200: * Returns the number of bytes decoded (which have been dumped in @out).
1201: **/
1202: size_t
1.266 misha 1203: 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 1204: {
1.213 paf 1205: const unsigned char *inptr;
1206: unsigned char *outptr;
1.210 paf 1207: const unsigned char *inend;
1.213 paf 1208: int saved;
1.210 paf 1209: unsigned char c;
1210: int i;
1211:
1212: inend = in + inlen;
1213: outptr = out;
1214:
1215: /* convert 4 base64 bytes to 3 normal bytes */
1216: saved = *save;
1217: i = *state;
1218: inptr = in;
1219: while (inptr < inend) {
1220: c = gmime_base64_rank[*inptr++];
1.266 misha 1221: switch(c) {
1222: case 0xff: // non-base64 and non-whitespace chars. not allowed in strict mode
1223: if(strict)
1224: throw Exception(BASE64_FORMAT, 0, "Invalid base64 char on position %d is detected", inptr-in-1);
1225: case 0xfe: // whitespace chars 0x09, 0x0A, 0x0D, 0x20 are allowed in any mode
1226: break;
1227: default:
1228: saved = (saved << 6) | c;
1229: i++;
1230: if (i == 4) {
1231: *outptr++ = (unsigned char)(saved >> 16);
1232: *outptr++ = (unsigned char)(saved >> 8);
1233: *outptr++ = (unsigned char)(saved);
1234: i = 0;
1235: }
1.210 paf 1236: }
1237: }
1238:
1239: *save = saved;
1240: *state = i;
1241:
1242: /* quick scan back for '=' on the end somewhere */
1243: /* fortunately we can drop 1 output char for each trailing = (upto 2) */
1244: i = 2;
1245: while (inptr > in && i) {
1246: inptr--;
1.266 misha 1247: if (gmime_base64_rank[*inptr] <= 0xfe) {
1.210 paf 1248: if (*inptr == '=' && outptr > out)
1249: outptr--;
1250: i--;
1251: }
1252: }
1253:
1254: /* if i != 0 then there is a truncation error! */
1255: return (outptr - out);
1256: }
1257:
1258:
1.239 misha 1259: char* pa_base64_encode(const char *in, size_t in_size){
1.252 misha 1260: size_t new_size = ((in_size / 3 + 1) * 4);
1261: new_size += new_size / (BASE64_GROUPS_IN_LINE * 4)/*new lines*/ + 1/*zero terminator*/;
1262: char* result = new(PointerFreeGC) char[new_size];
1.178 paf 1263: int state=0;
1264: int save=0;
1.183 paf 1265: #ifndef NDEBUG
1266: size_t filled=
1267: #endif
1.251 misha 1268: g_mime_utils_base64_encode_close ((const unsigned char*)in, in_size, (unsigned char*)result, &state, &save);
1269:
1270: //throw Exception(PARSER_RUNTIME, 0, "%d %d %d", in_size, new_size, filled);
1271: assert(filled <= new_size);
1.178 paf 1272:
1273: return result;
1.98 paf 1274: }
1.210 paf 1275:
1.222 misha 1276:
1.239 misha 1277: char* pa_base64_encode(const String& file_spec){
1.222 misha 1278: unsigned char* base64=0;
1279: File_base64_action_info info={&base64};
1280:
1281: file_read_action_under_lock(file_spec,
1282: "pa_base64_encode", file_base64_file_action, &info);
1283:
1284: return (char*)base64;
1285: }
1286:
1287:
1288: static void file_base64_file_action(
1.229 misha 1289: struct stat& finfo,
1290: int f,
1291: const String&, const char* /*fname*/, bool,
1292: void *context) {
1.222 misha 1293:
1294: if(finfo.st_size) {
1295: File_base64_action_info& info=*static_cast<File_base64_action_info *>(context);
1296: *info.base64=new(PointerFreeGC) unsigned char[finfo.st_size * 2 + 6];
1297: unsigned char* base64 = *info.base64;
1298: int state=0;
1299: int save=0;
1300: int nCount;
1301: do {
1302: unsigned char buffer[FILE_BUFFER_SIZE];
1303: nCount = file_block_read(f, buffer, sizeof(buffer));
1304: if( nCount ){
1305: size_t filled=g_mime_utils_base64_encode_step ((const unsigned char*)buffer, nCount, base64, &state, &save);
1306: base64+=filled;
1307: }
1308: } while(nCount > 0);
1309: g_mime_utils_base64_encode_close (0, 0, base64, &state, &save);
1310: }
1311: }
1312:
1.265 misha 1313: void pa_base64_decode(const char *in, size_t in_size, char*& result, size_t& result_size, bool strict) {
1.264 misha 1314: // every 4 base64 bytes are converted into 3 normal bytes
1315: // not full set (tail) of 4-bytes set is ignored
1316: size_t new_size=in_size/4*3;
1317: result=new(PointerFreeGC) char[new_size+1/*terminator*/];
1318:
1.210 paf 1319: int state=0;
1320: int save=0;
1321: result_size=
1.266 misha 1322: g_mime_utils_base64_decode_step ((const unsigned char*)in, in_size,
1323: (unsigned char*)result, &state, &save, strict);
1.264 misha 1324: assert(result_size <= new_size);
1.211 paf 1325: result[result_size]=0; // for text files
1.265 misha 1326:
1327: if(strict && state!=0)
1.266 misha 1328: throw Exception(BASE64_FORMAT, 0, "Unexpected end of chars");
1.210 paf 1329: }
1.218 misha 1330:
1331:
1.221 misha 1332: int file_block_read(const int f, unsigned char* buffer, const size_t size){
1333: int nCount = read(f, buffer, size);
1334: if (nCount < 0)
1.238 misha 1335: throw Exception("file.read",
1.221 misha 1336: 0,
1337: "read failed: %s (%d)", strerror(errno), errno);
1338: return nCount;
1339: }
1340:
1.239 misha 1341: const unsigned long pa_crc32(const char *in, size_t in_size){
1.218 misha 1342: unsigned long crc32=0xFFFFFFFF;
1.220 misha 1343:
1.240 misha 1344: InitCrc32Table();
1.239 misha 1345: for(size_t i = 0; i<in_size; i++)
1346: CalcCrc32(in[i], crc32);
1.220 misha 1347:
1.218 misha 1348: return ~crc32;
1349: }
1350:
1.239 misha 1351: const unsigned long pa_crc32(const String& file_spec){
1.218 misha 1352: unsigned long crc32=0xFFFFFFFF;
1353: file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
1354: return ~crc32;
1355: }
1356:
1357: static void file_crc32_file_action(
1.229 misha 1358: struct stat& finfo,
1359: int f,
1360: const String&, const char* /*fname*/, bool,
1.239 misha 1361: void *context) {
1.218 misha 1362: unsigned long& crc32=*static_cast<unsigned long *>(context);
1363: if(finfo.st_size) {
1364: InitCrc32Table();
1.220 misha 1365: int nCount=0;
1.218 misha 1366: do {
1.221 misha 1367: unsigned char buffer[FILE_BUFFER_SIZE];
1368: nCount = file_block_read(f, buffer, sizeof(buffer));
1.220 misha 1369: for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
1370: } while(nCount > 0);
1.218 misha 1371: }
1372: }
1373:
E-mail: