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