Annotation of parser3/src/main/pa_http.C, revision 1.137
1.1 paf 1: /** @file
2: Parser: http support functions.
3:
1.135 moko 4: Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)
1.121 moko 5: Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.1 paf 6: */
7:
8: #include "pa_http.h"
9: #include "pa_common.h"
1.81 moko 10: #include "pa_base64.h"
1.1 paf 11: #include "pa_charsets.h"
12: #include "pa_request_charsets.h"
1.22 misha 13: #include "pa_vfile.h"
14: #include "pa_random.h"
1.1 paf 15:
1.137 ! moko 16: volatile const char * IDENT_PA_HTTP_C="$Id: pa_http.C,v 1.136 2026/09/06 21:30:54 moko Exp $" IDENT_PA_HTTP_H;
1.53 moko 17:
1.1 paf 18: // defines
19:
1.19 misha 20: #define HTTP_METHOD_NAME "method"
21: #define HTTP_FORM_NAME "form"
22: #define HTTP_BODY_NAME "body"
23: #define HTTP_TIMEOUT_NAME "timeout"
24: #define HTTP_HEADERS_NAME "headers"
1.22 misha 25: #define HTTP_FORM_ENCTYPE_NAME "enctype"
1.19 misha 26: #define HTTP_ANY_STATUS_NAME "any-status"
1.59 moko 27: #define HTTP_OMIT_POST_CHARSET_NAME "omit-post-charset" // ^file::load[...;http://...;$.method[post]] by default adds charset to content-type
1.12 misha 28:
1.1 paf 29: #define HTTP_USER "user"
30: #define HTTP_PASSWORD "password"
31:
1.70 moko 32: #define HTTP_USER_AGENT "user-agent"
1.1 paf 33: #define DEFAULT_USER_AGENT "parser3"
34:
1.59 moko 35: #ifndef INADDR_NONE
36: #define INADDR_NONE ((ulong) -1)
37: #endif
1.1 paf 38:
39: #undef CRLF
40: #define CRLF "\r\n"
41:
1.54 misha 42: // helpers
1.56 misha 43:
1.130 moko 44: #ifdef HTTPD_DEBUG
45: void pa_log(const char* fmt, ...);
46: #define LOG(action) action
47: #else
48: #define LOG(action)
49: #endif
50:
51: ssize_t pa_send(int sock, const char *buffer, size_t len){
52: size_t total_sent = 0;
53: while (total_sent < len) {
54: ssize_t bytes_sent=send(sock, buffer + total_sent, len - total_sent, 0);
55: if (bytes_sent < 0) {
56: return bytes_sent;
57: } else if (bytes_sent == 0) {
58: // Connection closed by the remote peer?
59: break;
60: }
61: LOG(
62: if(bytes_sent != len - total_sent)
63: pa_log("httpd [%d] partial send %d of (%d)", sock, bytes_sent, len - total_sent)
64: );
65: total_sent += bytes_sent;
66: }
67: return total_sent;
68: }
69:
1.85 moko 70: bool HTTP_Headers::add_header(const char *line){
1.78 moko 71: const char *value=strchr(line, ':');
72:
73: if(value && value != line){ // we need only headers, not the response code
1.134 moko 74: Header header = Header(String::Body(str_upper(line, value-line)), String::Body(value+1).trim(String::TRIM_BOTH, " \t\n\r"));
1.78 moko 75:
76: if(header.name == String::Body(HTTP_CONTENT_TYPE_UPPER) && content_type.is_empty())
77: content_type=header.value;
78:
79: if(header.name == String::Body("CONTENT-LENGTH") && content_length==0)
1.95 moko 80: ALTER_EXCEPTION_COMMENT(content_length=pa_atoul(header.value.cstr()), " for content-length");
1.78 moko 81:
82: headers+=header;
83:
84: return true;
85: }
86: return false;
87: }
88:
1.54 misha 89: class Cookies_table_template_columns: public ArrayString {
90: public:
91: Cookies_table_template_columns() {
92: *this+=new String("name");
93: *this+=new String("value");
94: *this+=new String("expires");
95: *this+=new String("max-age");
96: *this+=new String("domain");
97: *this+=new String("path");
98: *this+=new String("httponly");
99: *this+=new String("secure");
100: }
101: };
102:
103:
1.1 paf 104: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
1.22 misha 105: memset(addr, 0, sizeof(*addr));
106: addr->sin_family=AF_INET;
107: addr->sin_port=htons(port);
108: if(host) {
1.65 moko 109: struct hostent *hostIP=gethostbyname(host);
110: if(hostIP && hostIP->h_addrtype == AF_INET){
111: memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length);
112: return true;
113: }
114: }
115: return false;
1.1 paf 116: }
117:
1.84 moko 118: class HTTP_response : public PA_Allocated {
1.78 moko 119: public:
120: char *buf;
121: size_t length;
122: size_t buf_size;
123: size_t body_offset;
124:
1.85 moko 125: HTTP_Headers headers;
1.78 moko 126:
1.97 moko 127: HTTP_response() : buf(NULL), length(0), buf_size(0), body_offset(0){}
1.78 moko 128:
129: void resize(size_t size){
130: buf_size=size;
131: buf=(char *)pa_realloc(buf, size + 1);
132: }
133:
1.120 moko 134: bool read(SOCKET sock, size_t size){
1.103 moko 135: if(length + size > buf_size)
136: resize(buf_size * 2 + size);
1.78 moko 137: ssize_t received_size=recv(sock, buf + length, size, 0);
1.103 moko 138: if(received_size == 0)
1.78 moko 139: return false;
1.103 moko 140: if(received_size < 0) {
141: if(int no = pa_socks_errno())
1.102 moko 142: throw Exception("http.timeout", 0, "error receiving response: %s (%d)", pa_socks_strerr(no), no);
1.78 moko 143: return false;
144: }
145: length+=received_size;
146: buf[length]='\0';
147: return true;
148: }
149:
1.83 moko 150: size_t first_line(){
1.89 moko 151: char *header=strchr(buf, '\n');
152: if(!header)
1.78 moko 153: return false;
154:
1.89 moko 155: return header-buf;
1.78 moko 156: }
157:
158: const char *status_code(char *status_line, int &result){
159: char* status_start = strchr(status_line, ' ');
160:
161: if(!(status_start++))
162: return status_line;
163:
164: char* status_end=strchr(status_start, ' ');
165:
166: if(!status_end)
167: return status_line;
168:
169: if(status_end==status_start)
170: return status_line;
1.1 paf 171:
1.78 moko 172: const char *result_str=pa_strdup(status_start, status_end-status_start);
1.95 moko 173: ALTER_EXCEPTION_COMMENT(result=pa_atoui(result_str), " for HTTP status");
1.78 moko 174: return result_str;
175: }
1.2 paf 176:
1.78 moko 177: bool body_start(){
178: char *p=buf;
179: while((p=strchr(p, '\n'))) {
180: if(p[1]=='\r' && p[2]=='\n'){ // \r\n\r\n
181: *p='\0';
182: body_offset=p-buf+3;
183: return true;
184: }
185: if(p[1]=='\n') { // \n\n
186: *p='\0';
187: body_offset=p-buf+2;
188: return true;
189: }
190: p++;
191: }
192: return false;
1.2 paf 193: }
1.78 moko 194:
195: void parse_headers(){
196: const String header_block(buf, String::L_TAINTED);
197:
198: ArrayString aheaders;
199: header_block.split(aheaders, 0, "\n");
200:
1.124 moko 201: ArrayString::Iterator i(aheaders);
1.78 moko 202: i.next(); // skipping status
1.125 moko 203: for(;i;){
1.78 moko 204: const char *line=i.next()->cstr();
205: if(!headers.add_header(line))
1.97 moko 206: throw Exception("http.response", 0, "bad response from host - bad header \"%s\"", line);
1.78 moko 207: }
1.1 paf 208: }
209:
1.120 moko 210: int read_response(SOCKET sock, bool fail_on_status_ne_200);
1.78 moko 211: };
212:
213: enum HTTP_response_state {
214: HTTP_STATUS_CODE,
215: HTTP_HEADERS,
216: HTTP_BODY
217: };
218:
1.120 moko 219: int HTTP_response::read_response(SOCKET sock, bool fail_on_status_ne_200) {
1.78 moko 220: HTTP_response_state state=HTTP_STATUS_CODE;
221: int result=0;
222:
223: size_t chunk_size=0x400*16;
1.88 moko 224: resize(2*chunk_size);
1.78 moko 225:
1.88 moko 226: while(read(sock, chunk_size)){
1.78 moko 227: switch(state){
228: case HTTP_STATUS_CODE: {
1.88 moko 229: size_t status_size=first_line();
1.78 moko 230: if(!status_size)
231: break;
232:
1.88 moko 233: const char *status=status_code(pa_strdup(buf, status_size), result);
1.78 moko 234:
235: if(!result || fail_on_status_ne_200 && result!=200)
236: throw Exception("http.status", status ? new String(status) : &String::Empty, "invalid HTTP response status");
237:
238: state=HTTP_HEADERS;
239: }
240:
241: case HTTP_HEADERS: {
1.88 moko 242: if(!body_start())
1.78 moko 243: break;
244:
1.88 moko 245: parse_headers();
1.78 moko 246:
1.97 moko 247: size_t content_length=check_file_size(headers.content_length, 0);
1.88 moko 248: if(content_length>0 && (content_length + body_offset) > length){
249: resize(content_length + body_offset + 0x400*64);
1.78 moko 250: }
251:
252: state=HTTP_BODY;
1.1 paf 253: break;
254: }
1.78 moko 255:
256: case HTTP_BODY: {
257: chunk_size=0x400*64;
1.1 paf 258: break;
259: }
260: }
261: }
1.78 moko 262:
263: if(state==HTTP_STATUS_CODE)
1.97 moko 264: throw Exception("http.response", 0, "bad response from host - no status found (size=%u)", length);
1.78 moko 265:
266: if(state==HTTP_HEADERS){
1.88 moko 267: parse_headers();
268: body_offset=length;
1.1 paf 269: }
1.78 moko 270:
271: return result;
1.1 paf 272: }
273:
274: /* ********************** request *************************** */
275:
276: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
277: # define PA_USE_ALARM
278: #endif
279:
280: #ifdef PA_USE_ALARM
281: static sigjmp_buf timeout_env;
282: static void timeout_handler(int /*sig*/){
1.101 moko 283: siglongjmp(timeout_env, 1);
1.1 paf 284: }
1.118 moko 285:
286: #define PA_NO_THREADS (HTTPD_Server::mode != HTTPD_Server::MULTITHREADED)
287:
288: #define ALARM(value) if(PA_NO_THREADS) alarm(value)
1.101 moko 289: #else
290: #define ALARM(value)
1.1 paf 291: #endif
292:
1.78 moko 293: static int http_request(HTTP_response& response, const char* host, short port, const char* request, size_t request_size, int timeout_secs, bool fail_on_status_ne_200) {
1.1 paf 294: if(!host)
1.73 moko 295: throw Exception("http.host", 0, "zero hostname"); //never
1.1 paf 296:
1.120 moko 297: volatile SOCKET sock=INVALID_SOCKET; // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning]
1.101 moko 298:
1.1 paf 299: #ifdef PA_USE_ALARM
1.118 moko 300: if(PA_NO_THREADS) signal(SIGALRM, timeout_handler);
301: if(PA_NO_THREADS && sigsetjmp(timeout_env, 1)) {
1.101 moko 302: // duplicating closesocket to make code more simple for old compilers
1.120 moko 303: if(sock != INVALID_SOCKET)
1.101 moko 304: closesocket(sock);
305: throw Exception("http.timeout", 0, "timeout occurred while retrieving document");
1.1 paf 306: return 0; // never
1.101 moko 307: } else
1.1 paf 308: #endif
1.101 moko 309: {
310: ALARM(timeout_secs);
1.1 paf 311: try {
312: int result;
313: struct sockaddr_in dest;
314:
315: if(!set_addr(&dest, host, port))
1.127 moko 316: throw Exception("http.host", 0, "cannot resolve hostname \"%s\"", host);
1.1 paf 317:
1.120 moko 318: if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/)) == INVALID_SOCKET) {
1.1 paf 319: int no=pa_socks_errno();
1.127 moko 320: throw Exception("http.connect", 0, "cannot make socket: %s (%d)", pa_socks_strerr(no), no);
1.1 paf 321: }
322:
323: // To enable SO_DONTLINGER (that is, disable SO_LINGER)
324: // l_onoff should be set to zero and setsockopt should be called
325: linger dont_linger={0,0};
326: setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger));
327:
328: #ifdef WIN32
329: // SO_*TIMEO can be defined in .h but not implemlemented in protocol,
330: // failing subsequently with Option not supported by protocol (99) message
331: // could not suppress that, so leaving this only for win32
332: int timeout_ms=timeout_secs*1000;
333: setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
334: setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
335: #endif
336:
337: if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
338: int no=pa_socks_errno();
1.127 moko 339: throw Exception("http.connect", 0, "cannot connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no);
1.1 paf 340: }
1.22 misha 341:
1.130 moko 342: if(pa_send(sock, request, request_size) < 0) {
1.1 paf 343: int no=pa_socks_errno();
1.78 moko 344: throw Exception("http.timeout", 0, "error sending request: %s (%d)", pa_socks_strerr(no), no);
1.1 paf 345: }
346:
1.88 moko 347: result=response.read_response(sock, fail_on_status_ne_200);
1.78 moko 348: closesocket(sock);
1.101 moko 349: ALARM(0);
1.1 paf 350: return result;
351: } catch(...) {
1.101 moko 352: ALARM(0);
1.120 moko 353: if(sock != INVALID_SOCKET)
1.78 moko 354: closesocket(sock);
1.1 paf 355: rethrow;
356: }
357: }
358: }
359:
360: #ifndef DOXYGEN
361: struct Http_pass_header_info {
362: Request_charsets* charsets;
363: String* request;
1.35 misha 364: bool* user_agent_specified;
365: bool* content_type_specified;
366: bool* content_type_url_encoded;
1.1 paf 367: };
368: #endif
1.50 moko 369:
370: char *pa_http_safe_header_name(const char *name) {
371: char *result=pa_strdup(name);
372: char *n=result;
1.52 misha 373: if(!pa_isalpha((unsigned char)*n))
1.50 moko 374: *n++ = '_';
375: for(; *n; ++n) {
1.52 misha 376: if (!pa_isalnum((unsigned char)*n) && *n != '-' && *n != '_')
1.50 moko 377: *n = '_';
378: }
379: return result;
380: }
381:
1.101 moko 382: static void http_pass_header(HashStringValue::key_type aname, HashStringValue::value_type avalue, Http_pass_header_info *info) {
1.9 misha 383:
1.41 misha 384: const char* name_cstr=aname.cstr();
385:
1.38 misha 386: if(strcasecmp(name_cstr, HTTP_CONTENT_LENGTH)==0)
387: return;
388:
1.50 moko 389: String name=String(pa_http_safe_header_name(capitalize(name_cstr)), String::L_AS_IS);
390: String value=attributed_meaning_to_string(*avalue, String::L_HTTP_HEADER, true);
1.9 misha 391:
1.35 misha 392: *info->request << name << ": " << value << CRLF;
1.1 paf 393:
1.38 misha 394: if(strcasecmp(name_cstr, HTTP_USER_AGENT)==0)
1.35 misha 395: *info->user_agent_specified=true;
1.38 misha 396: if(strcasecmp(name_cstr, HTTP_CONTENT_TYPE)==0){
1.35 misha 397: *info->content_type_specified=true;
1.62 moko 398: *info->content_type_url_encoded=pa_strncasecmp(value.cstr(), HTTP_CONTENT_TYPE_FORM_URLENCODED)==0;
1.35 misha 399: }
1.1 paf 400: }
401:
1.10 misha 402: static void http_pass_cookie(HashStringValue::key_type name,
1.20 misha 403: HashStringValue::value_type value,
404: Http_pass_header_info *info) {
1.10 misha 405:
1.17 misha 406: *info->request << String(name, String::L_HTTP_COOKIE) << "="
1.31 misha 407: << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, true)
1.10 misha 408: << "; ";
409:
410: }
1.1 paf 411:
412: static const String* basic_authorization_field(const char* user, const char* pass) {
413: if(!user&& !pass)
414: return 0;
415:
416: String combined;
417: if(user)
418: combined<<user;
419: combined<<":";
420: if(pass)
421: combined<<pass;
422:
1.20 misha 423: String* result=new String("Basic ");
1.82 moko 424: *result<<pa_base64_encode(combined.cstr(), combined.length(), Base64Options(false /*no wrap*/));
1.1 paf 425: return result;
426: }
427:
1.73 moko 428: static void form_string_value2string(HashStringValue::key_type key, const String& value, String& result) {
1.30 misha 429: result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1 paf 430: }
1.20 misha 431:
1.1 paf 432: #ifndef DOXYGEN
433: struct Form_table_value2string_info {
434: HashStringValue::key_type key;
435: String& result;
436:
437: Form_table_value2string_info(HashStringValue::key_type akey, String& aresult):
438: key(akey), result(aresult) {}
439: };
440: #endif
441: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
442: form_string_value2string(info->key, *row->get(0), info->result);
443: }
1.73 moko 444:
445: static void form_value2string(HashStringValue::key_type key, HashStringValue::value_type value, String* result) {
1.1 paf 446: if(const String* svalue=value->get_string())
447: form_string_value2string(key, *svalue, *result);
448: else if(Table* tvalue=value->get_table()) {
449: Form_table_value2string_info info(key, *result);
450: tvalue->for_each(form_table_value2string, &info);
451: } else
1.73 moko 452: throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED),
1.63 moko 453: "is %s, " HTTP_FORM_NAME " option value can be string or table only (file is allowed for $." HTTP_METHOD_NAME "[POST] + $." HTTP_FORM_ENCTYPE_NAME "[" HTTP_CONTENT_TYPE_MULTIPART_FORMDATA "])", value->type());
1.1 paf 454: }
1.20 misha 455:
1.5 misha 456: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1 paf 457: String string;
1.3 paf 458: form.for_each<String*>(form_value2string, &string);
1.44 misha 459: return string.untaint_and_transcode_cstr(String::L_URI, &charsets);
1.1 paf 460: }
1.22 misha 461:
462: struct FormPart {
463: Request* r;
464: const char* boundary;
1.48 moko 465: String* string;
1.22 misha 466: Form_table_value2string_info* info;
1.48 moko 467:
468: struct BinaryBlock{
469: const char* ptr;
470: size_t length;
471:
472: BinaryBlock(String* astring, Request* r): ptr(astring->untaint_and_transcode_cstr(String::L_AS_IS, &r->charsets)), length(strlen(ptr)){}
473: BinaryBlock(const char* aptr, size_t alength): ptr(aptr), length(alength){}
474: };
475:
476: Array<BinaryBlock> blocks;
477:
478: FormPart(Request* ar, const char* aboundary): r(ar), boundary(aboundary), string(new String()){}
479:
480: const char *post(size_t &length){
481: if(blocks.count()){
482: blocks+=BinaryBlock(string, r);
483:
484: length=0;
485: for(size_t i=0; i<blocks.count(); i++)
486: length+=blocks[i].length;
487:
488: char *result=(char *)pa_malloc_atomic(length);
489: char *ptr=result;
490:
491: for(size_t i=0; i<blocks.count(); i++){
492: memcpy(ptr, blocks[i].ptr, blocks[i].length);
493: ptr+=blocks[i].length;
494: }
495:
496: return result;
497: } else {
498: BinaryBlock result(string, r);
499: length=result.length;
500: return result.ptr;
501: }
502: }
1.22 misha 503: };
504:
1.73 moko 505: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0) {
506: *part.string << "--" << part.boundary << CRLF CONTENT_DISPOSITION_CAPITALIZED ": form-data; name=\"" << name << "\"";
1.22 misha 507: if(file_name){
508: if(strcmp(file_name, NONAME_DAT)!=0)
1.48 moko 509: *part.string << "; filename=\"" << file_name << "\"";
510: *part.string << CRLF HTTP_CONTENT_TYPE_CAPITALIZED ": " << part.r->mime_type_of(file_name);
1.22 misha 511: }
1.48 moko 512: *part.string << CRLF CRLF;
1.22 misha 513: }
514:
1.73 moko 515: static void form_string_value2part(HashStringValue::key_type key, const String& value, FormPart& part) {
1.28 misha 516: form_part_boundary_header(part, key);
1.48 moko 517: *part.string << value << CRLF;
1.22 misha 518: }
519:
1.73 moko 520: static void form_file_value2part(HashStringValue::key_type key, VFile& vfile, FormPart& part) {
1.28 misha 521: form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.48 moko 522: part.blocks+=FormPart::BinaryBlock(part.string, part.r);
523: part.blocks+=FormPart::BinaryBlock(vfile.value_ptr(), vfile.value_size());
524: part.string=new String();
525: *part.string << CRLF;
1.22 misha 526: }
527:
528: static void form_table_value2part(Table::element_type row, FormPart* part) {
529: form_string_value2part(part->info->key, *row->get(0), *part);
530: }
531:
1.136 moko 532: static bool form_element_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) {
533: if(const String* svalue=value->get_string()){
534: form_string_value2part(key, *svalue, part);
535: } else if(VFile* vfile=dynamic_cast<VFile *>(value)){
536: form_file_value2part(key, *vfile, part);
537: } else {
538: return false;
539: }
540: return true;
541: }
542:
1.73 moko 543: static void form_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) {
1.136 moko 544: if(form_element_value2part(key, value, part)) {
545: // string or file
546: } else if(Table* tvalue=value->get_table()) {
1.48 moko 547: Form_table_value2string_info info(key, *part.string);
1.22 misha 548: part.info = &info;
549: tvalue->for_each(form_table_value2part, &part);
1.136 moko 550: } else if(HashStringValue* hvalue=value->get_hash()){
551: // hash or array: several strings/files under the same field name
552: for(HashStringValue::Iterator j(*hvalue); j; j.next())
553: if(!form_element_value2part(key, j.value(), part))
554: throw Exception(PARSER_RUNTIME, new String(j.key(), String::L_TAINTED), "is %s, multiple values of " HTTP_FORM_NAME " field '%s' must be strings or files", j.value()->type(), key.cstr());
1.22 misha 555: } else
1.136 moko 556: throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED), "is %s, " HTTP_FORM_NAME " field value can be string, table, file, hash or array", value->type());
1.22 misha 557: }
558:
559: const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){
1.48 moko 560: FormPart formpart(&r, boundary);
1.22 misha 561: form.for_each<FormPart&>(form_value2part, formpart);
1.48 moko 562: *formpart.string << "--" << boundary << "--";
563: // @todo: return binary blocks here to save memory in pa_internal_file_read_http
564: return formpart.post(post_size);
1.22 misha 565: }
566:
1.54 misha 567: // Set-Cookie: name=value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly
568: static ArrayString* parse_cookie(Request& r, const String& cookie) {
1.64 moko 569: char *current=pa_strdup(cookie.cstr());
1.54 misha 570:
571: const String* name=0;
1.55 moko 572: const String* value=&String::Empty;
573: const String* expires=&String::Empty;
574: const String* max_age=&String::Empty;
575: const String* path=&String::Empty;
576: const String* domain=&String::Empty;
577: const String* httponly=&String::Empty;
578: const String* secure=&String::Empty;
1.54 misha 579:
580: bool first_pair=true;
581:
582: do {
583: if(char *meaning=search_stop(current, ';'))
584: if(char *attribute=search_stop(meaning, '=')) {
585: const String* sname=new String(unescape_chars(attribute, strlen(attribute), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
586: const String* smeaning=0;
587: if(meaning)
588: smeaning=new String(unescape_chars(meaning, strlen(meaning), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
589:
590: if(first_pair) {
591: // name + value
592: name=sname;
1.122 moko 593: if(smeaning)
594: value=smeaning;
1.54 misha 595: first_pair=false;
596: } else {
597: const String& slower=sname->change_case(r.charsets.source(), String::CC_LOWER);
598:
599: if(slower == "expires")
600: expires=smeaning;
601: else if(slower == "max-age")
602: max_age=smeaning;
603: else if(slower == "domain")
604: domain=smeaning;
605: else if(slower == "path")
606: path=smeaning;
607: else if(slower == "httponly")
608: httponly=new String("1", String::L_CLEAN);
609: else if(slower == "secure")
610: secure=new String("1", String::L_CLEAN);
611: else {
612: // todo@ ?
613: }
614: }
615: }
616: } while(current);
617:
618: if(!name)
619: return 0;
620:
621: ArrayString* result=new ArrayString(8);
622: *result+=name;
623: *result+=value;
624: *result+=expires;
625: *result+=max_age;
626: *result+=domain;
627: *result+=path;
628: *result+=httponly;
629: *result+=secure;
630:
631: return result;
632: }
633:
1.56 misha 634: Table* parse_cookies(Request& r, Table *cookies){
635: Table& result=*new Table(new Cookies_table_template_columns);
636:
1.125 moko 637: for(Array_iterator<Table::element_type> i(*cookies); i; )
1.56 misha 638: if(ArrayString* row=parse_cookie(r, *i.next()->get(0)))
639: result+=row;
640:
641: return &result;
642: }
643:
1.75 moko 644: void tables_update(HashStringValue& tables, const String::Body name, const String& value){
1.72 moko 645: Table *table;
646: if(Value *valready=tables.get(name)) {
647: // second+ appearence
648: table=valready->get_table();
649: } else {
650: // first appearence
651: Table::columns_type columns=new ArrayString(1);
652: *columns+=new String("value");
653: table=new Table(columns);
654: tables.put(name, new VTable(table));
655: }
656: // this string becomes next row
657: ArrayString& row=*new ArrayString(1);
658: row+=&value;
659: *table+=&row;
660: }
661:
1.1 paf 662: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.72 moko 663: File_read_http_result pa_internal_file_read_http(Request& r, const String& file_spec, bool as_text, HashStringValue *options, bool transcode_text_result) {
1.1 paf 664: File_read_http_result result;
1.20 misha 665: char host[MAX_STRING];
1.66 moko 666: const char *idna_host;
1.1 paf 667: const char* uri;
1.49 moko 668: short port=80;
1.10 misha 669: const char* method="GET";
1.21 misha 670: bool method_is_get=true;
1.1 paf 671: HashStringValue* form=0;
672: int timeout_secs=2;
673: bool fail_on_status_ne_200=true;
1.12 misha 674: bool omit_post_charset=false;
1.1 paf 675: Value* vheaders=0;
1.10 misha 676: Value* vcookies=0;
1.11 misha 677: Value* vbody=0;
1.72 moko 678: Charset* asked_remote_charset=0;
1.58 moko 679: Charset* real_remote_charset=0;
1.1 paf 680: const char* user_cstr=0;
681: const char* password_cstr=0;
1.22 misha 682: const char* encode=0;
683: bool multipart=false;
1.1 paf 684:
685: if(options) {
686: int valid_options=pa_get_valid_file_options_count(*options);
687:
688: if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
689: valid_options++;
1.21 misha 690: method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
691: method_is_get=strcmp(method, "GET")==0;
1.1 paf 692: }
1.22 misha 693: if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
694: valid_options++;
695: encode=vencode->as_string().cstr();
696: }
1.1 paf 697: if(Value* vform=options->get(HTTP_FORM_NAME)) {
698: valid_options++;
699: form=vform->get_hash();
700: }
1.11 misha 701: if(vbody=options->get(HTTP_BODY_NAME)) {
1.1 paf 702: valid_options++;
703: }
704: if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
705: valid_options++;
706: timeout_secs=vtimeout->as_int();
707: }
1.11 misha 708: if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1 paf 709: valid_options++;
710: }
1.11 misha 711: if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10 misha 712: valid_options++;
713: }
1.1 paf 714: if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
715: valid_options++;
716: fail_on_status_ne_200=!vany_status->as_bool();
1.12 misha 717: }
1.20 misha 718: if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12 misha 719: valid_options++;
720: omit_post_charset=vomit_post_charset->as_bool();
721: }
1.6 misha 722: if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.77 moko 723: asked_remote_charset=&pa_charsets.get(vcharset_name->as_string());
1.58 moko 724: }
725: if(Value* vresponse_charset_name=options->get(PA_RESPONSE_CHARSET_NAME)) {
1.61 moko 726: valid_options++;
1.77 moko 727: real_remote_charset=&pa_charsets.get(vresponse_charset_name->as_string());
1.1 paf 728: }
729: if(Value* vuser=options->get(HTTP_USER)) {
730: valid_options++;
731: user_cstr=vuser->as_string().cstr();
732: }
733: if(Value* vpassword=options->get(HTTP_PASSWORD)) {
734: valid_options++;
735: password_cstr=vpassword->as_string().cstr();
736: }
737:
738: if(valid_options!=options->count())
1.46 misha 739: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 paf 740: }
741: if(!asked_remote_charset) // defaulting to $request:charset
1.22 misha 742: asked_remote_charset=&(r.charsets).source();
743:
744: if(encode){
745: if(method_is_get)
1.127 moko 746: throw Exception(PARSER_RUNTIME, 0, "you cannot use $." HTTP_FORM_ENCTYPE_NAME " option with method GET");
1.22 misha 747:
748: multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
749:
750: if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
1.72 moko 751: throw Exception(PARSER_RUNTIME, 0, "$." HTTP_FORM_ENCTYPE_NAME " option value can be " HTTP_CONTENT_TYPE_FORM_URLENCODED " or " HTTP_CONTENT_TYPE_MULTIPART_FORMDATA " only");
1.22 misha 752: }
1.1 paf 753:
1.11 misha 754: if(vbody){
755: if(method_is_get)
1.127 moko 756: throw Exception(PARSER_RUNTIME, 0, "you cannot use $." HTTP_BODY_NAME " option with method GET");
1.11 misha 757:
758: if(form)
1.127 moko 759: throw Exception(PARSER_RUNTIME, 0, "you cannot use options $." HTTP_BODY_NAME " and $." HTTP_FORM_NAME " together");
1.11 misha 760: }
1.1 paf 761:
762: //preparing request
1.29 misha 763: String& connect_string=*new String(file_spec);
1.1 paf 764:
1.48 moko 765: const char* request;
766: size_t request_size;
1.1 paf 767: {
768: // influence URLencoding of tainted pieces to String::L_URI lang
1.22 misha 769: Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1 paf 770:
1.44 misha 771: const char* connect_string_cstr=connect_string.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1 paf 772:
773: const char* current=connect_string_cstr;
774: if(strncmp(current, "http://", 7)!=0)
1.72 moko 775: throw Exception(PARSER_RUNTIME, &connect_string, "does not start with http://"); //never
1.1 paf 776: current+=7;
777:
1.119 moko 778: pa_strncpy(host, current, sizeof(host));
1.34 misha 779: char* host_uri=lsplit(host, '/');
780: uri=host_uri?current+(host_uri-1-host):"/";
781: char* port_cstr=lsplit(host, ':');
1.49 moko 782:
783: if (port_cstr){
784: char* error_pos=0;
785: port=(short)strtol(port_cstr, &error_pos, 10);
786: if(port==0 || *error_pos)
787: throw Exception(PARSER_RUNTIME, &connect_string, "invalid port number '%s'", port_cstr);
788: }
1.1 paf 789:
1.66 moko 790: idna_host=pa_idna_encode(host, r.charsets.source());
791:
1.11 misha 792: // making request head
1.1 paf 793: String head;
1.11 misha 794: head << method << " " << uri;
1.28 misha 795: if(method_is_get && form)
796: head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11 misha 797:
1.66 moko 798: head <<" HTTP/1.0" CRLF "Host: "<< idna_host;
1.49 moko 799: if (port != 80)
800: head << ":" << port_cstr;
801: head << CRLF;
1.11 misha 802:
1.71 moko 803: char* boundary= multipart ? get_uuid_boundary() : 0;
1.22 misha 804:
1.35 misha 805: String user_headers;
806: bool user_agent_specified=false;
807: bool content_type_specified=false;
808: bool content_type_url_encoded=false;
809: if(vheaders && !vheaders->is_string()) { // allow empty
810: if(HashStringValue *headers=vheaders->get_hash()) {
811: Http_pass_header_info info={
812: &(r.charsets),
813: &user_headers,
814: &user_agent_specified,
815: &content_type_specified,
816: &content_type_url_encoded};
817: headers->for_each<Http_pass_header_info*>(http_pass_header, &info);
818: } else
1.72 moko 819: throw Exception(PARSER_RUNTIME, 0, "headers param must be hash");
1.35 misha 820: };
821:
1.48 moko 822: const char* request_body=0;
1.22 misha 823: size_t post_size=0;
824: if(form && !method_is_get) {
1.38 misha 825: head << "Content-Type: " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
1.28 misha 826:
827: if(!omit_post_charset)
828: head << "; charset=" << asked_remote_charset->NAME_CSTR();
829:
1.22 misha 830: if(multipart) {
1.28 misha 831: head << "; boundary=" << boundary;
1.48 moko 832: request_body=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22 misha 833: } else {
1.48 moko 834: request_body=pa_form2string(*form, r.charsets);
835: post_size=strlen(request_body);
1.22 misha 836: }
1.28 misha 837: head << CRLF;
1.35 misha 838: } else if(vbody) {
1.38 misha 839: // $.body was specified
1.35 misha 840: if(content_type_url_encoded){
1.36 misha 841: // transcode + url-encode
1.48 moko 842: request_body=vbody->as_string().untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.35 misha 843: } else {
1.36 misha 844: // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.72 moko 845: const String &sbody=vbody->as_string();
846: request_body=Charset::transcode(String::C(sbody.cstr(), sbody.length()), r.charsets.source(), *asked_remote_charset).str;
1.35 misha 847: }
1.48 moko 848: post_size=strlen(request_body);
1.1 paf 849: }
850:
851: // http://www.ietf.org/rfc/rfc2617.txt
852: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.38 misha 853: head << "Authorization: " << *authorization_field_value << CRLF;
1.1 paf 854:
1.35 misha 855: head << user_headers;
856:
1.1 paf 857: if(!user_agent_specified) // defaulting
1.38 misha 858: head << "User-Agent: " DEFAULT_USER_AGENT CRLF;
1.1 paf 859:
1.12 misha 860: if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
1.72 moko 861: throw Exception(PARSER_RUNTIME, 0, "$.content-type can't be specified with method POST");
1.12 misha 862:
1.11 misha 863: if(vcookies && !vcookies->is_string()){ // allow empty
1.10 misha 864: if(HashStringValue* cookies=vcookies->get_hash()) {
1.37 misha 865: head << "Cookie: ";
1.35 misha 866: Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10 misha 867: cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info);
868: head << CRLF;
869: } else
1.72 moko 870: throw Exception(PARSER_RUNTIME, 0, "cookies param must be hash");
1.10 misha 871: }
872:
1.48 moko 873: if(request_body)
1.128 moko 874: head << "Content-Length: " << pa_uitoa(post_size) << CRLF;
1.48 moko 875:
876: head << CRLF;
877:
878: const char *request_head=head.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1 paf 879:
1.48 moko 880: if(request_body){
881: size_t head_size = strlen(request_head);
882: request_size=post_size + head_size;
883: char *ptr=(char *)pa_malloc_atomic(request_size);
884: memcpy(ptr, request_head, head_size);
885: memcpy(ptr+head_size, request_body, post_size);
886: request=ptr;
887: } else {
888: request_size=strlen(request_head);
889: request=request_head;
890: }
1.1 paf 891: }
892:
1.78 moko 893:
1.97 moko 894: HTTP_response response;
1.22 misha 895:
1.28 misha 896: // sending request
1.95 moko 897: int status_code;
898: ALTER_EXCEPTION_SOURCE(status_code=http_request(response, idna_host, port, request, request_size, timeout_secs, fail_on_status_ne_200), &connect_string);
1.78 moko 899:
1.72 moko 900: // processing results
1.78 moko 901: char* raw_body=response.buf + response.body_offset;
902: size_t raw_body_size=response.length - response.body_offset;
903:
1.1 paf 904: result.headers=new HashStringValue;
905: VHash* vtables=new VHash;
1.133 moko 906: HASH_PUT_CSTR(*result.headers, "tables", vtables);
1.72 moko 907:
1.78 moko 908: if (!real_remote_charset && !response.headers.content_type.is_empty())
909: real_remote_charset=detect_charset(response.headers.content_type.cstr());
1.1 paf 910:
1.72 moko 911: if(as_text)
1.77 moko 912: real_remote_charset=pa_charsets.checkBOM(raw_body, raw_body_size, real_remote_charset);
1.72 moko 913:
914: if (!real_remote_charset)
915: real_remote_charset=asked_remote_charset; // never null
916:
1.125 moko 917: for(Array_iterator<HTTP_Headers::Header> i(response.headers.headers); i; ){
1.85 moko 918: HTTP_Headers::Header header=i.next();
1.72 moko 919:
920: header.transcode(*real_remote_charset, r.charsets.source());
921:
922: String &header_value=*new String(header.value, String::L_TAINTED);
923:
924: tables_update(vtables->hash(), header.name, header_value);
925: result.headers->put(header.name, new VString(header_value));
1.16 misha 926: }
927:
1.72 moko 928: // filling $.cookies
1.89 moko 929: if(vcookies=vtables->hash().get("SET-COOKIE"))
1.133 moko 930: HASH_PUT_CSTR(*result.headers, HTTP_COOKIES_NAME, new VTable(parse_cookies(r, vcookies->get_table())));
1.72 moko 931:
1.1 paf 932: // output response
933: String::C real_body=String::C(raw_body, raw_body_size);
1.16 misha 934:
935: if(as_text && transcode_text_result && raw_body_size) { // raw_body_size must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
1.22 misha 936: real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.1 paf 937: }
938:
939: result.str=const_cast<char *>(real_body.str); // hacking a little
940: result.length=real_body.length;
1.16 misha 941:
1.22 misha 942: if(as_text && result.length)
943: fix_line_breaks(result.str, result.length);
944:
1.1 paf 945: result.headers->put(file_status_name, new VInt(status_code));
1.16 misha 946:
1.1 paf 947: return result;
948: }
1.84 moko 949:
950: /* ********************** httpd *************************** */
951:
1.100 moko 952: enum EscapeState {
953: Initial,
954: Default,
955: EscapeFirst,
956: EscapeSecond
957: };
958:
959: static bool check_uri(const char *uri){
960: EscapeState state=Initial;
1.120 moko 961: uint escapedValue=0;
1.100 moko 962:
963: const char *pattern="/../";
964: const char *pos=pattern;
965:
966: while(*uri){
967: uchar c=(uchar)*(uri++);
968: switch(state) {
969: case Initial:
970: if(c!='/')
971: return false;
972: state=Default;
973: break;
974: case Default:
975: if(c=='%'){
976: state=EscapeFirst;
977: continue;
978: }
979: if(c=='?')
980: return true;
981: break;
982: case EscapeFirst:
983: if(isxdigit(c)){
984: state=EscapeSecond;
985: escapedValue=hex_value[c] << 4;
986: continue;
987: }
988: return false;
989: case EscapeSecond:
990: if(isxdigit(c)){
991: state=Default;
1.105 moko 992: c=(uchar)(escapedValue + hex_value[c]);
1.100 moko 993:
994: // implementing Apache AllowEncodedSlashes Off just in case
995: if(c=='/' || c=='\\')
996: return false;
997:
998: break;
999: }
1000: return false;
1001: }
1002:
1003: if(c==*pos || c=='\\' && *pos=='/'){
1004: if(!*(++pos))
1005: return false;
1006: } else {
1007: pos=pattern;
1008: }
1009: }
1010: return true;
1011: }
1012:
1.84 moko 1013: class HTTPD_request : public HTTP_response {
1014: public:
1015: const char *method;
1016: const char *uri;
1017:
1.97 moko 1018: HTTPD_request() : HTTP_response(), method(NULL), uri(NULL){};
1.84 moko 1019:
1.120 moko 1020: ssize_t pa_recv(SOCKET sockfd, char *buf, size_t len);
1.103 moko 1021:
1.120 moko 1022: bool read(SOCKET sock, size_t size){
1.103 moko 1023: if(length + size > buf_size)
1024: resize(buf_size * 2 + size);
1025: ssize_t received_size=pa_recv(sock, buf + length, size);
1026: if(received_size == 0)
1027: return false;
1028: if(received_size < 0) {
1029: if(int no = pa_socks_errno())
1.111 moko 1030: throw Exception("httpd.read", 0, "error receiving request: %s (%d)", pa_socks_strerr(no), no);
1.103 moko 1031: return false;
1032: }
1033: length+=received_size;
1034: buf[length]='\0';
1035: return true;
1036: }
1037:
1.84 moko 1038: const char *extract_method(char *method_line){
1039: char* uri_start = strchr(method_line, ' ');
1040:
1041: if(!uri_start || uri_start == method_line)
1042: return NULL;
1043:
1044: char* uri_end=strchr(uri_start+1, ' ');
1045:
1046: if(!uri_end || uri_end == uri_start+1)
1047: return NULL;
1048:
1049: uri=pa_strdup(uri_start+1, uri_end-uri_start-1);
1.100 moko 1050: if(!check_uri(uri))
1051: throw Exception("httpd.request", 0, "invalid uri '%s'", uri);
1052:
1.84 moko 1053: return str_upper(method_line, uri_start-method_line);
1054: }
1055:
1.103 moko 1056:
1.120 moko 1057: bool read_header(SOCKET);
1058: size_t read_post(SOCKET, char *, size_t);
1.84 moko 1059: };
1060:
1061: enum HTTPD_request_state {
1062: HTTPD_METHOD,
1063: HTTPD_HEADERS
1064: };
1065:
1.120 moko 1066: ssize_t HTTPD_request::pa_recv(SOCKET sockfd, char *buffer, size_t len){
1.111 moko 1067: LOG(pa_log("httpd [%d] recv %d appending to %d ...", sockfd, len, length));
1.107 moko 1068:
1069: #ifdef PA_USE_ALARM
1.118 moko 1070: if(PA_NO_THREADS) signal(SIGALRM, timeout_handler);
1071: if(PA_NO_THREADS && sigsetjmp(timeout_env, 1)) {
1.111 moko 1072: LOG(pa_log("httpd [%d] recv got %d sec timeout", sockfd, pa_httpd_timeout));
1073: if(length) // timeout on "void" connection is normal
1074: throw Exception("httpd.timeout", 0, "timeout occurred while receiving request");
1075: return 0;
1.103 moko 1076: } else
1.107 moko 1077: #endif
1.103 moko 1078: {
1.107 moko 1079: ALARM(pa_httpd_timeout);
1.104 moko 1080: ssize_t result=recv(sockfd, buffer, len, 0);
1.107 moko 1081: ALARM(0);
1.111 moko 1082: LOG(pa_log("httpd [%d] recv got %d bytes", sockfd, result));
1.112 moko 1083: LOG(pa_log("httpd [%d] %s", sockfd, buffer));
1.103 moko 1084: return result;
1085: }
1086: }
1087:
1.115 moko 1088: static bool valid_http_method(const char * method){
1089: return method && (
1090: !strcmp(method, "GET") ||
1091: !strcmp(method, "HEAD") ||
1092: !strcmp(method, "POST") ||
1093: !strcmp(method, "PUT") ||
1094: !strcmp(method, "DELETE") ||
1095: !strcmp(method, "CONNECT") ||
1096: !strcmp(method, "OPTIONS") ||
1097: !strcmp(method, "TRACE") ||
1098: !strcmp(method, "PATCH")
1099: );
1100: }
1101:
1.120 moko 1102: bool HTTPD_request::read_header(SOCKET sock) {
1.84 moko 1103: enum HTTPD_request_state state = HTTPD_METHOD;
1104:
1105: size_t chunk_size = 0x400*4;
1106: resize(chunk_size);
1107:
1108: while(read(sock, chunk_size)){
1109: switch(state){
1110: case HTTPD_METHOD: {
1111: size_t method_size = first_line();
1112: if(!method_size)
1113: break;
1114:
1115: char *method_line = pa_strdup(buf, method_size);
1116: method = extract_method(method_line);
1117:
1.115 moko 1118: if(!valid_http_method(method))
1.84 moko 1119: throw Exception("httpd.method", new String(method ? method : method_line), "invalid request method");
1120: state = HTTPD_HEADERS;
1121: }
1122:
1123: case HTTPD_HEADERS: {
1124: if(!body_start())
1125: break;
1126:
1127: parse_headers();
1.110 moko 1128: return true;
1.84 moko 1129: }
1130: }
1131: }
1132:
1.111 moko 1133: if(!length){ // browsers open connections in advance and they will be empty unless user requests more pages
1134: LOG(pa_log("httpd [%d] void request", sock));
1.110 moko 1135: return false;
1.111 moko 1136: }
1.110 moko 1137:
1.84 moko 1138: if(state == HTTPD_METHOD)
1139: throw Exception("httpd.request", 0, "bad request from host - no method found (size=%u)", length);
1140:
1141: if(state == HTTPD_HEADERS){
1142: parse_headers();
1143: body_offset=length;
1144: }
1.110 moko 1145:
1146: return true;
1.84 moko 1147: }
1148:
1.120 moko 1149: size_t HTTPD_request::read_post(SOCKET sock, char *body, size_t max_bytes) {
1.87 moko 1150: size_t total_read = min(length - body_offset, max_bytes);
1.98 moko 1151: memcpy(body, buf + body_offset, total_read);
1.87 moko 1152:
1153: while (total_read < max_bytes){
1.103 moko 1154: ssize_t received_size = pa_recv(sock, body + total_read, max_bytes - total_read);
1.87 moko 1155: if(received_size == 0)
1156: return total_read;
1157: if(received_size < 0) {
1158: if(int no = pa_socks_errno())
1.111 moko 1159: throw Exception("httpd.read", new String(uri), "error receiving request body: %s (%d)", pa_socks_strerr(no), no);
1.87 moko 1160: return total_read;
1161: }
1162: total_read += received_size;
1163: }
1164: return total_read;
1165: }
1166:
1.84 moko 1167: /* ********************************************************** */
1168:
1.85 moko 1169: Array<HTTP_Headers::Header> &HTTPD_Connection::headers() {
1.84 moko 1170: return request->headers.headers;
1171: }
1172:
1173: const char *HTTPD_Connection::method() {
1174: return request->method;
1175: }
1176:
1177: const char *HTTPD_Connection::uri() {
1178: return request->uri;
1179: }
1180:
1181: const char *HTTPD_Connection::content_type() {
1182: return request->headers.content_type.cstr();
1183: }
1184:
1185: uint64_t HTTPD_Connection::content_length(){
1186: return request->headers.content_length;
1187: }
1188:
1.110 moko 1189: bool HTTPD_Connection::read_header(){
1.84 moko 1190: request = new HTTPD_request();
1.111 moko 1191: bool result = request->read_header(sock);
1192: LOG(if(result){
1193: pa_log("httpd [%d] got %s \"%s\"", sock, method(), uri());
1194: })
1195: return result;
1.84 moko 1196: }
1197:
1.87 moko 1198: size_t HTTPD_Connection::read_post(char *body, size_t max_bytes) {
1199: return request->read_post(sock, body, max_bytes);
1200: }
1201:
1.90 moko 1202: size_t HTTPD_Connection::send_body(const void *buf, size_t size) {
1.112 moko 1203: LOG(pa_log("httpd [%d] response %d bytes", sock, size));
1204: LOG(pa_log("httpd [%d] %s", sock, buf));
1.131 moko 1205: ssize_t result=pa_send(sock, (const char*)buf, size);
1206: if(result < 0) {
1.90 moko 1207: int no=pa_socks_errno();
1.111 moko 1208: throw Exception("httpd.write", 0, "error sending response: %s (%d)", pa_socks_strerr(no), no);
1.90 moko 1209: }
1.131 moko 1210: return result;
1.90 moko 1211: }
1212:
1.93 moko 1213: HTTPD_Connection::~HTTPD_Connection(){
1.120 moko 1214: if(sock != INVALID_SOCKET){
1.111 moko 1215: LOG(pa_log("httpd [%d] closed", sock));
1.93 moko 1216: closesocket(sock);
1.111 moko 1217: }
1.93 moko 1218: }
1219:
1.132 moko 1220: static int sock_ready(SOCKET fd, int timeout_value){
1.93 moko 1221: struct timeval timeout = {0, timeout_value * 1000};
1222: fd_set fds;
1223: FD_ZERO(&fds);
1224: FD_SET(fd, &fds);
1.120 moko 1225: int nfds = (int)fd + 1; /* typecast as nfds is ignored in MSVC anyway */
1.132 moko 1226: return select(nfds, &fds, NULL, NULL, &timeout)>0; /* read */
1.93 moko 1227: }
1228:
1.120 moko 1229: bool HTTPD_Connection::accept(SOCKET server_sock, int timeout_value) {
1.132 moko 1230: int ready = sock_ready(server_sock, timeout_value);
1.93 moko 1231: if (ready < 0) {
1232: int no=pa_socks_errno();
1233: if(no == EINTR)
1234: return false;
1235: throw Exception("httpd.accept", 0, "error waiting for connection: %s (%d)", pa_socks_strerr(no), no);
1236: }
1237: if (ready == 0)
1238: return false; /* Timeout */
1239:
1240: struct sockaddr_in addr;
1241: socklen_t sock_addr_len = sizeof(struct sockaddr_in);
1242: memset(&addr, 0, sock_addr_len);
1243:
1244: sock = ::accept(server_sock, (struct sockaddr *)&addr, &sock_addr_len);
1.120 moko 1245: if(sock == INVALID_SOCKET){
1.93 moko 1246: int no=pa_socks_errno();
1247: throw Exception("httpd.accept", 0, "error accepting connection: %s (%d)", pa_socks_strerr(no), no);
1248: }
1249:
1.123 moko 1250: // Has no positive performance effect, requires include <netinet/tcp.h>
1251: // static int sock_on=1;
1252: // setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&sock_on, sizeof(sock_on));
1253:
1.93 moko 1254: remote_addr = pa_strdup(inet_ntoa(addr.sin_addr));
1.111 moko 1255: LOG(pa_log("httpd [%d] accepted from %s", sock, remote_addr));
1.93 moko 1256: return true;
1257: }
1.84 moko 1258:
1.107 moko 1259: HTTPD_Server::HTTPD_MODE HTTPD_Server::mode = HTTPD_Server::SEQUENTIAL;
1.114 moko 1260: const char *HTTPD_Server::port=NULL;
1.106 moko 1261:
1.108 moko 1262: void HTTPD_Server::set_mode(const String &value){
1263: if(value == "sequental") mode = SEQUENTIAL;
1.113 moko 1264: #ifdef HAVE_TLS
1.108 moko 1265: else if (value == "threaded") mode = MULTITHREADED;
1.113 moko 1266: #endif
1.108 moko 1267: #ifdef _MSC_VER
1.117 moko 1268: else throw Exception("httpd.mode", &value, "$MAIN:HTTPD.mode must be 'sequental' or 'threaded'");
1.108 moko 1269: #else
1270: else if (value == "parallel") mode = PARALLEL;
1.117 moko 1271: else throw Exception("httpd.mode", &value, "$MAIN:HTTPD.mode must be 'sequental', 'parallel' or 'threaded'");
1.108 moko 1272: #endif
1273: }
1274:
1.120 moko 1275: SOCKET HTTPD_Server::bind(const char *host_port){
1.84 moko 1276: struct sockaddr_in me;
1277:
1.114 moko 1278: port = strchr(host_port, ':');
1.86 moko 1279: const char *host = NULL;
1.116 moko 1280: if(port){
1.114 moko 1281: if(port > host_port)
1282: host = pa_strdup(host_port, port - host_port);
1.86 moko 1283: port += 1;
1284: } else {
1285: port = host_port;
1286: }
1287:
1.105 moko 1288: if(!set_addr(&me, host, (short)pa_atoui(port))){
1.84 moko 1289: if (host)
1.127 moko 1290: throw Exception("httpd.bind", 0, "cannot resolve hostname \"%s\"", host);
1.84 moko 1291: me.sin_addr.s_addr=INADDR_ANY;
1292: }
1293:
1.120 moko 1294: SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/);
1.84 moko 1295:
1.120 moko 1296: if(sock == INVALID_SOCKET){
1.84 moko 1297: int no=pa_socks_errno();
1.127 moko 1298: throw Exception("httpd.bind", 0, "cannot make socket: %s (%d)", pa_socks_strerr(no), no);
1.84 moko 1299: }
1300:
1.93 moko 1301: static int sock_on = 1;
1302:
1.84 moko 1303: if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&sock_on, sizeof(sock_on)) ||
1304: setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&sock_on, sizeof(sock_on)) ||
1305: ::bind(sock, (struct sockaddr*)&me, sizeof(me)) ||
1306: listen(sock, 16)) {
1.89 moko 1307: closesocket(sock);
1.84 moko 1308: int no = pa_socks_errno();
1.127 moko 1309: throw Exception("httpd.bind", 0, "cannot bind socket: %s (%d)", pa_socks_strerr(no), no);
1.84 moko 1310: }
1311: return sock;
1312: }
E-mail: