Annotation of parser3/src/main/pa_common.C, revision 1.185
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.185 ! paf 8: static const char * const IDENT_COMMON_C="$Date: 2004/04/06 10:00:11 $";
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.126 paf 649: };
1.123 paf 650: #endif
1.154 paf 651: static void file_read_action(
652: struct stat& finfo,
653: int f,
1.166 paf 654: const String& file_spec, const char* /*fname*/, bool as_text,
1.154 paf 655: void *context) {
1.126 paf 656: File_read_action_info& info=*static_cast<File_read_action_info *>(context);
1.123 paf 657: if(size_t to_read_size=(size_t)finfo.st_size) {
1.154 paf 658: *info.data=new(PointerFreeGC) char[to_read_size+(as_text?1:0)];
1.126 paf 659: *info.data_size=(size_t)read(f, *info.data, to_read_size);
1.123 paf 660:
661: if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126 paf 662: throw Exception(0,
1.123 paf 663: &file_spec,
1.173 paf 664: "read failed: actually read %u bytes count not in [0..%u] valid range",
1.126 paf 665: *info.data_size, to_read_size);
1.123 paf 666: } else { // empty file
667: if(as_text) {
1.154 paf 668: *info.data=new(PointerFreeGC) char[1];
1.123 paf 669: *(char*)(*info.data)=0;
670: } else
671: *info.data=0;
672: *info.data_size=0;
673: return;
674: }
1.126 paf 675: }
1.154 paf 676: File_read_result file_read(Request_charsets& charsets, const String& file_spec,
677: bool as_text, HashStringValue *params,
1.126 paf 678: bool fail_on_read_problem) {
1.167 paf 679: File_read_result result={false, 0, 0, 0};
1.154 paf 680: #ifdef PA_HTTP
681: if(file_spec.starts_with("http://")) {
1.126 paf 682: // fail on read problem
1.169 paf 683: File_read_http_result http=file_read_http(charsets, file_spec, as_text, params);
1.154 paf 684: result.success=true;
685: result.str=http.str;
686: result.length=http.length;
687: result.headers=http.headers;
1.126 paf 688: } else {
1.154 paf 689: #endif
1.161 paf 690: if(params && params->count())
691: throw Exception("parser.runtime",
692: 0,
693: "invalid option passed");
694:
1.154 paf 695: File_read_action_info info={&result.str, &result.length};
696: result.success=file_read_action_under_lock(file_spec,
1.126 paf 697: "read", file_read_action, &info,
698: as_text, fail_on_read_problem);
1.154 paf 699: #ifdef PA_HTTP
1.126 paf 700: }
1.154 paf 701: #endif
1.123 paf 702:
1.154 paf 703: if(result.success && as_text) {
1.131 paf 704: // UTF-8 signature: EF BB BF
1.154 paf 705: if(result.length>=3) {
706: char *in=(char *)result.str;
1.159 paf 707: if(strncmp(in, "\xEF\xBB\xBF", 3)==0) {
1.154 paf 708: result.str=in+3; result.length-=3;// skip prefix
1.131 paf 709: }
710: }
711:
1.154 paf 712: fix_line_breaks((char *)(result.str), result.length);
1.123 paf 713: }
1.126 paf 714:
715: return result;
1.123 paf 716: }
717:
1.154 paf 718: #ifdef PA_SAFE_MODE
719: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) {
720: if(finfo.st_uid/*foreign?*/!=geteuid()
721: && finfo.st_gid/*foreign?*/!=getegid())
722: throw Exception("parser.runtime",
723: &file_spec,
724: "parser is in safe mode: "
725: "reading files of foreign group and user disabled "
726: "[recompile parser with --disable-safe-mode configure option], "
727: "actual filename '%s', "
728: "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",
729: fname,
730: finfo.st_uid, geteuid(),
731: finfo.st_gid, getegid());
732: }
733: #endif
1.149 paf 734:
1.154 paf 735: bool file_read_action_under_lock(const String& file_spec,
1.126 paf 736: const char* action_name, File_read_action action, void *context,
737: bool as_text,
1.123 paf 738: bool fail_on_read_problem) {
1.154 paf 739: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.33 paf 740: int f;
741:
742: // first open, next stat:
1.45 paf 743: // directory update of NTFS hard links performed on open.
1.33 paf 744: // ex:
745: // a.html:^test[] and b.html hardlink to a.html
746: // user inserts ! before ^test in a.html
1.126 paf 747: // directory entry of b.html in NTFS not updated at once,
1.35 paf 748: // they delay update till open, so we would receive "!^test[" string
749: // if would do stat, next open.
1.123 paf 750: // later: it seems, even this does not help sometimes
1.98 paf 751: if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123 paf 752: try {
1.162 paf 753: if(pa_lock_shared_blocking(f)!=0)
1.126 paf 754: throw Exception("file.lock",
1.123 paf 755: &file_spec,
756: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 757: strerror(errno), errno, fname);
1.123 paf 758:
1.124 paf 759: struct stat finfo;
760: if(stat(fname, &finfo)!=0)
761: throw Exception("file.missing", // hardly possible: we just opened it OK
762: &file_spec,
763: "stat failed: %s (%d), actual filename '%s'",
1.154 paf 764: strerror(errno), errno, fname);
1.124 paf 765:
1.140 paf 766: #ifdef PA_SAFE_MODE
1.149 paf 767: check_safe_mode(finfo, file_spec, fname);
1.105 paf 768: #endif
1.32 paf 769:
1.154 paf 770: action(finfo, f, file_spec, fname, as_text, context);
1.123 paf 771: } catch(...) {
1.162 paf 772: pa_unlock(f);close(f);
1.123 paf 773: if(fail_on_read_problem)
1.154 paf 774: rethrow;
1.123 paf 775: return false;
776: }
1.87 paf 777:
1.162 paf 778: pa_unlock(f);close(f);
1.72 parser 779: return true;
1.118 paf 780: } else {
781: if(fail_on_read_problem)
1.126 paf 782: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.118 paf 783: &file_spec,
1.123 paf 784: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 785: action_name, strerror(errno), errno, fname);
1.118 paf 786: return false;
787: }
1.8 paf 788: }
789:
1.63 parser 790: static void create_dir_for_file(const String& file_spec) {
791: size_t pos_after=1;
1.154 paf 792: size_t pos_before;
793: while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
794: mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775);
1.63 parser 795: pos_after=pos_before+1;
796: }
797: }
798:
1.98 paf 799: bool file_write_action_under_lock(
1.28 paf 800: const String& file_spec,
1.126 paf 801: const char* action_name, File_write_action action, void *context,
802: bool as_text,
803: bool do_append,
804: bool do_block,
1.110 paf 805: bool fail_on_lock_problem) {
1.154 paf 806: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.28 paf 807: int f;
1.80 paf 808: if(access(fname, W_OK)!=0) // no
1.126 paf 809: create_dir_for_file(file_spec);
1.50 paf 810:
1.80 paf 811: if((f=open(fname,
812: O_CREAT|O_RDWR
813: |(as_text?_O_TEXT:_O_BINARY)
1.138 paf 814: |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162 paf 815: if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126 paf 816: Exception e("file.lock",
1.110 paf 817: &file_spec,
818: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 819: strerror(errno), errno, fname);
1.126 paf 820: close(f);
1.110 paf 821: if(fail_on_lock_problem)
822: throw e;
1.98 paf 823: return false;
824: }
1.96 paf 825:
1.158 paf 826: try {
1.126 paf 827: action(f, context);
1.158 paf 828: } catch(...) {
1.138 paf 829: #ifdef HAVE_FTRUNCATE
1.104 paf 830: if(!do_append)
1.125 paf 831: ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138 paf 832: #endif
1.162 paf 833: pa_unlock(f);close(f);
1.154 paf 834: rethrow;
1.158 paf 835: }
1.80 paf 836:
1.138 paf 837: #ifdef HAVE_FTRUNCATE
1.104 paf 838: if(!do_append)
1.125 paf 839: 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 840: #endif
1.162 paf 841: pa_unlock(f);close(f);
1.98 paf 842: return true;
1.80 paf 843: } else
1.126 paf 844: throw Exception(errno==EACCES?"file.access":0,
1.80 paf 845: &file_spec,
1.96 paf 846: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 847: action_name, strerror(errno), errno, fname);
1.96 paf 848: // here should be nothing, see rethrow above
849: }
850:
851: #ifndef DOXYGEN
852: struct File_write_action_info {
1.154 paf 853: const char* str; size_t length;
1.126 paf 854: };
1.96 paf 855: #endif
856: static void file_write_action(int f, void *context) {
1.126 paf 857: File_write_action_info& info=*static_cast<File_write_action_info *>(context);
1.154 paf 858: if(info.length) {
859: int written=write(f, info.str, info.length);
1.116 paf 860: if(written<0)
1.126 paf 861: throw Exception(0,
862: 0,
863: "write failed: %s (%d)", strerror(errno), errno);
1.113 paf 864: }
1.96 paf 865: }
866: void file_write(
867: const String& file_spec,
1.154 paf 868: const char* data, size_t size,
1.126 paf 869: bool as_text,
1.96 paf 870: bool do_append) {
1.126 paf 871: File_write_action_info info={data, size};
1.98 paf 872: file_write_action_under_lock(
1.154 paf 873: file_spec,
874: "write", file_write_action, &info,
875: as_text,
876: do_append);
1.30 paf 877: }
878:
1.63 parser 879: // throws nothing! [this is required in file_move & file_delete]
1.50 paf 880: static void rmdir(const String& file_spec, size_t pos_after) {
1.154 paf 881: size_t pos_before;
882: if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126 paf 883: rmdir(file_spec, pos_before+1);
1.50 paf 884:
1.154 paf 885: rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC));
1.50 paf 886: }
1.164 paf 887: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.154 paf 888: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.54 parser 889: if(unlink(fname)!=0)
1.164 paf 890: if(fail_on_problem)
1.126 paf 891: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.93 paf 892: &file_spec,
893: "unlink failed: %s (%d), actual filename '%s'",
1.154 paf 894: strerror(errno), errno, fname);
1.93 paf 895: else
896: return false;
1.50 paf 897:
1.126 paf 898: rmdir(file_spec, 1);
1.93 paf 899: return true;
1.60 parser 900: }
1.95 paf 901: void file_move(const String& old_spec, const String& new_spec) {
1.154 paf 902: const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC);
903: const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC);
1.63 parser 904:
1.126 paf 905: create_dir_for_file(new_spec);
1.63 parser 906:
1.60 parser 907: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 908: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.60 parser 909: &old_spec,
910: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.154 paf 911: strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 912:
1.126 paf 913: rmdir(old_spec, 1);
1.31 paf 914: }
915:
1.51 paf 916:
1.126 paf 917: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 918: struct stat lfinfo;
919: bool result=stat(fname, &lfinfo)==0;
920: if(afinfo)
921: *afinfo=lfinfo;
922: return result;
1.119 paf 923: }
924:
925: bool entry_exists(const String& file_spec) {
1.154 paf 926: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.126 paf 927: return entry_exists(fname, 0);
1.118 paf 928: }
929:
1.51 paf 930: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154 paf 931: char* fname=file_spec.cstrm(String::L_FILE_SPEC);
1.120 paf 932: if(need_dir) {
1.126 paf 933: size_t size=strlen(fname);
1.120 paf 934: while(size) {
1.126 paf 935: char c=fname[size-1];
1.120 paf 936: if(c=='/' || c=='\\')
937: fname[--size]=0;
938: else
939: break;
940: }
941: }
1.51 paf 942: struct stat finfo;
1.118 paf 943: if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109 paf 944: bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51 paf 945: return is_dir==need_dir;
946: }
947: return false;
948: }
1.31 paf 949: bool file_readable(const String& file_spec) {
1.126 paf 950: return entry_readable(file_spec, false);
1.51 paf 951: }
952: bool dir_readable(const String& file_spec) {
1.126 paf 953: return entry_readable(file_spec, true);
1.65 parser 954: }
1.154 paf 955: const String* file_readable(const String& path, const String& name) {
956: String& result=*new String(path);
957: result << "/";
958: result << name;
959: return file_readable(result)?&result:0;
1.43 paf 960: }
961: bool file_executable(const String& file_spec) {
1.154 paf 962: return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44 paf 963: }
964:
1.64 parser 965: bool file_stat(const String& file_spec,
1.58 parser 966: size_t& rsize,
1.126 paf 967: time_t& ratime,
968: time_t& rmtime,
969: time_t& rctime,
1.64 parser 970: bool fail_on_read_problem) {
1.154 paf 971: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
972: struct stat finfo;
1.44 paf 973: if(stat(fname, &finfo)!=0)
1.64 parser 974: if(fail_on_read_problem)
1.126 paf 975: throw Exception("file.missing",
1.67 parser 976: &file_spec,
977: "getting file size failed: %s (%d), real filename '%s'",
1.154 paf 978: strerror(errno), errno, fname);
1.64 parser 979: else
980: return false;
1.58 parser 981: rsize=finfo.st_size;
982: ratime=finfo.st_atime;
983: rmtime=finfo.st_mtime;
984: rctime=finfo.st_ctime;
1.64 parser 985: return true;
1.18 paf 986: }
987:
1.126 paf 988: char* getrow(char* *row_ref, char delim) {
989: char* result=*row_ref;
1.8 paf 990: if(result) {
1.126 paf 991: *row_ref=strchr(result, delim);
1.8 paf 992: if(*row_ref)
993: *((*row_ref)++)=0;
994: else if(!*result)
995: return 0;
996: }
997: return result;
998: }
999:
1.126 paf 1000: char* lsplit(char* string, char delim) {
1.23 paf 1001: if(string) {
1.126 paf 1002: char* v=strchr(string, delim);
1.8 paf 1003: if(v) {
1004: *v=0;
1005: return v+1;
1006: }
1007: }
1008: return 0;
1009: }
1010:
1.126 paf 1011: char* lsplit(char* *string_ref, char delim) {
1012: char* result=*string_ref;
1013: char* next=lsplit(*string_ref, delim);
1.8 paf 1014: *string_ref=next;
1015: return result;
1.9 paf 1016: }
1017:
1.126 paf 1018: char* rsplit(char* string, char delim) {
1.18 paf 1019: if(string) {
1.126 paf 1020: char* v=strrchr(string, delim);
1.18 paf 1021: if(v) {
1.9 paf 1022: *v=0;
1023: return v+1;
1024: }
1025: }
1026: return NULL;
1.10 paf 1027: }
1028:
1.37 paf 1029: /// @todo less stupid type detection
1.154 paf 1030: const char* format(double value, char* fmt) {
1.126 paf 1031: char local_buf[MAX_NUMBER];
1.108 paf 1032: size_t size;
1033:
1.10 paf 1034: if(fmt)
1035: if(strpbrk(fmt, "diouxX"))
1036: if(strpbrk(fmt, "ouxX"))
1.126 paf 1037: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.10 paf 1038: else
1.126 paf 1039: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
1.10 paf 1040: else
1.126 paf 1041: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
1.10 paf 1042: else
1.126 paf 1043: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
1.10 paf 1044:
1.154 paf 1045: return pa_strdup(local_buf, size);
1.12 paf 1046: }
1047:
1.36 paf 1048: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 1049: #ifdef WIN32
1050: do{
1.154 paf 1051: int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 1052: if(chunk_written<=0)
1053: break;
1054: size-=chunk_written;
1.36 paf 1055: buf=((const char*)buf)+chunk_written;
1.126 paf 1056: } while(size>0);
1.12 paf 1057:
1058: return size;
1059: #else
1.126 paf 1060: return fwrite(buf, 1, size, stdout);
1.12 paf 1061: #endif
1.2 paf 1062: }
1.14 paf 1063:
1.154 paf 1064: char* unescape_chars(const char* cp, int len) {
1065: char* s=new(PointerFreeGC) char[len + 1];
1.14 paf 1066: enum EscapeState {
1.33 paf 1067: EscapeRest,
1068: EscapeFirst,
1.14 paf 1069: EscapeSecond
1070: } escapeState=EscapeRest;
1071: int escapedValue=0;
1072: int srcPos=0;
1073: int dstPos=0;
1074: while(srcPos < len) {
1.126 paf 1075: int ch=cp[srcPos];
1.14 paf 1076: switch(escapeState) {
1077: case EscapeRest:
1078: if(ch=='%') {
1079: escapeState=EscapeFirst;
1080: } else if(ch=='+') {
1.126 paf 1081: s[dstPos++]=' ';
1.14 paf 1082: } else {
1083: s[dstPos++]=ch;
1084: }
1085: break;
1086: case EscapeFirst:
1087: escapedValue=hex_value[ch] << 4;
1088: escapeState=EscapeSecond;
1089: break;
1090: case EscapeSecond:
1.126 paf 1091: escapedValue +=hex_value[ch];
1.14 paf 1092: s[dstPos++]=escapedValue;
1093: escapeState=EscapeRest;
1094: break;
1095: }
1.126 paf 1096: srcPos++;
1.14 paf 1097: }
1098: s[dstPos]=0;
1099: return s;
1.24 paf 1100: }
1101:
1102: #ifdef WIN32
1.126 paf 1103: void back_slashes_to_slashes(char* s) {
1.24 paf 1104: if(s)
1105: for(; *s; s++)
1106: if(*s=='\\')
1.126 paf 1107: *s='/';
1.24 paf 1108: }
1.42 paf 1109: /*
1.126 paf 1110: void slashes_to_back_slashes(char* s) {
1.42 paf 1111: if(s)
1112: for(; *s; s++)
1113: if(*s=='/')
1.126 paf 1114: *s='\\';
1.42 paf 1115: }
1116: */
1.24 paf 1117: #endif
1.41 paf 1118:
1.126 paf 1119: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41 paf 1120: while(true) {
1121: if(!(*s1)) {
1122: if(!(*s2))
1123: return true;
1124: else
1125: return !strict;
1126: } else if(!(*s2))
1127: return !strict;
1128: if(isalpha(*s1)) {
1129: if(tolower(*s1) !=tolower(*s2))
1130: return false;
1131: } else if((*s1) !=(*s2))
1132: return false;
1.126 paf 1133: s1++;
1134: s2++;
1.41 paf 1135: }
1.57 parser 1136: }
1137:
1.84 paf 1138: static bool isLeap(int year) {
1.57 parser 1139: return !(
1140: (year % 4) || ((year % 400) && !(year % 100))
1.126 paf 1141: );
1.57 parser 1142: }
1143:
1144: int getMonthDays(int year, int month) {
1145: int monthDays[]={
1.126 paf 1146: 31,
1147: isLeap(year) ? 29 : 28,
1148: 31,
1149: 30,
1150: 31,
1151: 30,
1152: 31,
1153: 31,
1154: 30,
1155: 31,
1156: 30,
1.57 parser 1157: 31
1.126 paf 1158: };
1159: return monthDays[month];
1.41 paf 1160: }
1.69 parser 1161:
1.126 paf 1162: void remove_crlf(char* start, char* end) {
1163: for(char* p=start; p<end; p++)
1.69 parser 1164: switch(*p) {
1.126 paf 1165: case '\n': *p='|'; break;
1166: case '\r': *p=' '; break;
1.69 parser 1167: }
1.91 paf 1168: }
1169:
1170:
1171: /// must be last in this file
1172: #undef vsnprintf
1.126 paf 1173: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 1174: if(!s)
1175: return 0;
1176:
1177: int r;
1178: // note: on win32& maybe somewhere else
1179: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
1180: --s;
1.172 paf 1181:
1182: // clients do not check for negative 's', feature: ignore such prints
1183: if((ssize_t)s<0)
1184: return 0;
1185:
1.91 paf 1186: #if _MSC_VER
1187: /*
1188: win32:
1189: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
1190:
1.154 paf 1191: if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91 paf 1192: */
1.126 paf 1193: r=_vsnprintf(b, s, f, l);
1.91 paf 1194: if(r<0)
1195: r=s;
1196: #else
1.126 paf 1197: r=vsnprintf(b, s, f, l);
1.91 paf 1198: /*
1199: solaris:
1200: man vsnprintf
1201:
1202: The snprintf() function returns the number of characters
1203: formatted, that is, the number of characters that would have
1204: been written to the buffer if it were large enough. If the
1205: value of n is 0 on a call to snprintf(), an unspecified
1206: value less than 1 is returned.
1207: */
1208:
1209: if(r<0)
1210: r=0;
1.167 paf 1211: else if((size_t)r>s)
1.91 paf 1212: r=s;
1213: #endif
1214: b[r]=0;
1215: return r;
1216: }
1217:
1.126 paf 1218: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 1219: va_list l;
1.126 paf 1220: va_start(l, f);
1221: int r=__vsnprintf(b, s, f, l);
1222: va_end(l);
1.91 paf 1223: return r;
1.178 paf 1224: }
1225:
1226: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
1227: /*
1228: * Authors: Michael Zucchi <notzed@helixcode.com>
1229: * Jeffrey Stedfast <fejj@helixcode.com>
1230: *
1231: * Copyright 2000 Helix Code, Inc. (www.helixcode.com)
1232: *
1233: * This program is free software; you can redistribute it and/or modify
1234: * it under the terms of the GNU General Public License as published by
1235: * the Free Software Foundation; either version 2 of the License, or
1236: * (at your option) any later version.
1237: *
1238: * This program is distributed in the hope that it will be useful,
1239: * but WITHOUT ANY WARRANTY; without even the implied warranty of
1240: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1241: * GNU General Public License for more details.
1242: *
1243: * You should have received a copy of the GNU General Public License
1244: * along with this program; if not, write to the Free Software
1245: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
1246: *
1247: */
1248: static char *base64_alphabet =
1249: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1250:
1251: /**
1252: * g_mime_utils_base64_encode_step:
1253: * @in: input stream
1254: * @inlen: length of the input
1255: * @out: output string
1256: * @state: holds the number of bits that are stored in @save
1257: * @save: leftover bits that have not yet been encoded
1258: *
1259: * Base64 encodes a chunk of data. Performs an 'encode step', only
1260: * encodes blocks of 3 characters to the output at a time, saves
1261: * left-over state in state and save (initialise to 0 on first
1262: * invocation).
1263: *
1264: * Returns the number of bytes encoded.
1265: **/
1266: static size_t
1267: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1268: {
1269: const register unsigned char *inptr;
1270: register unsigned char *outptr;
1271:
1272: if (inlen <= 0)
1273: return 0;
1274:
1275: inptr = in;
1276: outptr = out;
1277:
1278: if (inlen + ((unsigned char *)save)[0] > 2) {
1279: const unsigned char *inend = in + inlen - 2;
1280: register int c1 = 0, c2 = 0, c3 = 0;
1281: register int already;
1282:
1283: already = *state;
1284:
1285: switch (((char *)save)[0]) {
1286: case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
1287: case 2: c1 = ((unsigned char *)save)[1];
1288: c2 = ((unsigned char *)save)[2]; goto skip2;
1289: }
1290:
1291: /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
1292: while (inptr < inend) {
1293: c1 = *inptr++;
1294: skip1:
1295: c2 = *inptr++;
1296: skip2:
1297: c3 = *inptr++;
1298: *outptr++ = base64_alphabet [c1 >> 2];
1299: *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
1300: *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
1301: *outptr++ = base64_alphabet [c3 & 0x3f];
1302: /* this is a bit ugly ... */
1303: if ((++already) >= 19) {
1304: *outptr++ = '\n';
1305: already = 0;
1306: }
1307: }
1308:
1309: ((unsigned char *)save)[0] = 0;
1310: inlen = 2 - (inptr - inend);
1311: *state = already;
1312: }
1313:
1314: //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
1315:
1316: if (inlen > 0) {
1317: register char *saveout;
1318:
1319: /* points to the slot for the next char to save */
1320: saveout = & (((char *)save)[1]) + ((char *)save)[0];
1321:
1322: /* inlen can only be 0 1 or 2 */
1323: switch (inlen) {
1324: case 2: *saveout++ = *inptr++;
1325: case 1: *saveout++ = *inptr++;
1326: }
1327: ((char *)save)[0] += inlen;
1328: }
1329:
1330: /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
1331: (int)((char *)save)[0],
1332: (int)((char *)save)[1],
1333: (int)((char *)save)[2]));*/
1334:
1335: return (outptr - out);
1336: }
1337:
1338: /**
1339: * g_mime_utils_base64_encode_close:
1340: * @in: input stream
1341: * @inlen: length of the input
1342: * @out: output string
1343: * @state: holds the number of bits that are stored in @save
1344: * @save: leftover bits that have not yet been encoded
1345: *
1346: * Base64 encodes the input stream to the output stream. Call this
1347: * when finished encoding data with g_mime_utils_base64_encode_step to
1348: * flush off the last little bit.
1349: *
1350: * Returns the number of bytes encoded.
1351: **/
1352: static size_t
1353: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1354: {
1355: unsigned char *outptr = out;
1356: int c1, c2;
1357:
1358: if (inlen > 0)
1359: outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
1360:
1361: c1 = ((unsigned char *)save)[1];
1362: c2 = ((unsigned char *)save)[2];
1363:
1364: switch (((unsigned char *)save)[0]) {
1365: case 2:
1366: outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
1367: goto skip;
1368: case 1:
1369: outptr[2] = '=';
1370: skip:
1371: outptr[0] = base64_alphabet [c1 >> 2];
1372: outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
1373: outptr[3] = '=';
1374: outptr += 4;
1375: break;
1376: }
1377:
1378: *outptr++ = 0;
1379:
1380: *save = 0;
1381: *state = 0;
1382:
1383: return (outptr - out);
1384: }
1385:
1386: char* pa_base64(const char *in, size_t len)
1387: {
1388: /* wont go to more than 2x size (overly conservative) */
1389: char* result=new(PointerFreeGC) char[len * 2 + 6];
1390: int state=0;
1391: int save=0;
1.183 paf 1392: #ifndef NDEBUG
1393: size_t filled=
1394: #endif
1395: g_mime_utils_base64_encode_close ((const unsigned char*)in, len,
1.178 paf 1396: (unsigned char*)result, &state, &save);
1397: assert(filled <= len * 2 + 6);
1398:
1399: return result;
1.98 paf 1400: }
E-mail: