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