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