Annotation of parser3/src/main/pa_common.C, revision 1.179
1.15 paf 1: /** @file
1.16 paf 2: Parser: commonly functions.
3:
1.174 paf 4: Copyright(c) 2001-2004 ArtLebedev Group (http://www.artlebedev.com)
1.101 paf 5: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.111 paf 6: */
1.16 paf 7:
1.179 ! paf 8: static const char * const IDENT_COMMON_C="$Date: 2004/03/05 11:38:12 $";
1.1 paf 9:
10: #include "pa_common.h"
1.4 paf 11: #include "pa_exception.h"
1.154 paf 12: #include "pa_hash.h"
1.14 paf 13: #include "pa_globals.h"
1.154 paf 14: #include "pa_request_charsets.h"
15: #include "pa_charsets.h"
16:
17: #define PA_HTTP
18:
19: #ifdef PA_HTTP
1.126 paf 20: #include "pa_vstring.h"
1.154 paf 21: #include "pa_vint.h"
1.155 paf 22: #include "pa_vhash.h"
23: #include "pa_vtable.h"
1.154 paf 24:
25: #ifdef CYGWIN
26: #define _GNU_H_WINDOWS32_SOCKETS
27: // for PASCAL
28: #include <windows.h>
29: // SOCKET
30: typedef u_int SOCKET;
31: int PASCAL closesocket(SOCKET);
32: #else
33: # if defined(WIN32)
34: # include <windows.h>
35: # else
36: # define closesocket close
37: # endif
38: #endif
1.1 paf 39:
1.126 paf 40: #else
1.154 paf 41:
42: # if defined(WIN32)
43: # include <windows.h>
44: # endif
45:
1.98 paf 46: #endif
47:
1.93 paf 48: // some maybe-undefined constants
49:
1.82 paf 50: #ifndef _O_TEXT
51: # define _O_TEXT 0
52: #endif
53: #ifndef _O_BINARY
54: # define _O_BINARY 0
1.47 paf 55: #endif
1.80 paf 56:
1.138 paf 57: #ifdef HAVE_FTRUNCATE
58: # define PA_O_TRUNC 0
59: #else
60: # ifdef _O_TRUNC
61: # define PA_O_TRUNC _O_TRUNC
62: # else
63: # error you must have either ftruncate function or _O_TRUNC bit declared
64: # endif
1.154 paf 65: #endif
1.176 paf 66:
67: # ifndef INADDR_NONE
68: # define INADDR_NONE ((ulong) -1)
69: # endif
1.154 paf 70:
71: // defines for globals
72:
73: #define FILE_STATUS_NAME "status"
74:
75: // globals
76:
77: const String file_status_name(FILE_STATUS_NAME);
78:
1.178 paf 79: // defines
1.154 paf 80:
81: #define HTTP_METHOD_NAME "method"
82: #define HTTP_TIMEOUT_NAME "timeout"
83: #define HTTP_HEADERS_NAME "headers"
84: #define HTTP_ANY_STATUS_NAME "any-status"
85: #define HTTP_CHARSET_NAME "charset"
1.155 paf 86: #define HTTP_TABLES_NAME "tables"
1.178 paf 87: #define HTTP_USER "user"
88: #define HTTP_PASSWORD "password"
1.154 paf 89:
90: // defines
91:
1.127 paf 92: #define DEFAULT_USER_AGENT "parser3"
93:
1.154 paf 94: // functions
1.127 paf 95:
1.154 paf 96: void fix_line_breaks(char *str, size_t& length) {
1.87 paf 97: //_asm int 3;
1.154 paf 98: const char* const eob=str+length;
99: char* dest=str;
1.72 parser 100: // fix DOS: \r\n -> \n
101: // fix Macintosh: \r -> \n
1.154 paf 102: char* bol=str;
1.137 paf 103: while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72 parser 104: size_t len=eol-bol;
105: if(dest!=bol)
1.126 paf 106: memcpy(dest, bol, len);
1.72 parser 107: dest+=len;
1.126 paf 108: *dest++='\n';
1.72 parser 109:
1.126 paf 110: if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72 parser 111: bol=eol+2;
1.154 paf 112: length--;
1.126 paf 113: } else // \r, not \n = Macintosh
1.72 parser 114: bol=eol+1;
115: }
1.154 paf 116: // last piece without \r
1.72 parser 117: if(dest!=bol)
1.126 paf 118: memcpy(dest, bol, eob-bol);
1.154 paf 119: str[length]=0; // terminating
1.72 parser 120: }
1.18 paf 121:
1.154 paf 122: char* file_read_text(Request_charsets& charsets,
123: const String& file_spec,
124: bool fail_on_read_problem,
125: HashStringValue* params/*, HashStringValue* * out_fields*/) {
126: File_read_result file=
127: file_read(charsets, file_spec, true, params, fail_on_read_problem);
128: return file.success?file.str:0;
1.126 paf 129: }
130:
1.178 paf 131: //http request stuff
1.154 paf 132: #ifdef PA_HTTP
133:
134: #undef CRLF
135: #define CRLF "\r\n"
1.126 paf 136:
137: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
138: memset(addr, 0, sizeof(*addr));
139: addr->sin_family=AF_INET;
140: addr->sin_port=htons(port);
141: if(host) {
1.175 paf 142: ulong packed_ip=inet_addr(host);
143: struct hostent *hostIP = packed_ip==INADDR_NONE?
144: gethostbyname(host)
145: : gethostbyaddr((char *)&packed_ip, sizeof(packed_ip), AF_INET);
146: if(hostIP)
1.126 paf 147: memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length);
148: else
149: return false;
150: } else
151: addr->sin_addr.s_addr=INADDR_ANY;
152: return true;
153: }
154:
1.171 paf 155: static int http_read_response(char*& response, size_t& response_size, int sock, bool fail_on_status_ne_200){
156: response=(char*)pa_malloc_atomic(1/*terminator*/); // setting memory block type
157: response[(response_size=0)]=0;
1.154 paf 158: int result=0;
1.171 paf 159: char* EOLat=0;
1.126 paf 160: while(true) {
1.171 paf 161: char buf[MAX_STRING*10];
162: ssize_t received_size=recv(sock, buf, sizeof(buf), 0);
163: if(received_size<=0)
1.126 paf 164: break;
1.171 paf 165: response=(char*)pa_realloc(response, response_size+received_size+1/*terminator*/);
166: memcpy(response+response_size, buf, received_size);
167: response_size+=received_size;
168: response[response_size]=0;
169:
170: if(!result && (EOLat=strstr(response, CRLF))) { // checking status in first response
171: const String status_line(pa_strdup(response, EOLat-response));
1.154 paf 172: ArrayString astatus;
173: size_t pos_after=0;
174: status_line.split(astatus, pos_after, " ");
175: const String& status_code=*astatus.get(1);
176: result=status_code.as_int();
1.142 paf 177:
1.154 paf 178: if(fail_on_status_ne_200 && result!=200)
1.142 paf 179: throw Exception("http.status",
1.154 paf 180: &status_code,
1.142 paf 181: "invalid HTTP response status");
182: }
183: }
1.154 paf 184: if(result)
185: return result;
1.142 paf 186: else
187: throw Exception("http.response",
188: 0,
1.173 paf 189: "bad response from host - no status found (size=%u)", response_size);
1.126 paf 190: }
191:
192: /* ********************** request *************************** */
193:
194: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
1.145 paf 195: # define PA_USE_ALARM
1.126 paf 196: #endif
197:
1.145 paf 198: #ifdef PA_USE_ALARM
1.126 paf 199: static sigjmp_buf timeout_env;
200: static void timeout_handler(int sig){
201: siglongjmp(timeout_env, 1);
202: }
203: #endif
204:
1.171 paf 205: static int http_request(char*& response, size_t& response_size,
1.152 paf 206: const char* host, int port,
207: const char* request,
1.166 paf 208: int
209: #ifdef PA_USE_ALARM
210: timeout
211: #endif
212: ,
1.152 paf 213: bool fail_on_status_ne_200) {
1.126 paf 214: if(!host)
215: throw Exception("http.host",
1.154 paf 216: 0,
1.126 paf 217: "zero hostname"); //never
218:
1.145 paf 219: #ifdef PA_USE_ALARM
1.146 paf 220: signal(SIGALRM, timeout_handler);
1.126 paf 221: #endif
222: int sock=-1;
1.145 paf 223: #ifdef PA_USE_ALARM
224: if(sigsetjmp(timeout_env, 1)) {
225: // stupid gcc [2.95.4] generated bad code
226: // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
227: // rewritten simplier [though duplicating closesocket code]
228: if(sock>=0)
229: closesocket(sock);
230: throw Exception("http.timeout",
231: origin_string,
232: "timeout occured while retrieving document");
1.146 paf 233: return 0; // never
1.145 paf 234: } else {
235: alarm(timeout);
236: #endif
1.146 paf 237: try {
238: int result;
1.126 paf 239: struct sockaddr_in dest;
1.154 paf 240:
241: if(!set_addr(&dest, host, port))
1.126 paf 242: throw Exception("http.host",
1.154 paf 243: 0,
1.127 paf 244: "can not resolve hostname \"%s\"", host);
1.126 paf 245:
246: if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0)
247: throw Exception("http.connect",
1.154 paf 248: 0,
1.127 paf 249: "can not make socket: %s (%d)", strerror(errno), errno);
1.126 paf 250: if(connect(sock, (struct sockaddr *)&dest, sizeof(dest)))
251: throw Exception("http.connect",
1.154 paf 252: 0,
1.127 paf 253: "can not connect to host \"%s\": %s (%d)", host, strerror(errno), errno);
1.126 paf 254: size_t request_size=strlen(request);
255: if(send(sock, request, request_size, 0)!=(ssize_t)request_size)
256: throw Exception("http.connect",
1.154 paf 257: 0,
1.127 paf 258: "error sending request: %s (%d)", strerror(errno), errno);
1.126 paf 259:
1.171 paf 260: result=http_read_response(response, response_size, sock, fail_on_status_ne_200);
1.142 paf 261: closesocket(sock);
1.145 paf 262: #ifdef PA_USE_ALARM
1.142 paf 263: alarm(0);
1.126 paf 264: #endif
1.147 paf 265: return result;
1.146 paf 266: } catch(...) {
1.145 paf 267: #ifdef PA_USE_ALARM
1.146 paf 268: alarm(0);
1.126 paf 269: #endif
1.146 paf 270: if(sock>=0)
271: closesocket(sock);
1.154 paf 272: rethrow;
1.146 paf 273: }
1.148 paf 274: #ifdef PA_USE_ALARM
1.126 paf 275: }
1.148 paf 276: #endif
1.126 paf 277: }
278:
1.127 paf 279: #ifndef DOXYGEN
280: struct Http_pass_header_info {
1.154 paf 281: Request_charsets* charsets;
1.127 paf 282: String* request;
283: bool user_agent_specified;
284: };
285: #endif
1.154 paf 286: static void http_pass_header(HashStringValue::key_type key,
287: HashStringValue::value_type value,
288: Http_pass_header_info *info) {
289: *info->request <<key<<": "
290: << attributed_meaning_to_string(*value, String::L_HTTP_HEADER, false)
291: << CRLF;
1.135 paf 292:
1.154 paf 293: if(String(key, String::L_TAINTED).change_case(info->charsets->source(), String::CC_UPPER)=="USER-AGENT")
294: info->user_agent_specified=true;
1.126 paf 295: }
1.154 paf 296:
297:
298: static Charset* detect_charset(Charset& source_charset, const String& content_type_value) {
1.156 paf 299: const String::Body CONTENT_TYPE_VALUE=
1.154 paf 300: content_type_value.change_case(source_charset, String::CC_UPPER);
301: // content-type: xxx/xxx; source_charset=WE-NEED-THIS
302: // content-type: xxx/xxx; source_charset="WE-NEED-THIS"
303: // content-type: xxx/xxx; source_charset="WE-NEED-THIS";
304: size_t before_charseteq_pos=CONTENT_TYPE_VALUE.pos("CHARSET=");
305: if(before_charseteq_pos!=STRING_NOT_FOUND) {
306: size_t charset_begin=before_charseteq_pos+8/*CHARSET="*/;
307: size_t open_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
308: bool quoted=open_quote_pos==charset_begin;
309: if(quoted)
310: charset_begin++; // skip opening '"'
311: size_t charset_end=CONTENT_TYPE_VALUE.length();
312: if(quoted) {
313: size_t close_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
314: if(close_quote_pos!=STRING_NOT_FOUND)
315: charset_end=close_quote_pos;
316: } else {
317: size_t delim_pos=CONTENT_TYPE_VALUE.pos(';', charset_begin);
318: if(delim_pos!=STRING_NOT_FOUND)
319: charset_end=delim_pos;
320: }
1.156 paf 321: const String::Body CHARSET_NAME_BODY=
1.154 paf 322: CONTENT_TYPE_VALUE.mid(charset_begin, charset_end);
323:
324: return &charsets.get(CHARSET_NAME_BODY);
325: }
326:
327: return 0;
328: }
329:
1.178 paf 330: static const String* basic_authorization_field(const char* user, const char* pass) {
331: if(!user&& !pass)
332: return 0;
333:
334: String combined;
335: if(user)
336: combined<<user;
337: combined<<":";
338: if(pass)
339: combined<<pass;
340:
341: String* result=new String("Basic "); *result<<pa_base64(combined.cstr(), combined.length());
342: return result;
343: }
1.154 paf 344:
345: #ifndef DOXYGEN
346: struct File_read_http_result {
347: char *str; size_t length;
348: HashStringValue* headers;
349: };
350: #endif
1.155 paf 351: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.154 paf 352: static File_read_http_result file_read_http(Request_charsets& charsets,
353: const String& file_spec,
1.169 paf 354: bool as_text,
355: HashStringValue *options=0) {
1.154 paf 356: File_read_http_result result;
1.126 paf 357: char host[MAX_STRING];
1.129 paf 358: const char* uri;
1.126 paf 359: int port;
1.154 paf 360: const char* method=0;
1.126 paf 361: int timeout=2;
1.142 paf 362: bool fail_on_status_ne_200=true;
1.154 paf 363: Value* vheaders=0;
364: Charset *asked_remote_charset=0;
1.178 paf 365: const char* user_cstr=0;
366: const char* password_cstr=0;
1.126 paf 367:
1.127 paf 368: if(options) {
369: int valid_options=0;
1.177 paf 370: if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
1.127 paf 371: valid_options++;
1.154 paf 372: method=vmethod->as_string().cstr();
1.127 paf 373: }
1.177 paf 374: if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
1.127 paf 375: valid_options++;
376: timeout=vtimeout->as_int();
377: }
1.177 paf 378: if((vheaders=options->get(HTTP_HEADERS_NAME))) {
1.127 paf 379: valid_options++;
380: }
1.177 paf 381: if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
1.142 paf 382: valid_options++;
383: fail_on_status_ne_200=!vany_status->as_bool();
384: }
1.177 paf 385: if(Value* vcharset_name=options->get(HTTP_CHARSET_NAME)) {
1.154 paf 386: valid_options++;
387: asked_remote_charset=&::charsets.get(vcharset_name->as_string().
388: change_case(charsets.source(), String::CC_UPPER));
389: }
1.178 paf 390: if(Value* vuser=options->get(HTTP_USER)) {
391: valid_options++;
392: user_cstr=vuser->as_string().cstr();
393: }
394: if(Value* vpassword=options->get(HTTP_PASSWORD)) {
395: valid_options++;
396: password_cstr=vpassword->as_string().cstr();
397: }
1.142 paf 398:
1.154 paf 399: if(valid_options!=options->count())
1.127 paf 400: throw Exception("parser.runtime",
401: 0,
402: "invalid option passed");
1.154 paf 403: }
404: if(!asked_remote_charset) // defaulting to $request:charset
405: asked_remote_charset=&charsets.source();
406:
407: //preparing request
408: String& connect_string=*new String;
409: // not in ^sql{... L_SQL ...} spirit, but closer to ^file::load one
410: connect_string.append(file_spec, String::L_URI); // tainted pieces -> URI pieces
411:
412: const char* request_cstr;
413: {
414: // influence URLencoding of tainted pieces to String::L_URI lang
415: Temp_client_charset temp(charsets, *asked_remote_charset);
416:
417: const char* connect_string_cstr=connect_string.cstr(String::L_UNSPECIFIED);
1.126 paf 418:
1.154 paf 419: const char* current=connect_string_cstr;
420: if(strncmp(current, "http://", 7)!=0)
421: throw Exception(0,
422: &connect_string,
423: "does not start with http://"); //never
424: current+=7;
425:
426: strncpy(host, current, sizeof(host)-1); host[sizeof(host)-1]=0;
427: char* host_uri=lsplit(host, '/');
428: uri=host_uri?current+(host_uri-1-host):"/";
429: char* port_cstr=lsplit(host, ':');
430: char* error_pos=0;
431: port=port_cstr?strtol(port_cstr, &error_pos, 0):80;
432:
433: //making request
434: String request;
435: if(method)
436: request<<method;
437: else
438: request<<"GET";
439: request<< " "<< uri <<" HTTP/1.0" CRLF
440: "host: "<< host << CRLF;
1.178 paf 441:
1.179 ! paf 442: // http://www.ietf.org/rfc/rfc2617.txt
1.178 paf 443: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
444: request<<"Authorization: "<<*authorization_field_value<<CRLF;
445:
1.154 paf 446: bool user_agent_specified=false;
447: if(vheaders && !vheaders->is_string()) { // allow empty
448: if(HashStringValue *headers=vheaders->get_hash()) {
1.167 paf 449: Http_pass_header_info info={&charsets, &request, false};
1.154 paf 450: headers->for_each(http_pass_header, &info);
451: user_agent_specified=info.user_agent_specified;
452: } else
453: throw Exception("parser.runtime",
454: &connect_string,
455: "headers param must be hash");
456: };
457: if(!user_agent_specified) // defaulting
458: request << "user-agent: " DEFAULT_USER_AGENT CRLF;
459: request << CRLF;
460:
461: request_cstr=request.cstr(String::L_UNSPECIFIED);
462: }
463: // recode those pieces which are not in String::L_URI lang
464: // [those violating HTTP standard, but widly used]
465: request_cstr=Charset::transcode(
466: String::C(request_cstr, strlen(request_cstr)),
467: charsets.source(),
468: *asked_remote_charset);
1.126 paf 469:
470: //sending request
1.171 paf 471: char* response;
472: size_t response_size;
473: int status_code=http_request(response, response_size,
1.154 paf 474: host, port, request_cstr,
1.142 paf 475: timeout, fail_on_status_ne_200);
1.126 paf 476:
477: //processing results
1.171 paf 478: char* raw_body; size_t raw_body_size;
479: char* headers_end_at=strstr(response, CRLF CRLF /*change '4' below along!*/);
480: if(headers_end_at) {
481: raw_body=headers_end_at+4;
482: raw_body_size=response_size-(raw_body-response);
483: } else
1.126 paf 484: throw Exception("http.response",
1.133 paf 485: &connect_string,
1.126 paf 486: "bad response from host - no headers found");
1.171 paf 487:
488: *headers_end_at=0;
489: const String header_block(response, headers_end_at-response, true);
1.126 paf 490:
1.154 paf 491: ArrayString aheaders;
492: result.headers=new HashStringValue;
1.155 paf 493: VHash* vtables=new VHash;
1.177 paf 494: result.headers->put(HTTP_TABLES_NAME, vtables);
1.155 paf 495: HashStringValue& tables=vtables->hash();
496:
1.154 paf 497: size_t pos_after=0;
498: header_block.split(aheaders, pos_after, CRLF);
1.126 paf 499:
500: //processing headers
1.154 paf 501: size_t aheaders_count=aheaders.count();
502: Charset* real_remote_charset=0; // undetected, yet
503: for(size_t i=1; i<aheaders_count; i++) {
504: const String& line=*aheaders.get(i);
1.171 paf 505: size_t pos=line.pos(": ", 2);
1.154 paf 506: if(pos==STRING_NOT_FOUND || pos<1)
1.126 paf 507: throw Exception("http.response",
1.154 paf 508: &connect_string,
509: "bad response from host - bad header \"%s\"", line.cstr());
1.156 paf 510: const String::Body HEADER_NAME=
1.154 paf 511: line.mid(0, pos).change_case(charsets.source(), String::CC_UPPER);
512: const String& header_value=line.mid(pos+2, line.length());
513: if(HEADER_NAME=="CONTENT-TYPE")
514: real_remote_charset=detect_charset(charsets.source(), header_value);
1.155 paf 515:
516: // tables
517: {
518: Value *valready=(Value *)tables.get(HEADER_NAME);
519: bool existed=valready!=0;
520: Table *table;
521: if(existed) {
522: // second+ appearence
523: table=valready->get_table();
524: } else {
525: // first appearence
526: Table::columns_type columns =new ArrayString(1);
527: *columns+=new String("value");
528: table=new Table(columns);
529: }
530: // this string becomes next row
531: ArrayString& row=*new ArrayString(1);
532: row+=&header_value;
533: *table+=&row;
534: // not existed before? add it
535: if(!existed)
536: tables.put(HEADER_NAME, new VTable(table));
537: }
538:
1.154 paf 539: result.headers->put(HEADER_NAME, new VString(header_value));
1.126 paf 540: }
1.154 paf 541: // defaulting to used-asked charset [it's never empty!]
542: if(!real_remote_charset)
543: real_remote_charset=asked_remote_charset;
1.126 paf 544:
545: // output response
1.171 paf 546: String::C real_body=String::C(raw_body, raw_body_size);
547: if(as_text && raw_body_size) // must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
1.169 paf 548: real_body=Charset::transcode(real_body, *real_remote_charset, charsets.source());
1.154 paf 549:
550: result.str=const_cast<char *>(real_body.str); // hacking a little
551: result.length=real_body.length;
552: result.headers->put(file_status_name, new VInt(status_code));
553: return result;
1.34 paf 554: }
1.123 paf 555:
1.154 paf 556: #endif
557:
1.123 paf 558: #ifndef DOXYGEN
559: struct File_read_action_info {
1.154 paf 560: char **data; size_t *data_size;
1.126 paf 561: };
1.123 paf 562: #endif
1.154 paf 563: static void file_read_action(
564: struct stat& finfo,
565: int f,
1.166 paf 566: const String& file_spec, const char* /*fname*/, bool as_text,
1.154 paf 567: void *context) {
1.126 paf 568: File_read_action_info& info=*static_cast<File_read_action_info *>(context);
1.123 paf 569: if(size_t to_read_size=(size_t)finfo.st_size) {
1.154 paf 570: *info.data=new(PointerFreeGC) char[to_read_size+(as_text?1:0)];
1.126 paf 571: *info.data_size=(size_t)read(f, *info.data, to_read_size);
1.123 paf 572:
573: if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126 paf 574: throw Exception(0,
1.123 paf 575: &file_spec,
1.173 paf 576: "read failed: actually read %u bytes count not in [0..%u] valid range",
1.126 paf 577: *info.data_size, to_read_size);
1.123 paf 578: } else { // empty file
579: if(as_text) {
1.154 paf 580: *info.data=new(PointerFreeGC) char[1];
1.123 paf 581: *(char*)(*info.data)=0;
582: } else
583: *info.data=0;
584: *info.data_size=0;
585: return;
586: }
1.126 paf 587: }
1.154 paf 588: File_read_result file_read(Request_charsets& charsets, const String& file_spec,
589: bool as_text, HashStringValue *params,
1.126 paf 590: bool fail_on_read_problem) {
1.167 paf 591: File_read_result result={false, 0, 0, 0};
1.154 paf 592: #ifdef PA_HTTP
593: if(file_spec.starts_with("http://")) {
1.126 paf 594: // fail on read problem
1.169 paf 595: File_read_http_result http=file_read_http(charsets, file_spec, as_text, params);
1.154 paf 596: result.success=true;
597: result.str=http.str;
598: result.length=http.length;
599: result.headers=http.headers;
1.126 paf 600: } else {
1.154 paf 601: #endif
1.161 paf 602: if(params && params->count())
603: throw Exception("parser.runtime",
604: 0,
605: "invalid option passed");
606:
1.154 paf 607: File_read_action_info info={&result.str, &result.length};
608: result.success=file_read_action_under_lock(file_spec,
1.126 paf 609: "read", file_read_action, &info,
610: as_text, fail_on_read_problem);
1.154 paf 611: #ifdef PA_HTTP
1.126 paf 612: }
1.154 paf 613: #endif
1.123 paf 614:
1.154 paf 615: if(result.success && as_text) {
1.131 paf 616: // UTF-8 signature: EF BB BF
1.154 paf 617: if(result.length>=3) {
618: char *in=(char *)result.str;
1.159 paf 619: if(strncmp(in, "\xEF\xBB\xBF", 3)==0) {
1.154 paf 620: result.str=in+3; result.length-=3;// skip prefix
1.131 paf 621: }
622: }
623:
1.154 paf 624: fix_line_breaks((char *)(result.str), result.length);
1.123 paf 625: }
1.126 paf 626:
627: return result;
1.123 paf 628: }
629:
1.154 paf 630: #ifdef PA_SAFE_MODE
631: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) {
632: if(finfo.st_uid/*foreign?*/!=geteuid()
633: && finfo.st_gid/*foreign?*/!=getegid())
634: throw Exception("parser.runtime",
635: &file_spec,
636: "parser is in safe mode: "
637: "reading files of foreign group and user disabled "
638: "[recompile parser with --disable-safe-mode configure option], "
639: "actual filename '%s', "
640: "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",
641: fname,
642: finfo.st_uid, geteuid(),
643: finfo.st_gid, getegid());
644: }
645: #endif
1.149 paf 646:
1.154 paf 647: bool file_read_action_under_lock(const String& file_spec,
1.126 paf 648: const char* action_name, File_read_action action, void *context,
649: bool as_text,
1.123 paf 650: bool fail_on_read_problem) {
1.154 paf 651: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.33 paf 652: int f;
653:
654: // first open, next stat:
1.45 paf 655: // directory update of NTFS hard links performed on open.
1.33 paf 656: // ex:
657: // a.html:^test[] and b.html hardlink to a.html
658: // user inserts ! before ^test in a.html
1.126 paf 659: // directory entry of b.html in NTFS not updated at once,
1.35 paf 660: // they delay update till open, so we would receive "!^test[" string
661: // if would do stat, next open.
1.123 paf 662: // later: it seems, even this does not help sometimes
1.98 paf 663: if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123 paf 664: try {
1.162 paf 665: if(pa_lock_shared_blocking(f)!=0)
1.126 paf 666: throw Exception("file.lock",
1.123 paf 667: &file_spec,
668: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 669: strerror(errno), errno, fname);
1.123 paf 670:
1.124 paf 671: struct stat finfo;
672: if(stat(fname, &finfo)!=0)
673: throw Exception("file.missing", // hardly possible: we just opened it OK
674: &file_spec,
675: "stat failed: %s (%d), actual filename '%s'",
1.154 paf 676: strerror(errno), errno, fname);
1.124 paf 677:
1.140 paf 678: #ifdef PA_SAFE_MODE
1.149 paf 679: check_safe_mode(finfo, file_spec, fname);
1.105 paf 680: #endif
1.32 paf 681:
1.154 paf 682: action(finfo, f, file_spec, fname, as_text, context);
1.123 paf 683: } catch(...) {
1.162 paf 684: pa_unlock(f);close(f);
1.123 paf 685: if(fail_on_read_problem)
1.154 paf 686: rethrow;
1.123 paf 687: return false;
688: }
1.87 paf 689:
1.162 paf 690: pa_unlock(f);close(f);
1.72 parser 691: return true;
1.118 paf 692: } else {
693: if(fail_on_read_problem)
1.126 paf 694: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.118 paf 695: &file_spec,
1.123 paf 696: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 697: action_name, strerror(errno), errno, fname);
1.118 paf 698: return false;
699: }
1.8 paf 700: }
701:
1.63 parser 702: static void create_dir_for_file(const String& file_spec) {
703: size_t pos_after=1;
1.154 paf 704: size_t pos_before;
705: while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
706: mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775);
1.63 parser 707: pos_after=pos_before+1;
708: }
709: }
710:
1.98 paf 711: bool file_write_action_under_lock(
1.28 paf 712: const String& file_spec,
1.126 paf 713: const char* action_name, File_write_action action, void *context,
714: bool as_text,
715: bool do_append,
716: bool do_block,
1.110 paf 717: bool fail_on_lock_problem) {
1.154 paf 718: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.28 paf 719: int f;
1.80 paf 720: if(access(fname, W_OK)!=0) // no
1.126 paf 721: create_dir_for_file(file_spec);
1.50 paf 722:
1.80 paf 723: if((f=open(fname,
724: O_CREAT|O_RDWR
725: |(as_text?_O_TEXT:_O_BINARY)
1.138 paf 726: |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162 paf 727: if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126 paf 728: Exception e("file.lock",
1.110 paf 729: &file_spec,
730: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 731: strerror(errno), errno, fname);
1.126 paf 732: close(f);
1.110 paf 733: if(fail_on_lock_problem)
734: throw e;
1.98 paf 735: return false;
736: }
1.96 paf 737:
1.158 paf 738: try {
1.126 paf 739: action(f, context);
1.158 paf 740: } catch(...) {
1.138 paf 741: #ifdef HAVE_FTRUNCATE
1.104 paf 742: if(!do_append)
1.125 paf 743: ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138 paf 744: #endif
1.162 paf 745: pa_unlock(f);close(f);
1.154 paf 746: rethrow;
1.158 paf 747: }
1.80 paf 748:
1.138 paf 749: #ifdef HAVE_FTRUNCATE
1.104 paf 750: if(!do_append)
1.125 paf 751: 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 752: #endif
1.162 paf 753: pa_unlock(f);close(f);
1.98 paf 754: return true;
1.80 paf 755: } else
1.126 paf 756: throw Exception(errno==EACCES?"file.access":0,
1.80 paf 757: &file_spec,
1.96 paf 758: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 759: action_name, strerror(errno), errno, fname);
1.96 paf 760: // here should be nothing, see rethrow above
761: }
762:
763: #ifndef DOXYGEN
764: struct File_write_action_info {
1.154 paf 765: const char* str; size_t length;
1.126 paf 766: };
1.96 paf 767: #endif
768: static void file_write_action(int f, void *context) {
1.126 paf 769: File_write_action_info& info=*static_cast<File_write_action_info *>(context);
1.154 paf 770: if(info.length) {
771: int written=write(f, info.str, info.length);
1.116 paf 772: if(written<0)
1.126 paf 773: throw Exception(0,
774: 0,
775: "write failed: %s (%d)", strerror(errno), errno);
1.113 paf 776: }
1.96 paf 777: }
778: void file_write(
779: const String& file_spec,
1.154 paf 780: const char* data, size_t size,
1.126 paf 781: bool as_text,
1.96 paf 782: bool do_append) {
1.126 paf 783: File_write_action_info info={data, size};
1.98 paf 784: file_write_action_under_lock(
1.154 paf 785: file_spec,
786: "write", file_write_action, &info,
787: as_text,
788: do_append);
1.30 paf 789: }
790:
1.63 parser 791: // throws nothing! [this is required in file_move & file_delete]
1.50 paf 792: static void rmdir(const String& file_spec, size_t pos_after) {
1.154 paf 793: size_t pos_before;
794: if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126 paf 795: rmdir(file_spec, pos_before+1);
1.50 paf 796:
1.154 paf 797: rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC));
1.50 paf 798: }
1.164 paf 799: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.154 paf 800: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.54 parser 801: if(unlink(fname)!=0)
1.164 paf 802: if(fail_on_problem)
1.126 paf 803: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.93 paf 804: &file_spec,
805: "unlink failed: %s (%d), actual filename '%s'",
1.154 paf 806: strerror(errno), errno, fname);
1.93 paf 807: else
808: return false;
1.50 paf 809:
1.126 paf 810: rmdir(file_spec, 1);
1.93 paf 811: return true;
1.60 parser 812: }
1.95 paf 813: void file_move(const String& old_spec, const String& new_spec) {
1.154 paf 814: const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC);
815: const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC);
1.63 parser 816:
1.126 paf 817: create_dir_for_file(new_spec);
1.63 parser 818:
1.60 parser 819: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 820: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.60 parser 821: &old_spec,
822: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.154 paf 823: strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 824:
1.126 paf 825: rmdir(old_spec, 1);
1.31 paf 826: }
827:
1.51 paf 828:
1.126 paf 829: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 830: struct stat lfinfo;
831: bool result=stat(fname, &lfinfo)==0;
832: if(afinfo)
833: *afinfo=lfinfo;
834: return result;
1.119 paf 835: }
836:
837: bool entry_exists(const String& file_spec) {
1.154 paf 838: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.126 paf 839: return entry_exists(fname, 0);
1.118 paf 840: }
841:
1.51 paf 842: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154 paf 843: char* fname=file_spec.cstrm(String::L_FILE_SPEC);
1.120 paf 844: if(need_dir) {
1.126 paf 845: size_t size=strlen(fname);
1.120 paf 846: while(size) {
1.126 paf 847: char c=fname[size-1];
1.120 paf 848: if(c=='/' || c=='\\')
849: fname[--size]=0;
850: else
851: break;
852: }
853: }
1.51 paf 854: struct stat finfo;
1.118 paf 855: if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109 paf 856: bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51 paf 857: return is_dir==need_dir;
858: }
859: return false;
860: }
1.31 paf 861: bool file_readable(const String& file_spec) {
1.126 paf 862: return entry_readable(file_spec, false);
1.51 paf 863: }
864: bool dir_readable(const String& file_spec) {
1.126 paf 865: return entry_readable(file_spec, true);
1.65 parser 866: }
1.154 paf 867: const String* file_readable(const String& path, const String& name) {
868: String& result=*new String(path);
869: result << "/";
870: result << name;
871: return file_readable(result)?&result:0;
1.43 paf 872: }
873: bool file_executable(const String& file_spec) {
1.154 paf 874: return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44 paf 875: }
876:
1.64 parser 877: bool file_stat(const String& file_spec,
1.58 parser 878: size_t& rsize,
1.126 paf 879: time_t& ratime,
880: time_t& rmtime,
881: time_t& rctime,
1.64 parser 882: bool fail_on_read_problem) {
1.154 paf 883: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
884: struct stat finfo;
1.44 paf 885: if(stat(fname, &finfo)!=0)
1.64 parser 886: if(fail_on_read_problem)
1.126 paf 887: throw Exception("file.missing",
1.67 parser 888: &file_spec,
889: "getting file size failed: %s (%d), real filename '%s'",
1.154 paf 890: strerror(errno), errno, fname);
1.64 parser 891: else
892: return false;
1.58 parser 893: rsize=finfo.st_size;
894: ratime=finfo.st_atime;
895: rmtime=finfo.st_mtime;
896: rctime=finfo.st_ctime;
1.64 parser 897: return true;
1.18 paf 898: }
899:
1.126 paf 900: char* getrow(char* *row_ref, char delim) {
901: char* result=*row_ref;
1.8 paf 902: if(result) {
1.126 paf 903: *row_ref=strchr(result, delim);
1.8 paf 904: if(*row_ref)
905: *((*row_ref)++)=0;
906: else if(!*result)
907: return 0;
908: }
909: return result;
910: }
911:
1.126 paf 912: char* lsplit(char* string, char delim) {
1.23 paf 913: if(string) {
1.126 paf 914: char* v=strchr(string, delim);
1.8 paf 915: if(v) {
916: *v=0;
917: return v+1;
918: }
919: }
920: return 0;
921: }
922:
1.126 paf 923: char* lsplit(char* *string_ref, char delim) {
924: char* result=*string_ref;
925: char* next=lsplit(*string_ref, delim);
1.8 paf 926: *string_ref=next;
927: return result;
1.9 paf 928: }
929:
1.126 paf 930: char* rsplit(char* string, char delim) {
1.18 paf 931: if(string) {
1.126 paf 932: char* v=strrchr(string, delim);
1.18 paf 933: if(v) {
1.9 paf 934: *v=0;
935: return v+1;
936: }
937: }
938: return NULL;
1.10 paf 939: }
940:
1.37 paf 941: /// @todo less stupid type detection
1.154 paf 942: const char* format(double value, char* fmt) {
1.126 paf 943: char local_buf[MAX_NUMBER];
1.108 paf 944: size_t size;
945:
1.10 paf 946: if(fmt)
947: if(strpbrk(fmt, "diouxX"))
948: if(strpbrk(fmt, "ouxX"))
1.126 paf 949: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.10 paf 950: else
1.126 paf 951: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
1.10 paf 952: else
1.126 paf 953: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
1.10 paf 954: else
1.126 paf 955: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
1.10 paf 956:
1.154 paf 957: return pa_strdup(local_buf, size);
1.12 paf 958: }
959:
1.36 paf 960: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 961: #ifdef WIN32
962: do{
1.154 paf 963: int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 964: if(chunk_written<=0)
965: break;
966: size-=chunk_written;
1.36 paf 967: buf=((const char*)buf)+chunk_written;
1.126 paf 968: } while(size>0);
1.12 paf 969:
970: return size;
971: #else
1.126 paf 972: return fwrite(buf, 1, size, stdout);
1.12 paf 973: #endif
1.2 paf 974: }
1.14 paf 975:
1.154 paf 976: char* unescape_chars(const char* cp, int len) {
977: char* s=new(PointerFreeGC) char[len + 1];
1.14 paf 978: enum EscapeState {
1.33 paf 979: EscapeRest,
980: EscapeFirst,
1.14 paf 981: EscapeSecond
982: } escapeState=EscapeRest;
983: int escapedValue=0;
984: int srcPos=0;
985: int dstPos=0;
986: while(srcPos < len) {
1.126 paf 987: int ch=cp[srcPos];
1.14 paf 988: switch(escapeState) {
989: case EscapeRest:
990: if(ch=='%') {
991: escapeState=EscapeFirst;
992: } else if(ch=='+') {
1.126 paf 993: s[dstPos++]=' ';
1.14 paf 994: } else {
995: s[dstPos++]=ch;
996: }
997: break;
998: case EscapeFirst:
999: escapedValue=hex_value[ch] << 4;
1000: escapeState=EscapeSecond;
1001: break;
1002: case EscapeSecond:
1.126 paf 1003: escapedValue +=hex_value[ch];
1.14 paf 1004: s[dstPos++]=escapedValue;
1005: escapeState=EscapeRest;
1006: break;
1007: }
1.126 paf 1008: srcPos++;
1.14 paf 1009: }
1010: s[dstPos]=0;
1011: return s;
1.24 paf 1012: }
1013:
1014: #ifdef WIN32
1.126 paf 1015: void back_slashes_to_slashes(char* s) {
1.24 paf 1016: if(s)
1017: for(; *s; s++)
1018: if(*s=='\\')
1.126 paf 1019: *s='/';
1.24 paf 1020: }
1.42 paf 1021: /*
1.126 paf 1022: void slashes_to_back_slashes(char* s) {
1.42 paf 1023: if(s)
1024: for(; *s; s++)
1025: if(*s=='/')
1.126 paf 1026: *s='\\';
1.42 paf 1027: }
1028: */
1.24 paf 1029: #endif
1.41 paf 1030:
1.126 paf 1031: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41 paf 1032: while(true) {
1033: if(!(*s1)) {
1034: if(!(*s2))
1035: return true;
1036: else
1037: return !strict;
1038: } else if(!(*s2))
1039: return !strict;
1040: if(isalpha(*s1)) {
1041: if(tolower(*s1) !=tolower(*s2))
1042: return false;
1043: } else if((*s1) !=(*s2))
1044: return false;
1.126 paf 1045: s1++;
1046: s2++;
1.41 paf 1047: }
1.57 parser 1048: }
1049:
1.84 paf 1050: static bool isLeap(int year) {
1.57 parser 1051: return !(
1052: (year % 4) || ((year % 400) && !(year % 100))
1.126 paf 1053: );
1.57 parser 1054: }
1055:
1056: int getMonthDays(int year, int month) {
1057: int monthDays[]={
1.126 paf 1058: 31,
1059: isLeap(year) ? 29 : 28,
1060: 31,
1061: 30,
1062: 31,
1063: 30,
1064: 31,
1065: 31,
1066: 30,
1067: 31,
1068: 30,
1.57 parser 1069: 31
1.126 paf 1070: };
1071: return monthDays[month];
1.41 paf 1072: }
1.69 parser 1073:
1.126 paf 1074: void remove_crlf(char* start, char* end) {
1075: for(char* p=start; p<end; p++)
1.69 parser 1076: switch(*p) {
1.126 paf 1077: case '\n': *p='|'; break;
1078: case '\r': *p=' '; break;
1.69 parser 1079: }
1.91 paf 1080: }
1081:
1082:
1083: /// must be last in this file
1084: #undef vsnprintf
1.126 paf 1085: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 1086: if(!s)
1087: return 0;
1088:
1089: int r;
1090: // note: on win32& maybe somewhere else
1091: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
1092: --s;
1.172 paf 1093:
1094: // clients do not check for negative 's', feature: ignore such prints
1095: if((ssize_t)s<0)
1096: return 0;
1097:
1.91 paf 1098: #if _MSC_VER
1099: /*
1100: win32:
1101: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
1102:
1.154 paf 1103: if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91 paf 1104: */
1.126 paf 1105: r=_vsnprintf(b, s, f, l);
1.91 paf 1106: if(r<0)
1107: r=s;
1108: #else
1.126 paf 1109: r=vsnprintf(b, s, f, l);
1.91 paf 1110: /*
1111: solaris:
1112: man vsnprintf
1113:
1114: The snprintf() function returns the number of characters
1115: formatted, that is, the number of characters that would have
1116: been written to the buffer if it were large enough. If the
1117: value of n is 0 on a call to snprintf(), an unspecified
1118: value less than 1 is returned.
1119: */
1120:
1121: if(r<0)
1122: r=0;
1.167 paf 1123: else if((size_t)r>s)
1.91 paf 1124: r=s;
1125: #endif
1126: b[r]=0;
1127: return r;
1128: }
1129:
1.126 paf 1130: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 1131: va_list l;
1.126 paf 1132: va_start(l, f);
1133: int r=__vsnprintf(b, s, f, l);
1134: va_end(l);
1.91 paf 1135: return r;
1.178 paf 1136: }
1137:
1138: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
1139: /*
1140: * Authors: Michael Zucchi <notzed@helixcode.com>
1141: * Jeffrey Stedfast <fejj@helixcode.com>
1142: *
1143: * Copyright 2000 Helix Code, Inc. (www.helixcode.com)
1144: *
1145: * This program is free software; you can redistribute it and/or modify
1146: * it under the terms of the GNU General Public License as published by
1147: * the Free Software Foundation; either version 2 of the License, or
1148: * (at your option) any later version.
1149: *
1150: * This program is distributed in the hope that it will be useful,
1151: * but WITHOUT ANY WARRANTY; without even the implied warranty of
1152: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1153: * GNU General Public License for more details.
1154: *
1155: * You should have received a copy of the GNU General Public License
1156: * along with this program; if not, write to the Free Software
1157: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
1158: *
1159: */
1160: static char *base64_alphabet =
1161: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1162:
1163: /**
1164: * g_mime_utils_base64_encode_step:
1165: * @in: input stream
1166: * @inlen: length of the input
1167: * @out: output string
1168: * @state: holds the number of bits that are stored in @save
1169: * @save: leftover bits that have not yet been encoded
1170: *
1171: * Base64 encodes a chunk of data. Performs an 'encode step', only
1172: * encodes blocks of 3 characters to the output at a time, saves
1173: * left-over state in state and save (initialise to 0 on first
1174: * invocation).
1175: *
1176: * Returns the number of bytes encoded.
1177: **/
1178: static size_t
1179: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1180: {
1181: const register unsigned char *inptr;
1182: register unsigned char *outptr;
1183:
1184: if (inlen <= 0)
1185: return 0;
1186:
1187: inptr = in;
1188: outptr = out;
1189:
1190: if (inlen + ((unsigned char *)save)[0] > 2) {
1191: const unsigned char *inend = in + inlen - 2;
1192: register int c1 = 0, c2 = 0, c3 = 0;
1193: register int already;
1194:
1195: already = *state;
1196:
1197: switch (((char *)save)[0]) {
1198: case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
1199: case 2: c1 = ((unsigned char *)save)[1];
1200: c2 = ((unsigned char *)save)[2]; goto skip2;
1201: }
1202:
1203: /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
1204: while (inptr < inend) {
1205: c1 = *inptr++;
1206: skip1:
1207: c2 = *inptr++;
1208: skip2:
1209: c3 = *inptr++;
1210: *outptr++ = base64_alphabet [c1 >> 2];
1211: *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
1212: *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
1213: *outptr++ = base64_alphabet [c3 & 0x3f];
1214: /* this is a bit ugly ... */
1215: if ((++already) >= 19) {
1216: *outptr++ = '\n';
1217: already = 0;
1218: }
1219: }
1220:
1221: ((unsigned char *)save)[0] = 0;
1222: inlen = 2 - (inptr - inend);
1223: *state = already;
1224: }
1225:
1226: //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
1227:
1228: if (inlen > 0) {
1229: register char *saveout;
1230:
1231: /* points to the slot for the next char to save */
1232: saveout = & (((char *)save)[1]) + ((char *)save)[0];
1233:
1234: /* inlen can only be 0 1 or 2 */
1235: switch (inlen) {
1236: case 2: *saveout++ = *inptr++;
1237: case 1: *saveout++ = *inptr++;
1238: }
1239: ((char *)save)[0] += inlen;
1240: }
1241:
1242: /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
1243: (int)((char *)save)[0],
1244: (int)((char *)save)[1],
1245: (int)((char *)save)[2]));*/
1246:
1247: return (outptr - out);
1248: }
1249:
1250: /**
1251: * g_mime_utils_base64_encode_close:
1252: * @in: input stream
1253: * @inlen: length of the input
1254: * @out: output string
1255: * @state: holds the number of bits that are stored in @save
1256: * @save: leftover bits that have not yet been encoded
1257: *
1258: * Base64 encodes the input stream to the output stream. Call this
1259: * when finished encoding data with g_mime_utils_base64_encode_step to
1260: * flush off the last little bit.
1261: *
1262: * Returns the number of bytes encoded.
1263: **/
1264: static size_t
1265: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1266: {
1267: unsigned char *outptr = out;
1268: int c1, c2;
1269:
1270: if (inlen > 0)
1271: outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
1272:
1273: c1 = ((unsigned char *)save)[1];
1274: c2 = ((unsigned char *)save)[2];
1275:
1276: switch (((unsigned char *)save)[0]) {
1277: case 2:
1278: outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
1279: goto skip;
1280: case 1:
1281: outptr[2] = '=';
1282: skip:
1283: outptr[0] = base64_alphabet [c1 >> 2];
1284: outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
1285: outptr[3] = '=';
1286: outptr += 4;
1287: break;
1288: }
1289:
1290: *outptr++ = 0;
1291:
1292: *save = 0;
1293: *state = 0;
1294:
1295: return (outptr - out);
1296: }
1297:
1298: char* pa_base64(const char *in, size_t len)
1299: {
1300: /* wont go to more than 2x size (overly conservative) */
1301: char* result=new(PointerFreeGC) char[len * 2 + 6];
1302: int state=0;
1303: int save=0;
1304: size_t filled=g_mime_utils_base64_encode_close ((const unsigned char*)in, len,
1305: (unsigned char*)result, &state, &save);
1306: assert(filled <= len * 2 + 6);
1307:
1308: return result;
1.98 paf 1309: }
E-mail: