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