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