Annotation of parser3/src/main/pa_request.C, revision 1.468
1.54 paf 1: /** @file
1.55 paf 2: Parser: request class main part. @see compile.C and execute.C.
3:
1.439 moko 4: Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)
1.418 moko 5: Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.218 paf 6: */
1.55 paf 7:
1.69 paf 8: #include "pa_sapi.h"
1.53 paf 9: #include "pa_common.h"
1.372 moko 10: #include "pa_os.h"
1.1 paf 11: #include "pa_request.h"
1.3 paf 12: #include "pa_wwrapper.h"
13: #include "pa_vclass.h"
1.31 paf 14: #include "pa_globals.h"
1.30 paf 15: #include "pa_vint.h"
1.297 misha 16: #include "pa_vmethod_frame.h"
1.32 paf 17: #include "pa_types.h"
1.248 paf 18: #include "pa_venv.h"
19: #include "pa_vmath.h"
20: #include "pa_vstatus.h"
21: #include "pa_vrequest.h"
1.78 paf 22: #include "pa_vtable.h"
1.90 paf 23: #include "pa_vfile.h"
1.147 parser 24: #include "pa_dictionary.h"
1.208 paf 25: #include "pa_charset.h"
1.186 paf 26: #include "pa_charsets.h"
1.248 paf 27: #include "pa_cache_managers.h"
1.402 moko 28: #include "pa_http.h"
1.464 moko 29: #include "pa_websocket.h"
1.248 paf 30: #include "pa_vmail.h"
31: #include "pa_vform.h"
32: #include "pa_vcookie.h"
33: #include "pa_vresponse.h"
34: #include "pa_vmemory.h"
1.253 paf 35: #include "pa_vconsole.h"
1.267 paf 36: #include "pa_vdate.h"
1.424 moko 37: #include "pa_varray.h"
1.458 moko 38: #include "pa_code_cache.h"
1.159 parser 39:
1.468 ! moko 40: volatile const char * IDENT_PA_REQUEST_C="$Id: pa_request.C,v 1.467 2026/10/22 23:20:42 moko Exp $" IDENT_PA_REQUEST_H IDENT_PA_REQUEST_CHARSETS_H IDENT_PA_REQUEST_INFO_H IDENT_PA_VCONSOLE_H;
1.329 moko 41:
1.248 paf 42: // consts
43:
1.269 paf 44: #define UNHANDLED_EXCEPTION_METHOD_NAME "unhandled_exception"
1.207 paf 45:
1.82 paf 46: /// content type of response when no $MAIN:defaults.content-type defined
1.248 paf 47: const char* DEFAULT_CONTENT_TYPE="text/html";
48:
1.449 moko 49: // One recursion level uses ~0.85KB of stack under linux/gcc, ~1KB under win32 and ~2KB under win64.
50: // MSVC win64 exception handling requires an extra ~10KB !!! for each throw, and execute() catches and
51: // rethrows on every level to provide a stack trace.
1.450 moko 52: // So 1000 levels need ~1MB under linux (default 8MB stack is enough) and ~2+10=12MB under win64.
53: // Worse, win64 keeps the unwound frames until the catch block returns, so a handler running away
54: // in its turn starts on top of them and needs one more such budget. The stack is set to 40MB in
55: // the MSVC project settings to allow nested three runaways.
1.449 moko 56: const int EXECUTE_RECURSION_LIMIT=1000;
57: const int EXECUTE_RECURSION_RESERVE=100;
58:
1.446 moko 59: const int LOOP_LIMIT=100000;
60: const int ARRAY_LIMIT=1000000;
61: const int HTTPD_TIMEOUT=4;
1.465 moko 62: const size_t FILE_SIZE_LIMIT=512*0x400*0x400; // 512MB
63: const size_t POST_MAX_SIZE=10*0x400*0x400; // 10MB
1.361 moko 64:
1.248 paf 65: // defines for globals
66:
67: #define MAIN_METHOD_NAME "main"
68: #define AUTO_METHOD_NAME "auto"
1.364 moko 69: #define USE_METHOD_NAME "use"
1.309 misha 70: #define AUTOUSE_METHOD_NAME "autouse"
1.364 moko 71:
72: #define ORIGIN_KEY "origin"
73:
1.248 paf 74: // globals
75:
76: const String main_method_name(MAIN_METHOD_NAME);
77: const String auto_method_name(AUTO_METHOD_NAME);
1.364 moko 78: static const String use_method_name(USE_METHOD_NAME);
79: static const String autouse_method_name(AUTOUSE_METHOD_NAME);
1.311 misha 80:
1.364 moko 81: static const String origin_key(ORIGIN_KEY);
82:
1.369 moko 83: int pa_loop_limit=LOOP_LIMIT;
1.425 moko 84: int pa_array_limit=ARRAY_LIMIT;
1.427 moko 85: int pa_execute_recursion_limit=EXECUTE_RECURSION_LIMIT;
1.390 moko 86: int pa_httpd_timeout=HTTPD_TIMEOUT;
1.369 moko 87: size_t pa_file_size_limit=FILE_SIZE_LIMIT;
1.465 moko 88: size_t pa_post_max_size=POST_MAX_SIZE;
1.361 moko 89:
1.248 paf 90: // defines for statics
91:
92: #define MIME_TYPES_NAME "MIME-TYPES"
93: #define CLASS_PATH_NAME "CLASS_PATH"
94:
1.344 moko 95: #define DOWNLOAD_NAME_UPPER "DOWNLOAD"
96: #define BODY_NAME_UPPER "BODY"
97:
1.248 paf 98: // statics
99:
100: static const String main_class_name(MAIN_CLASS_NAME);
101: static const String mime_types_name(MIME_TYPES_NAME);
1.395 moko 102: static const String class_path_name(CLASS_PATH_NAME);
1.361 moko 103:
1.395 moko 104: static const String charsets_name("CHARSETS");
105: static const String strict_vars_name("STRICT-VARS");
106: static const String prototype_name("OBJECT-PROTOTYPE");
1.415 moko 107: static const String getter_protected_name("CLASS-GETTER-PROTECTED");
108: static const String locals_name("LOCALS");
1.395 moko 109: static const String limits_name("LIMITS");
110: static const String loop_limit_name("max_loop");
1.425 moko 111: static const String array_limit_name("max_array_size");
1.427 moko 112: static const String recursion_limit_name("max_recursion");
1.395 moko 113: static const String file_size_limit_name("max_file_size");
1.465 moko 114: static const String post_max_size_name("post_max_size");
1.395 moko 115: static const String lock_wait_timeout_name("lock_wait_timeout");
116: static const String httpd_name("HTTPD");
117: static const String httpd_timeout_name("timeout");
1.402 moko 118: static const String httpd_mode_name("mode");
1.458 moko 119: #ifdef CODE_CACHE
120: static const String httpd_code_cache_name("code-cache");
121: #endif
1.395 moko 122:
123: static const String conf_method_name("conf");
124: static const String post_process_method_name("postprocess");
125: static const String response_body_file_name("file");
1.248 paf 126:
1.344 moko 127: static const String download_name_upper(DOWNLOAD_NAME_UPPER);
128: static const String body_name_upper(BODY_NAME_UPPER);
129:
130: // more static
131:
132: static const String content_type_name_upper(HTTP_CONTENT_TYPE_UPPER);
133: static const String content_disposition_name_upper(CONTENT_DISPOSITION_UPPER);
1.392 moko 134: static const String content_disposition_inline(CONTENT_DISPOSITION_INLINE);
1.344 moko 135: static const String content_disposition_attachment(CONTENT_DISPOSITION_ATTACHMENT);
136:
1.420 moko 137: const String content_disposition_filename_name(CONTENT_DISPOSITION_FILENAME_NAME);
138: const String content_disposition_filename_name_asterisk("filename*");
139:
1.248 paf 140: // defines
1.82 paf 141:
1.344 moko 142: #define CHARSET_NAME_UPPER "CHARSET"
143: #define LAST_MODIFIED_NAME_UPPER "LAST-MODIFIED"
144:
1.233 paf 145: // op.C
1.248 paf 146: VStateless_class& VClassMAIN_create();
1.123 paf 147:
1.157 parser 148: //
1.445 moko 149: void Request::recursion_limit_reached() {
150: if(execute_recursion_limit>pa_execute_recursion_limit)
151: throw Recursion_limit_exception();
152:
153: execute_recursion_limit+=EXECUTE_RECURSION_RESERVE;
154: throw Exception(PARSER_RUNTIME, 0, "call canceled - endless recursion detected");
155: }
156:
1.408 moko 157: Request::Request(SAPI_Info& asapi_info, Request_info& arequest_info, String::Language adefault_lang):
1.248 paf 158: // private
1.427 moko 159: anti_endless_execute_recursion(0),
1.445 moko 160: execute_recursion_limit(pa_execute_recursion_limit),
1.248 paf 161:
162: // public
1.335 moko 163: allow_class_replace(false),
1.248 paf 164: method_frame(0),
165: rcontext(0),
166: wcontext(0),
1.191 paf 167: fconnection(0),
1.371 moko 168: fin_cycle(0),
1.307 misha 169: fskip(SKIP_NOTHING),
1.248 paf 170:
171: // public
1.257 paf 172: request_info(arequest_info),
1.248 paf 173: sapi_info(asapi_info),
1.359 moko 174: charsets(pa_UTF8_charset, pa_UTF8_charset, pa_UTF8_charset), // default charsets
1.248 paf 175:
176: main_class(VClassMAIN_create()),
1.260 paf 177: form(*new VForm(charsets, arequest_info)),
1.248 paf 178: mail(*new VMail),
1.462 moko 179: response(*new VResponse(arequest_info, charsets, adefault_lang)),
1.298 misha 180: cookie(*new VCookie(charsets, arequest_info)),
1.285 misha 181: console(*new VConsole),
1.464 moko 182: websocket(0),
1.248 paf 183:
184: // private
185: configure_admin_done(false),
186:
187: // private mime types
1.464 moko 188: mime_types(0)
1.157 parser 189: {
1.261 paf 190: pa_register_thread_request(*this);
191:
1.248 paf 192: // file_no=0 => unknown
1.434 moko 193: file_list+=String::Body("UNKNOWN");
194: file_list+=String::Body("-body of process-"); // pseudo_file_no__process
1.458 moko 195: #ifdef CODE_CACHE
196: Code_cache_manager::add_files(file_list);
197: #endif
1.186 paf 198:
1.178 paf 199: // maybe expire old caches
1.264 paf 200: cache_managers->maybe_expire();
1.178 paf 201:
1.157 parser 202: /// directly used
1.233 paf 203: // MAIN class, operators
1.353 moko 204: put_class(&main_class);
1.157 parser 205: // classes:
206: // table, file, random, mail, image, ...
1.248 paf 207: methoded_array().register_directly_used(*this);
1.157 parser 208:
209: /// methodless
1.354 moko 210:
1.157 parser 211: // env class
1.353 moko 212: put_class(new VEnv(asapi_info));
1.175 paf 213: // status class
1.353 moko 214: put_class(new VStatus());
1.157 parser 215: // request class
1.353 moko 216: put_class(new VRequest(arequest_info, charsets, form, asapi_info));
1.157 parser 217: // cookie class
1.353 moko 218: put_class(&cookie);
1.253 paf 219: // console class
1.353 moko 220: put_class(&console);
1.354 moko 221:
1.157 parser 222: /// methoded
1.354 moko 223:
1.157 parser 224: // response class
1.353 moko 225: put_class(&response);
1.157 parser 226: // form class
1.353 moko 227: put_class(&form);
1.213 paf 228: // mail class
1.353 moko 229: put_class(&mail);
1.157 parser 230: // math class
1.353 moko 231: put_class(new VMath);
1.248 paf 232: // memory class
1.353 moko 233: put_class(new VMemory);
1.117 paf 234: }
1.192 paf 235:
236: Request::~Request() {
237: #ifdef XML
238: // if for some strange reason xml generic errors failed to be reported, free them up
1.248 paf 239: if(const char* xml_generic_errors=xmlGenericErrors()) {
240: SAPI::log(sapi_info, "warning: unreported xmlGenericErrors: %s", xml_generic_errors);
1.341 moko 241: pa_free((void *)xml_generic_errors);
1.192 paf 242: }
243: #endif
244: }
1.236 paf 245:
1.248 paf 246: Value& Request::get_self() { return method_frame/*always have!*/->self(); }
1.192 paf 247:
1.355 moko 248: VStateless_class* Request::get_class(const String& name){
249: VStateless_class* result=classes().get(name);
1.313 misha 250: if(!result)
1.375 moko 251: if(const Method *method=main_class.get_element_method(autouse_method_name)){
1.364 moko 252: Value *vname=new VString(name);
253: CONSTRUCTOR_FRAME_ACTION(*method, 0 /*no parent*/, main_class, {
254: frame.store_params(&vname, 1);
255: // we don't need the result
256: call(frame);
257: });
258: result=classes().get(name);
259: }
1.309 misha 260: return result;
261: }
262:
1.411 moko 263: VStateless_class& Request::get_class_ref(const String& name){
264: VStateless_class* result=get_class(name);
265: if(!result)
266: throw Exception(PARSER_RUNTIME, &name, "class is undefined");
267: return *result;
268: }
269:
1.424 moko 270: bool Request::add_class(const char* atype, VStateless_class *aclass){
1.436 moko 271: if(!classes().put_dont_replace(String::Body(atype), aclass))
272: return true;
1.437 moko 273: if(!allow_class_replace && strcmp(atype, VARRAY_TYPE))
274: return false;
1.436 moko 275: classes().remove(String::Body(atype));
1.424 moko 276: classes().put(atype, aclass);
277: return true;
278: }
279:
1.356 moko 280: static void load_charset(HashStringValue::key_type akey, HashStringValue::value_type avalue, Request_charsets* charsets) {
1.359 moko 281: pa_charsets.load_charset(*charsets, akey, avalue->as_string());
1.208 paf 282: }
1.356 moko 283:
1.395 moko 284:
285: #define CONF_OPTION(config, name, code, exception_name) \
286: if(config) \
287: if(Value* option=config->get_element(name)) { \
288: if(option->is_evaluated_expr()) { \
289: code; \
290: } else \
1.415 moko 291: throw Exception(PARSER_RUNTIME, 0, "$MAIN:" exception_name, name.cstr()); \
1.395 moko 292: }
293:
1.248 paf 294: void Request::configure_admin(VStateless_class& conf_class) {
1.208 paf 295: if(configure_admin_done)
1.356 moko 296: throw Exception(PARSER_RUNTIME, 0, "parser already configured");
1.208 paf 297: configure_admin_done=true;
298:
1.227 paf 299: // charsets must only be specified in method_frame config
1.208 paf 300: // so that users would not interfere
301:
302: /* $MAIN:CHARSETS[
303: $.charsetname1[/full/path/to/charset/file.cfg]
304: ...
305: ]
306: */
1.308 misha 307: if(Value* vcharsets=conf_class.get_element(charsets_name)) {
1.342 moko 308: if(!vcharsets->is_string()) {
1.248 paf 309: if(HashStringValue* charsets=vcharsets->get_hash())
1.281 paf 310: charsets->for_each<Request_charsets*>(load_charset, &this->charsets);
1.240 paf 311: else
1.415 moko 312: throw Exception(PARSER_RUNTIME, 0, "$MAIN:%s must be hash", charsets_name.cstr());
1.342 moko 313: }
1.208 paf 314: }
315:
1.330 moko 316: #ifdef STRICT_VARS
1.332 moko 317: VVoid::strict_vars=false;
1.330 moko 318: if(Value* strict_vars=conf_class.get_element(strict_vars_name)) {
319: if(strict_vars->is_bool())
320: VVoid::strict_vars=strict_vars->as_bool();
1.357 moko 321: else
1.415 moko 322: throw Exception(PARSER_RUNTIME, 0, "$MAIN:%s must be bool", strict_vars_name.cstr());
1.357 moko 323: }
324: #endif
325:
326: #ifdef OBJECT_PROTOTYPE
327: VClass::prototype=true;
328: if(Value* prototype=conf_class.get_element(prototype_name)) {
329: if(prototype->is_bool())
330: VClass::prototype=prototype->as_bool();
331: else
1.415 moko 332: throw Exception(PARSER_RUNTIME, 0, "$MAIN:%s must be bool", prototype_name.cstr());
1.330 moko 333: }
334: #endif
335:
1.415 moko 336: #ifdef CLASS_GETTER_UNPROTECTED
337: VClass::getter_protected=true;
338: if(Value* getter_protected=conf_class.get_element(getter_protected_name)) {
339: if(getter_protected->is_bool())
340: VClass::getter_protected=getter_protected->as_bool();
341: else
342: throw Exception(PARSER_RUNTIME, 0, "$MAIN:%s must be bool", getter_protected_name.cstr());
343: }
344: #endif
345:
346: VStateless_class::gall_vars_local=false;
347: if(Value* locals=conf_class.get_element(locals_name)) {
348: if(locals->is_bool()){
349: VStateless_class::gall_vars_local=locals->as_bool();
350: main_class.set_all_vars_local();
351: } else
352: throw Exception(PARSER_RUNTIME, 0, "$MAIN:%s must be bool", locals_name.cstr());
353: }
354:
1.362 moko 355: Value* limits=conf_class.get_element(limits_name);
356:
1.361 moko 357: pa_loop_limit=LOOP_LIMIT;
1.395 moko 358: CONF_OPTION(limits, loop_limit_name, {
359: pa_loop_limit=option->as_int();
360: if(pa_loop_limit==0) pa_loop_limit=INT_MAX;
361: }, "LIMITS.%s must be int");
1.361 moko 362:
1.425 moko 363: pa_array_limit=ARRAY_LIMIT;
364: CONF_OPTION(limits, array_limit_name, {
365: pa_array_limit=option->as_int();
366: if(pa_array_limit==0) pa_array_limit=INT_MAX;
367: }, "LIMITS.%s must be int");
368:
1.427 moko 369: pa_execute_recursion_limit=EXECUTE_RECURSION_LIMIT;
370: CONF_OPTION(limits, recursion_limit_name, {
371: pa_execute_recursion_limit=option->as_int();
1.445 moko 372: if(pa_execute_recursion_limit<=0) pa_execute_recursion_limit=INT_MAX;
373: pa_execute_recursion_limit=min(pa_execute_recursion_limit, INT_MAX-EXECUTE_RECURSION_RESERVE);
1.395 moko 374: }, "LIMITS.%s must be int");
1.445 moko 375: execute_recursion_limit=pa_execute_recursion_limit;
1.390 moko 376:
1.369 moko 377: pa_file_size_limit=FILE_SIZE_LIMIT;
1.395 moko 378: CONF_OPTION(limits, file_size_limit_name, {
379: double limit=option->as_double();
380: if(limit >= (double)SSIZE_MAX)
1.448 moko 381: throw Exception(PARSER_RUNTIME, 0, "$MAIN:LIMITS.%s must be less than %s", file_size_limit_name.cstr(), pa_itoa(SSIZE_MAX));
1.395 moko 382: pa_file_size_limit=(size_t)limit;
383: if(pa_file_size_limit==0)
384: pa_file_size_limit=SSIZE_MAX;
385: }, "LIMITS.%s must be number");
1.361 moko 386:
1.465 moko 387: pa_post_max_size=POST_MAX_SIZE;
388: CONF_OPTION(limits, post_max_size_name, {
389: double limit=option->as_double();
390: if(limit >= (double)SSIZE_MAX)
391: throw Exception(PARSER_RUNTIME, 0, "$MAIN:LIMITS.%s must be less than %s", post_max_size_name.cstr(), pa_itoa(SSIZE_MAX));
392: if(limit > 0)
393: pa_post_max_size=(size_t)limit;
394: }, "LIMITS.%s must be number");
395:
1.372 moko 396: pa_lock_attempts=PA_LOCK_ATTEMPTS;
1.395 moko 397: CONF_OPTION(limits, lock_wait_timeout_name, {
398: double limit=option->as_double();
399: if(limit >= 3600*24)
1.426 moko 400: throw Exception(PARSER_RUNTIME, 0, "$MAIN:LIMITS.%s must be less than %d", lock_wait_timeout_name.cstr(), 3600*24);
1.395 moko 401: pa_lock_attempts=(unsigned int)(limit*2)+1;
402: }, "LIMITS.%s must be number");
403:
404: Value* httpd=conf_class.get_element(httpd_name);
405:
406: pa_httpd_timeout=HTTPD_TIMEOUT;
407: CONF_OPTION(httpd, httpd_timeout_name, {
408: pa_httpd_timeout=option->as_int();
409: if(pa_httpd_timeout==0) pa_httpd_timeout=INT_MAX;
410: }, "HTTPD.%s must be int");
1.372 moko 411:
1.403 moko 412: if(httpd)
413: if(Value* option=httpd->get_element( httpd_mode_name)) {
414: if(option->get_junction())
1.415 moko 415: throw Exception(PARSER_RUNTIME, 0, "$MAIN:HTTPD:mode must be string");
1.403 moko 416: HTTPD_Server::set_mode(option->as_string());
417: }
1.402 moko 418:
1.458 moko 419: #ifdef CODE_CACHE
420: CONF_OPTION(httpd, httpd_code_cache_name, {
421: Code_cache_manager::set_enabled(option->as_bool());
422: }, "HTTPD.%s must be bool");
423: #endif
424:
1.227 paf 425: // configure method_frame options
1.208 paf 426: // until someone with less privileges have overriden them
1.248 paf 427: methoded_array().configure_admin(*this);
1.208 paf 428: }
1.150 parser 429:
1.442 moko 430: const char* Request::get_exception_cstr(const Exception& e, VException& details) {
1.349 moko 431:
1.269 paf 432: #define PA_URI_FORMAT "%s: "
1.349 moko 433: #define PA_COMMENT_TYPE_FORMAT "%s [%s]"
434:
1.269 paf 435: #define PA_ORIGIN_FILE_POS_FORMAT "%s(%d:%d): "
436: #define PA_SOURCE_FORMAT "'%s' "
1.349 moko 437:
438: #define PA_ORIGIN_FILE_POS_VALUE file_list[details.origin.file_no].cstr(), 1+details.origin.line, 1+details.origin.col,
439: #define PA_SOURCE_VALUE details.problem_source->cstr(),
440:
441: #define EXCEPTION_CSTR(f1,v1,f2,v2) \
1.466 moko 442: pa_snprintf(result, MAX_STRING, \
1.349 moko 443: PA_URI_FORMAT \
444: f1 f2 \
445: PA_COMMENT_TYPE_FORMAT, \
446: request_info.uri, \
447: v1 v2 \
448: e.comment(), e.type() \
449: );
450:
1.269 paf 451: char* result=new(PointerFreeGC) char[MAX_STRING];
452:
453: if(details.problem_source) { // do we know the guy?
1.349 moko 454: if(details.origin.file_no) // do whe know where he came from?
455: EXCEPTION_CSTR(PA_ORIGIN_FILE_POS_FORMAT, PA_ORIGIN_FILE_POS_VALUE, PA_SOURCE_FORMAT, PA_SOURCE_VALUE)
456: else
457: EXCEPTION_CSTR(PA_SOURCE_FORMAT, PA_SOURCE_VALUE,,)
458: } else {
459: if(details.origin.file_no) // do whe know where he came from?
460: EXCEPTION_CSTR(PA_ORIGIN_FILE_POS_FORMAT, PA_ORIGIN_FILE_POS_VALUE,,)
461: else
462: EXCEPTION_CSTR(,,,)
463: }
1.269 paf 464:
465: return result;
466: }
1.272 paf 467:
1.444 moko 468: Table &Request::Exception_trace::table(Request &r, const String* problem_source, size_t bottom, size_t top){
1.407 moko 469: // $stack[^table::create{name file lineno colno}]
470: Table::columns_type stack_trace_columns(new ArrayString);
471: *stack_trace_columns+=new String("name");
472: *stack_trace_columns+=new String("file");
473: *stack_trace_columns+=new String("lineno");
474: *stack_trace_columns+=new String("colno");
475: Table& stack_trace=*new Table(stack_trace_columns);
476:
1.444 moko 477: if(bottom<top)
478: for(size_t i=bottom+(get(bottom).name()==problem_source); i<top; i++) {
1.407 moko 479: Trace trace=get(i);
480: Table::element_type row(new ArrayString);
481:
482: *row+=trace.name(); // name column
483: Operation::Origin origin=trace.origin();
484: if(origin.file_no) {
485: *row+=new String(r.file_list[origin.file_no], String::L_TAINTED); // 'file' column
1.422 moko 486: *row+=new String(pa_uitoa(1+origin.line), String::L_CLEAN); // 'lineno' column
487: *row+=new String(pa_uitoa(1+origin.col), String::L_CLEAN); // 'colno' column
1.407 moko 488: }
489: stack_trace+=row;
490: }
491:
492: return stack_trace;
493: }
494:
1.272 paf 495: void Request::configure() {
496: // configure admin options if not configured yet
497: if(!configure_admin_done)
498: configure_admin(main_class);
499: }
1.408 moko 500:
1.459 moko 501: /// HEAD request: only the headers are sent
502: static bool is_header_only(Request_info& info) {
503: return info.method && strcasecmp(info.method, "HEAD")==0;
504: }
505:
1.64 paf 506: /**
507: load MAIN class, execute @main.
508: MAIN class consists of all the auto.p files we'd manage to find
509: plus
510: the file user requested us to process
511: all located classes become children of one another,
512: composing class we name 'MAIN'
1.180 paf 513:
514: @test log stack trace
515:
1.64 paf 516: */
1.459 moko 517: void Request::core(const char* config_filespec, const String &amain_method_name, const String* amain_class_name) {
518: bool header_only=is_header_only(request_info);
1.169 parser 519: try {
1.211 paf 520: // loading config
1.384 moko 521: if(config_filespec)
1.454 moko 522: use_file_directly(*new String(backslashes_to_slashes(config_filespec)));
1.8 paf 523:
1.338 moko 524: // filling mail received
525: mail.fill_received(*this);
526:
1.272 paf 527: try {
528: // compile requested file
1.389 moko 529: if(request_info.path_translated)
530: use_file_directly(*new String(request_info.path_translated, String::L_TAINTED), true, true /* load auto.p files */);
1.272 paf 531: configure();
532: } catch(...) {
533: configure(); // configure anyway, useful in @unhandled_exception [say, if they would want to mail by SMTP something]
534: rethrow;
535: }
1.25 paf 536:
1.412 moko 537: VStateless_class& main = amain_class_name ? get_class_ref(*amain_class_name) : main_class;
1.25 paf 538: // execute @main[]
1.412 moko 539: const String* body_string=amain_method_name.is_empty() ? &String::Empty : execute_method(main, amain_method_name);
1.41 paf 540: if(!body_string)
1.412 moko 541: throw Exception(PARSER_RUNTIME, &amain_method_name, "method not found in class %s", main.type());
1.79 paf 542:
1.464 moko 543: if(response.started==VResponse::WEBSOCKET)
544: websocket->close(); // graceful: waits for the Close of the client
545: // ignore the result in websocket or stream mode
546: if(response.started)
1.460 moko 547: return;
548:
1.250 paf 549: // extract response body
1.344 moko 550: Value* body_value=response.fields().get(download_name_upper); // $response:download?
1.430 moko 551: bool as_attachment=body_value!=0;
1.250 paf 552: if(!body_value)
1.344 moko 553: body_value=response.fields().get(body_name_upper); // $response:body
1.250 paf 554: if(!body_value)
555: body_value=new VString(*body_string); // just result of ^main[]
556:
1.119 paf 557: // @postprocess
1.383 moko 558: if(const Method *method=main_class.get_method(post_process_method_name)) {
559: METHOD_FRAME_ACTION(*method, 0 /*no parent*/, main_class, {
560: frame.store_params(&body_value, 1);
561: call(frame);
562: body_value=&frame.result();
563: });
564: }
1.90 paf 565:
1.430 moko 566: // can throw exceptions while handling $response:download[]
1.462 moko 567: output_result(body_value->as_vfile(response.lang, &charsets), header_only, as_attachment);
1.171 parser 568: } catch(const Exception& e) { // request handling problem
1.258 paf 569:
1.445 moko 570: // OK, as native execution stack has unwound
571: anti_endless_execute_recursion=0;
572:
1.431 moko 573: // we're returning not result, but error explanation
1.442 moko 574: VException& details=*new VException(*this, e);
1.431 moko 575: const char* exception_cstr=get_exception_cstr(e, details);
576:
577: // reset response
578: response.fields().clear();
1.462 moko 579: response.lang=response.default_lang;
1.431 moko 580: SAPI::clear_headers(sapi_info);
1.407 moko 581:
1.431 moko 582: // this is what we'd return in $response:body
583: const String* body_string=0;
1.407 moko 584:
1.431 moko 585: try {
1.407 moko 586: // maybe we'd be lucky enough as to report an error in a gracefull way...
587: if(const Method *method=main_class.get_method(*new String(UNHANDLED_EXCEPTION_METHOD_NAME))) {
588: // preparing parameters to @unhandled_exception[exception;stack]
589:
1.443 moko 590: Table& stack_trace=exception_trace.table(*this, details.problem_source);
1.444 moko 591: details.expire_trace();
1.407 moko 592: exception_trace.clear(); // forget all about previous life, in case there would be error inside of this method, error handled would not be mislead by old stack contents (see extract_origin)
593:
1.442 moko 594: Value *params[]={&details, new VTable(&stack_trace)};
1.407 moko 595: METHOD_FRAME_ACTION(*method, 0 /*no caller*/, main_class, {
596: frame.store_params(params, 2);
597: call(frame);
598: body_string=&frame.result().as_string();
599: });
600: }
1.383 moko 601:
1.407 moko 602: // conditionally log it
1.442 moko 603: Value* vhandled=details.handled();
1.407 moko 604: if(!vhandled || !vhandled->as_bool()) {
605: SAPI::log(sapi_info, "%s", exception_cstr);
606: }
1.431 moko 607: } catch(const Exception& e) { // exception in @unhandled_exception
1.442 moko 608: VException& details=*new VException(*this, e);
1.431 moko 609: // logging both initial and new exceptions
610: SAPI::log(sapi_info, "%s", exception_cstr);
611: SAPI::log(sapi_info, "Exception in @unhandled_exception at %s", get_exception_cstr(e, details));
1.464 moko 612: if(!response.started)
1.460 moko 613: SAPI::send_error(sapi_info, "Exception in @unhandled_exception, details are available in Parser error log.");
1.431 moko 614: return;
615: }
1.383 moko 616:
1.431 moko 617: if(body_string) { // could report an error beautifully?
618: VString body_vstring(*body_string);
1.462 moko 619: output_result(body_vstring.as_vfile(response.lang, &charsets), header_only, false);
1.464 moko 620: } else if(!response.started) {
1.431 moko 621: // doing that ugly
622: SAPI::send_error(sapi_info, exception_cstr, strcmp(e.type(), "file.missing") ? "500" : "404");
1.268 paf 623: }
1.1 paf 624: }
625: }
626:
1.266 paf 627: uint Request::register_file(String::Body file_spec) {
1.248 paf 628: file_list+=file_spec;
629: return file_list.count()-1;
630: }
631:
1.387 moko 632: void Request::use_file_directly(const String& file_spec, bool fail_on_file_absence, bool with_auto_p) {
1.73 paf 633: // cyclic dependence check
1.318 misha 634: if(used_files.get(file_spec))
1.248 paf 635: return;
1.318 misha 636: used_files.put(file_spec, true);
637:
1.385 moko 638: if(!fail_on_file_absence && !entry_exists(file_spec)) // ignore file absence if asked for
639: return;
1.318 misha 640:
1.386 moko 641: if(with_auto_p) {
1.454 moko 642: // loading auto.p files from document_root/..
1.386 moko 643: // to the one beside requested file.
644: // all assigned bases from upper dir
645: const char* target=file_spec.cstr();
646:
647: // all relative paths are calculated from main document
648: request_info.path_translated=target;
649:
650: const char* after=target;
1.454 moko 651: size_t drlen=strlen(request_info.document_root_path);
1.457 moko 652: if(path_cmp(after, request_info.document_root_path, drlen)==0)
1.454 moko 653: after+=drlen; // to start from document_root/auto.p
1.386 moko 654:
655: while(const char* before=strchr(after, '/')) {
656: String& sfile_spec=*new String;
657: if(after!=target) {
658: sfile_spec.append_strdup(target, before-target, String::L_CLEAN);
659: sfile_spec << "/" AUTO_FILE_NAME;
660:
1.387 moko 661: use_file_directly(sfile_spec, false /*ignore absence, sole user*/);
1.386 moko 662: }
663: for(after=before+1;*after=='/';after++);
664: }
665: }
666:
1.458 moko 667: Code_cache* code=0;
668: #ifdef CODE_CACHE
669: if(Code_cache* cached=Code_cache_manager::get(file_spec)) {
670: use_buf(main_class, 0, 0, cached->file_no, 0, cached);
671: return;
672: }
673: // to record the compilation; only while the httpd config runs
674: code=Code_cache_manager::create(file_spec);
675: #endif
676:
1.385 moko 677: if(const char* source=file_read_text(charsets, file_spec, true))
1.458 moko 678: use_buf(main_class, source, 0, register_file(file_spec), 0, code);
1.318 misha 679: }
680:
681:
1.454 moko 682: void Request::use_file(const String& afile_name, const String* use_filespec/*absolute*/, bool with_auto_p) {
683: if(afile_name.is_empty())
1.366 moko 684: throw Exception(PARSER_RUNTIME, 0, "usage failed - no filename was specified");
1.326 misha 685:
1.318 misha 686: const String* filespec=0;
1.454 moko 687: const String& file_name=backslashes_to_slashes(afile_name);
1.318 misha 688:
1.454 moko 689: if(file_name.first_char()=='/' || path_scheme(afile_name) || is_os_absolute_path(afile_name)) // path is not relative, no need to scan MAIN:CLASS_PATH
690: filespec=&full_disk_path(afile_name);
1.318 misha 691: else if(use_filespec){ // search in current dir first
1.454 moko 692: size_t last_slash_pos=use_filespec->strrchr('/');
1.331 misha 693: if(last_slash_pos!=STRING_NOT_FOUND)
694: filespec=file_exist(use_filespec->mid(0, last_slash_pos), file_name); // found in current dir?
1.318 misha 695: }
696:
697: if(!filespec){
698: // prevent multiple scan CLASS_PATH for searching one file
699: if(searched_along_class_path.get(file_name))
700: return;
701: searched_along_class_path.put(file_name, true);
1.308 misha 702: if(Value* element=main_class.get_element(class_path_name)) {
1.233 paf 703: if(element->is_string()) {
1.388 moko 704: filespec=file_exist(full_disk_path(element->as_string()), file_name); // found at class_path?
1.233 paf 705: } else if(Table *table=element->get_table()) {
1.318 misha 706: for(size_t i=table->count(); i--; ) {
1.248 paf 707: const String& path=*(*table->get(i))[0];
1.388 moko 708: if(filespec=file_exist(full_disk_path(path), file_name))
1.233 paf 709: break; // found along class_path
710: }
711: } else
1.366 moko 712: throw Exception(PARSER_RUNTIME, 0, "$" CLASS_PATH_NAME " must be string or table");
1.318 misha 713: if(!filespec)
1.415 moko 714: throw Exception(PARSER_RUNTIME, &file_name, "not found along $MAIN:" CLASS_PATH_NAME);
1.318 misha 715: } else
1.415 moko 716: throw Exception(PARSER_RUNTIME, &file_name, "usage failed - no $MAIN:" CLASS_PATH_NAME " were specified");
1.148 parser 717: }
1.230 paf 718:
1.387 moko 719: use_file_directly(*filespec, true, with_auto_p);
1.16 paf 720: }
721:
1.364 moko 722: void Request::use_file(const String& file_name, const String* use_filespec/*absolute*/, Operation::Origin origin) {
1.349 moko 723: static String use("USE");
724: try {
1.364 moko 725: static VHash* voptions=new VHash();
1.376 moko 726: if(const Method *method=main_class.get_method(use_method_name)){
1.364 moko 727: Value *params[]={new VString(file_name), voptions};
728: voptions->hash().put(origin_key, new VString(*use_filespec));
729:
730: CONSTRUCTOR_FRAME_ACTION(*method, 0 /*no parent*/, main_class, {
731: frame.store_params(params, 2);
732: // we don't need the result
733: call(frame);
734: });
735: }
1.349 moko 736: } catch (...) {
737: exception_trace.push(Trace(&use, origin));
738: rethrow;
739: }
740: }
1.208 paf 741:
1.458 moko 742: void Request::use_buf(VStateless_class& aclass, const char* source, const String* main_alias, uint file_no, int line_no_offset, Code_cache* code) {
1.358 moko 743: // temporary zero @conf to avoid it second execution
1.248 paf 744: Temp_method temp_method_conf(aclass, conf_method_name, 0);
1.358 moko 745: // temporary zero @auto to avoid it second execution
1.248 paf 746: Temp_method temp_method_auto(aclass, auto_method_name, 0);
1.233 paf 747:
1.295 misha 748: // compile loaded classes
1.458 moko 749: ArrayClass& cclasses=
750: #ifdef CODE_CACHE
751: !source ? code->replay(*this, aclass) :
752: #endif
753: compile(&aclass, source, main_alias, file_no, line_no_offset, code);
1.212 paf 754:
1.248 paf 755: VString* vfilespec=
1.435 moko 756: new VString(file_list[file_no]);
1.295 misha 757:
758: for(size_t i=0; i<cclasses.count(); i++){
759: VStateless_class& cclass=*cclasses.get(i);
1.296 misha 760:
761: // locate and execute possible @conf[] static
1.382 moko 762: if(execute_method_if_exists(cclass, conf_method_name, vfilespec))
1.295 misha 763: configure_admin(cclass/*, executed.method->name*/);
764:
765: // locate and execute possible @auto[] static
1.419 moko 766: execute_auto_method_if_exists(cclass, auto_method_name, vfilespec);
1.336 moko 767:
768: cclass.enable_default_setter();
1.295 misha 769: }
1.19 paf 770: }
771:
1.248 paf 772: const String& Request::relative(const char* apath, const String& relative_name) {
1.452 moko 773: // apath is a URI or a path already normalized by the target, always slash separated
1.341 moko 774: char *hpath=pa_strdup(apath);
1.248 paf 775: String& result=*new String;
776: if(rsplit(hpath, '/')) // if something/splitted
1.217 paf 777: result << hpath << "/";
1.248 paf 778: result << relative_name;
779: return result;
1.19 paf 780: }
781:
1.454 moko 782: void Request_info::set_document_root(const char* adocument_root) {
783: document_root=adocument_root;
784: char* path=backslashes_to_slashes(adocument_root);
785: if(path) {
786: size_t length=strlen(path);
787: while(length && path[length-1]=='/')
788: path[--length]=0;
789: }
790: document_root_path=path;
791: }
792:
1.453 moko 793: const String& Request::full_disk_path(const String& relative_name, uint allowed) {
1.454 moko 794: if(relative_name.first_char()!='/') {
795: if(uint scheme=path_scheme(relative_name)) {
796: check_path_scheme(scheme, relative_name, allowed);
797: if(scheme!=PA_SCHEME_FILE)
798: return relative_name; // an allowed uri is passed through
799: if(const String* path=file_uri_to_path(relative_name))
800: return backslashes_to_slashes(*path);
1.455 moko 801: #ifdef WIN32
802: throw Exception(PARSER_RUNTIME, &relative_name, "must be file:///path, file://localhost/path or file://server/share/path");
803: #else
1.454 moko 804: throw Exception(PARSER_RUNTIME, &relative_name, "must be file:///path or file://localhost/path");
1.455 moko 805: #endif
1.454 moko 806: }
807: // before '\' becomes '/', to avoid mixing the UNC path \\server with web path //server
808: if(is_os_absolute_path(relative_name))
809: return backslashes_to_slashes(relative_name);
1.453 moko 810: }
1.389 moko 811:
1.454 moko 812: const String& path=backslashes_to_slashes(relative_name);
813: if(path.first_char()!='/')
814: return relative(request_info.path_translated ? request_info.path_translated : pa_strcat(request_info.document_root_path, "/"), path);
815:
816: String& result=*new String(request_info.document_root_path);
817: result << path;
818: return result;
1.1 paf 819: }
1.45 paf 820:
1.453 moko 821: const String* Request::real_disk_path(const String& name) {
822: switch(path_scheme(name)) {
823: case PA_SCHEME_NONE: return &full_disk_path(name);
1.454 moko 824: case PA_SCHEME_FILE: {
1.456 moko 825: const String* path=clean_path_scheme(PA_SCHEME_FILE, name) ? file_uri_to_path(name) : 0;
1.454 moko 826: return path ? &backslashes_to_slashes(*path) : 0;
827: }
1.453 moko 828: default: return 0; // not a disk path
829: }
830: }
831:
1.267 paf 832: #ifndef DOXYGEN
833: class Add_header_attribute_info
834: {
835: public:
836: Add_header_attribute_info(Request& ar) : r(ar), add_last_modified(true) {}
837: Request& r;
838: bool add_last_modified;
839: };
840: #endif
1.344 moko 841: static void add_header_attribute(HashStringValue::key_type name, HashStringValue::value_type value, Add_header_attribute_info* info) {
842: if(name==BODY_NAME_UPPER || name==DOWNLOAD_NAME_UPPER || name==CHARSET_NAME_UPPER)
1.101 paf 843: return;
1.290 misha 844:
1.345 moko 845: if(name==LAST_MODIFIED_NAME_UPPER)
846: info->add_last_modified=false;
847:
1.316 misha 848: const char* aname=String(name, String::L_URI).untaint_and_transcode_cstr(String::L_URI, &info->r.charsets);
1.101 paf 849:
1.267 paf 850: SAPI::add_header_attribute(info->r.sapi_info,
1.345 moko 851: aname,
1.316 misha 852: attributed_meaning_to_string(*value, String::L_URI, false).untaint_and_transcode_cstr(String::L_URI, &info->r.charsets)
1.303 misha 853: );
1.267 paf 854: }
855:
1.366 moko 856: static void output_sole_piece(Request& r, bool header_only, VFile& body_file, Value* body_file_content_type) {
1.267 paf 857: // transcode text body when "text/*" or simple result
858: String::C output(body_file.value_ptr(), body_file.value_size());
859: if(!body_file_content_type/*vstring.as_vfile*/ || body_file_content_type->as_string().pos("text/")==0)
1.366 moko 860: output=Charset::transcode(output, r.charsets.source(), r.charsets.client());
1.267 paf 861:
1.311 misha 862: // prepare header: Content-Length
1.428 moko 863: SAPI::add_header_attribute(r.sapi_info, HTTP_CONTENT_LENGTH, pa_uitoa(output.length));
1.267 paf 864:
865: // send header
1.430 moko 866: SAPI::send_headers(r.sapi_info);
1.267 paf 867:
868: // send body
869: if(!header_only)
870: SAPI::send_body(r.sapi_info, output.str, output.length);
871: }
872:
873: #ifndef DOXYGEN
874: struct Range
875: {
1.396 moko 876: uint64_t start;
877: uint64_t end;
1.267 paf 878: };
879: #endif
1.396 moko 880:
881: #define UNSET ((uint64_t)-1)
882:
1.313 misha 883: static void parse_range(const String* s, Array<Range> &ar) {
1.267 paf 884: const char *p = s->cstr();
885: if(s->starts_with("bytes="))
886: p += 6;
887: Range r;
888: while(*p){
1.396 moko 889: r.start = UNSET;
890: r.end = UNSET;
1.401 moko 891:
892: while(*p==' ' || *p=='\t') p++;
893:
1.267 paf 894: if(*p >= '0' && *p <= '9'){
1.416 moko 895: const char *n=p;
1.401 moko 896: while(*p>='0' && *p<='9') p++;
1.440 moko 897: r.start = pa_atoul(pa_strdup(n, p-n)); // ((uint64_t)-1) is treated as UNSET
1.267 paf 898: }
1.401 moko 899:
900: while(*p==' ' || *p=='\t') p++;
901:
1.267 paf 902: if(*p++ != '-') break;
1.401 moko 903:
904: while(*p==' ' || *p=='\t') p++;
905:
1.267 paf 906: if(*p >= '0' && *p <= '9'){
1.416 moko 907: const char *n=p;
1.401 moko 908: while(*p>='0' && *p<='9') p++;
1.440 moko 909: r.end = pa_atoul(pa_strdup(n, p-n)); // ((uint64_t)-1) is treated as UNSET
1.267 paf 910: }
1.401 moko 911:
912: while(*p==' ' || *p=='\t') p++;
913:
914: if(*p)
915: if(*p++ != ',') break;
916:
1.267 paf 917: ar += r;
918: }
1.101 paf 919: }
1.267 paf 920:
1.400 moko 921: struct Send_range_action_info {
922: Request *r;
923: uint64_t offset;
924: uint64_t part_length;
925: };
926:
927: static void send_range(struct stat& /*finfo*/, int f, const String& /*file_spec*/, void *context){
928: Send_range_action_info &info = *(Send_range_action_info*)context;
929:
1.430 moko 930: SAPI::send_headers(info.r->sapi_info);
1.400 moko 931: pa_lseek(f, info.offset, SEEK_SET);
932:
1.432 moko 933: char buf[FILE_BUFFER_SIZE];
1.400 moko 934: do{
1.432 moko 935: size_t to_read = info.part_length < FILE_BUFFER_SIZE ? (size_t)info.part_length : FILE_BUFFER_SIZE;
1.400 moko 936: size_t to_write = file_block_read(f, buf, to_read);
937:
938: if(to_write == 0)
939: break;
940:
941: size_t size = SAPI::send_body(info.r->sapi_info, buf, to_write);
942: if(size != to_write)
943: break;
944:
945: info.part_length -= to_write;
946: } while (info.part_length);
947: }
948:
1.396 moko 949: static void output_pieces(Request& r, bool header_only, const String& filename, uint64_t content_length, Value& date, bool add_last_modified) {
1.315 misha 950: SAPI::add_header_attribute(r.sapi_info, "accept-ranges", "bytes");
1.270 paf 951:
1.339 moko 952: const char *range = SAPI::Env::get(r.sapi_info, "HTTP_RANGE");
1.396 moko 953: uint64_t offset=0;
954: uint64_t part_length=content_length;
1.401 moko 955:
956: if(range && content_length){
1.267 paf 957: Array<Range> ar;
958: parse_range(new String(range), ar);
1.396 moko 959: int count = ar.count();
1.267 paf 960: if(count == 1){
961: Range &rg = ar.get_ref(0);
1.401 moko 962:
963: if(rg.start == UNSET && rg.end == UNSET)
964: return SAPI::send_error(r.sapi_info, "", "416");
965:
1.396 moko 966: if(rg.start == UNSET && rg.end != UNSET){
1.440 moko 967: if(rg.end == 0)
968: return SAPI::send_error(r.sapi_info, "", "416");
1.401 moko 969: if(rg.end > content_length)
970: rg.end = content_length;
1.404 moko 971: rg.start = content_length - rg.end;
972: rg.end = content_length-1;
1.401 moko 973: } else if(rg.start != UNSET && rg.end == UNSET){
974: if(rg.start >= content_length)
975: return SAPI::send_error(r.sapi_info, "", "416");
1.267 paf 976: rg.end = content_length-1;
1.401 moko 977: } else {
978: if(rg.start >= content_length || rg.start > rg.end)
979: return SAPI::send_error(r.sapi_info, "", "416");
980: if(rg.end >= content_length)
981: rg.end = content_length-1;
1.267 paf 982: }
1.401 moko 983:
984: offset = rg.start;
985: part_length = rg.end-rg.start+1;
986:
1.400 moko 987: char buf[MAX_STRING];
1.466 moko 988: pa_snprintf(buf, MAX_STRING, "bytes %s-%s/%s", pa_uitoa(rg.start), pa_uitoa(rg.end), pa_uitoa(content_length));
1.401 moko 989: SAPI::add_header_attribute(r.sapi_info, HTTP_STATUS, "206");
1.315 misha 990: SAPI::add_header_attribute(r.sapi_info, "content-range", buf);
1.401 moko 991: } else {
1.410 moko 992: return SAPI::send_error(r.sapi_info, count ? "Multiple ranges are not supported" : "Invalid range", count ? "501" : "400");
1.267 paf 993: }
994: }
995:
1.428 moko 996: SAPI::add_header_attribute(r.sapi_info, HTTP_CONTENT_LENGTH, pa_uitoa(part_length));
1.267 paf 997:
1.314 misha 998: if(add_last_modified)
1.315 misha 999: SAPI::add_header_attribute(r.sapi_info, "last-modified", attributed_meaning_to_string(date, String::L_AS_IS, true).cstr());
1.314 misha 1000:
1.414 moko 1001: if(header_only){
1.430 moko 1002: SAPI::send_headers(r.sapi_info);
1.414 moko 1003: } else {
1.400 moko 1004: Send_range_action_info info = { &r, offset, part_length};
1005: file_read_action_under_lock(r.full_disk_path(filename), "send", send_range, &info);
1.267 paf 1006: }
1007: }
1008:
1.248 paf 1009: void Request::output_result(VFile* body_file, bool header_only, bool as_attachment) {
1.464 moko 1010: if(response.started)
1.460 moko 1011: return;
1012:
1.51 paf 1013: // header: cookies
1.248 paf 1014: cookie.output_result(sapi_info);
1.51 paf 1015:
1.394 moko 1016: // $.file and $.name (when body is real vfile)
1017: Value* vfile = body_file->fields().get(response_body_file_name);
1018: Value* vname = body_file->fields().get(name_name);
1019:
1020: const String* sfile = vfile ? &vfile->as_string() : NULL;
1021: const String* sname = vname ? &vname->as_string() : NULL;
1022:
1023: if(sname && *sname == NONAME_DAT)
1024: sname = NULL;
1.92 paf 1025:
1.409 moko 1026: // Content-Disposition, use $.name[<empty>] to avoid
1.394 moko 1027: const String* disposition_name = sname ? sname->is_empty() ? NULL : sname : sfile;
1028: if(disposition_name) {
1.420 moko 1029: String& filename = *new String(pa_filename(disposition_name->cstr()), String::L_URI);
1030: String& filename_asterisk = *new String(charsets.client().NAME(), String::L_CLEAN) << (*new String("''")) << filename;
1031:
1.394 moko 1032: VHash& hash=*new VHash();
1033: hash.hash().put(value_name, new VString(as_attachment ? content_disposition_attachment : content_disposition_inline));
1.420 moko 1034: hash.hash().put(content_disposition_filename_name, new VString(filename));
1035: hash.hash().put(content_disposition_filename_name_asterisk, new VString(filename_asterisk));
1.394 moko 1036: response.fields().put(content_disposition_name_upper, &hash);
1037: }
1.267 paf 1038:
1.394 moko 1039: // _file_ content-type might be specified
1040: Value* body_file_content_type = body_file->fields().get(content_type_name);
1041: if(!body_file_content_type){
1042: const String* scontent_name = sname && !sname->is_empty() ? sname : sfile;
1043: if(scontent_name)
1044: body_file_content_type = new VString(mime_type_of(scontent_name->cstr()));
1.267 paf 1045: }
1046:
1.312 misha 1047: // set Content-Type
1.314 misha 1048: if(body_file_content_type) {
1049: // body file content type
1.344 moko 1050: response.fields().put(content_type_name_upper, body_file_content_type);
1.314 misha 1051: } else {
1052: // default content type
1.344 moko 1053: response.fields().put_dont_replace(content_type_name_upper, new VString(*new String(DEFAULT_CONTENT_TYPE)));
1.314 misha 1054: }
1.312 misha 1055:
1.314 misha 1056: // prepare header: $response:fields without :body, :download and :charset
1.267 paf 1057: Add_header_attribute_info info(*this);
1.281 paf 1058: response.fields().for_each<Add_header_attribute_info*>(add_header_attribute, &info);
1.50 paf 1059:
1.394 moko 1060: if(sfile) {
1.314 misha 1061: // $response:[download|body][$.file[filespec]] -- optput specified file
1.367 moko 1062: uint64_t content_length=0;
1.267 paf 1063: time_t atime=0, mtime=0, ctime=0;
1.394 moko 1064: file_stat(full_disk_path(*sfile), content_length, atime, mtime, ctime);
1.267 paf 1065:
1066: VDate* vdate=0;
1067: if(Value* v=body_file->fields().get("mdate")) {
1.423 moko 1068: vdate=dynamic_cast<VDate*>(v);
1069: if(!vdate)
1.286 misha 1070: throw Exception(PARSER_RUNTIME, 0, "mdate must be a date");
1.267 paf 1071: }
1072: if(!vdate)
1.346 moko 1073: vdate=new VDate((pa_time_t)mtime);
1.62 paf 1074:
1.399 moko 1075: output_pieces(*this, header_only, *sfile, content_length, *vdate, info.add_last_modified);
1.267 paf 1076: } else {
1.314 misha 1077: if(body_file_content_type)
1078: if(HashStringValue *hash=body_file_content_type->get_hash())
1079: body_file_content_type=hash->get(value_name);
1080:
1.366 moko 1081: output_sole_piece(*this, header_only, *body_file, body_file_content_type);
1.267 paf 1082: }
1.50 paf 1083: }
1.104 paf 1084:
1.464 moko 1085: void Request::start(VResponse::Started mode) {
1086: // the headers: cookies and $response:fields, without Content-Length
1087: // prepare before response.started is set: after that an exception is not reported to the client
1088: cookie.output_result(sapi_info);
1089: Add_header_attribute_info info(*this);
1090: response.fields().for_each<Add_header_attribute_info*>(add_header_attribute, &info);
1091: response.started=mode;
1092: SAPI::send_headers(sapi_info);
1093: }
1094:
1.463 moko 1095: void Request::stream(Value& part) {
1.464 moko 1096: if(response.started==VResponse::WEBSOCKET)
1097: throw Exception("websocket", 0, "unable to stream: websocket is active");
1098:
1099: // convert before response.started is set: after that an exception is not reported to the client
1.460 moko 1100: VFile* file=dynamic_cast<VFile*>(&part);
1.462 moko 1101: String::C output=file ? String::C(file->value_ptr(), file->value_size()) : String::C(part.get_string()->cstr_to_string_body_untaint(response.lang, 0, &charsets));
1.460 moko 1102: if(!file || file->is_text_mode())
1103: output=Charset::transcode(output, charsets.source(), charsets.client());
1104:
1.464 moko 1105: if(!response.started) {
1.460 moko 1106: response.fields().put_dont_replace(content_type_name_upper, new VString(*new String(DEFAULT_CONTENT_TYPE)));
1.464 moko 1107: start(VResponse::STREAM);
1.460 moko 1108: }
1109:
1110: if(!is_header_only(request_info))
1111: SAPI::send_body(sapi_info, output.str, output.length);
1112: }
1113:
1.328 misha 1114: const String& Request::mime_type_of(const String* file_name) {
1115: return mime_type_of(file_name?file_name->taint_cstr(String::L_FILE_SPEC):0);
1116: }
1117:
1.248 paf 1118: const String& Request::mime_type_of(const char* user_file_name_cstr) {
1.468 ! moko 1119: // built at the first use: $MAIN:MIME-TYPES (table or @GET_MIME-TYPES[] property)
1.467 moko 1120: if(!mime_types) {
1.468 ! moko 1121: Value* element=main_class.get_element(mime_types_name);
! 1122: TEMP_GETTER_PROTECTED(false); // @GET_MIME-TYPES[] assigns $MIME-TYPES, which replaces the getter with the table
! 1123: Table *table=element ? process(*element).get_table() : 0;
1.467 moko 1124: mime_types=table ? table : new Table(0); // empty if nothing is defined
1125: }
1126:
1127: if(const char* cext=strrchr(user_file_name_cstr, '.')) {
1128: String sext(++cext);
1129: Table::Action_options options;
1130: if(mime_types->locate(0, sext.change_case(charsets.source(), String::CC_LOWER), options)) {
1131: if(const String* result=mime_types->item(1))
1132: return *result;
1133: else
1134: throw Exception(PARSER_RUNTIME, 0, MIME_TYPES_NAME " table column elements must not be empty");
1.104 paf 1135: }
1.467 moko 1136: }
1.248 paf 1137:
1138: return *new String("application/octet-stream");
1139: }
1140:
1.365 moko 1141: const String* Request::get_used_filespec(uint file_no){
1.318 misha 1142: if(file_no < file_list.count())
1143: return new String(file_list[file_no], String::L_TAINTED);
1144: return 0;
1145: }
1146:
1.248 paf 1147: #ifdef XML
1.280 paf 1148: xmlChar* Request::transcode(const String& s) {
1.248 paf 1149: return charsets.source().transcode(s);
1150: }
1151:
1.280 paf 1152: xmlChar* Request::transcode(const String::Body s) {
1.248 paf 1153: return charsets.source().transcode(s);
1154: }
1155:
1.280 paf 1156: const String& Request::transcode(const xmlChar* s) {
1.248 paf 1157: return charsets.source().transcode(s);
1.233 paf 1158: }
1.248 paf 1159: #endif
1160:
1.442 moko 1161: VException::VException(Request& r, const Exception& e):
1162: fexception(e), fhandled(&VBool::get(false)),
1.444 moko 1163: ftrace_bottom(r.exception_trace.bottom_index()), ftrace_top(r.exception_trace.top_index()),
1.442 moko 1164: origin(Operation::Origin::create(0, 0, 0)), problem_source(e.problem_source()) {
1165: Request::Exception_trace& exception_trace=r.exception_trace;
1.248 paf 1166:
1.349 moko 1167: if(!exception_trace.is_empty()) {
1.442 moko 1168: Request::Trace bottom=exception_trace.bottom_value();
1.350 moko 1169: origin=bottom.origin();
1.443 moko 1170: if(!problem_source) // we don't know who trigged the bug
1.350 moko 1171: problem_source=bottom.name(); // we usually know source of next-from-throw-point exception did that
1.248 paf 1172: }
1.442 moko 1173: if(origin.file_no)
1174: ffile=r.file_list[origin.file_no];
1175: }
1176:
1177: Value* VException::handled() {
1178: return fhash ? fhash->get(Symbols::HANDLED_SYMBOL) : fhandled;
1179: }
1.248 paf 1180:
1.444 moko 1181: Table& VException::stack(Request& r) {
1182: if(ftrace_top==size_t(-1))
1183: throw Exception(PARSER_RUNTIME, 0, "exception stack used outside of context");
1184: return r.exception_trace.table(r, problem_source, ftrace_bottom, ftrace_top);
1185: }
1186:
1.442 moko 1187: Value* VException::get_element(const String& name) {
1188: if(!fhash) {
1189: if(SYMBOLS_EQ(name,HANDLED_SYMBOL))
1190: return fhandled;
1191: if(SYMBOLS_EQ(name,TYPE_SYMBOL))
1192: return fexception.type(true) ? new VString(*new String(fexception.type())) : 0;
1193: if(SYMBOLS_EQ(name,SOURCE_SYMBOL))
1194: return problem_source ? new VString(*problem_source) : 0;
1195: if(SYMBOLS_EQ(name,COMMENT_SYMBOL))
1196: return fexception.comment(true) ? new VString(fexception.comment()) : 0;
1197: if(SYMBOLS_EQ(name,FILE_SYMBOL))
1198: return origin.file_no ? new VString(ffile) : 0;
1199: if(SYMBOLS_EQ(name,LINENO_SYMBOL))
1200: return origin.file_no ? new VInt(1+origin.line) : 0;
1201: if(SYMBOLS_EQ(name,COLNO_SYMBOL))
1202: return origin.file_no ? new VInt(1+origin.col) : 0;
1203: if(SYMBOLS_EQ(name,FIELDS_SYMBOL))
1204: return this;
1205: }
1206: // Computed field names need not be interned: use ordinary hash lookup.
1207: return VHashReference::get_element(name);
1208: }
1209:
1210: const VJunction* VException::put_element(const String& name, Value* value) {
1211: if(!fhash && SYMBOLS_EQ(name,HANDLED_SYMBOL)) {
1212: fhandled=value;
1213: return 0;
1214: }
1215: return VHashReference::put_element(name, value);
1216: }
1217:
1218: HashStringValue& VException::hash() {
1219: if(fhash)
1220: return *fhash;
1221: HashStringValue& result=*new HashStringValue;
1.248 paf 1222:
1.442 moko 1223: if(const char* type=fexception.type(true))
1224: result.put(Symbols::TYPE_SYMBOL, new VString(*new String(type)));
1.349 moko 1225: if(problem_source)
1.442 moko 1226: result.put(Symbols::SOURCE_SYMBOL, new VString(*problem_source));
1227: if(origin.file_no) {
1228: result.put(Symbols::FILE_SYMBOL, new VString(ffile));
1229: result.put(Symbols::LINENO_SYMBOL, new VInt(1+origin.line));
1230: result.put(Symbols::COLNO_SYMBOL, new VInt(1+origin.col));
1231: }
1232: if(const char* comment=fexception.comment(true))
1233: result.put(Symbols::COMMENT_SYMBOL, new VString(comment));
1234: result.put(Symbols::HANDLED_SYMBOL, fhandled);
1.248 paf 1235:
1.442 moko 1236: fhash=&result;
1237: return result;
1.133 parser 1238: }
1.337 moko 1239:
1240: Temp_value_element::Temp_value_element(Request& arequest, Value& awhere, const String& aname, Value* awhat) :
1241: frequest(arequest),
1242: fwhere(awhere),
1243: fname(aname),
1244: saved(awhere.get_element(aname))
1245: {
1246: Junction* junction;
1247: if(saved && (junction=saved->get_junction()) && junction->is_getter)
1248: saved=0;
1249: frequest.put_element(fwhere, aname, awhat);
1250: }
1251:
1252: Temp_value_element::~Temp_value_element() {
1253: frequest.put_element(fwhere, fname, saved ? saved : VVoid::get());
1254: }
E-mail: