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