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