| 1 | #ifdef RCSID |
| 2 | static char RCSid[] = |
| 3 | "$Header$"; |
| 4 | #endif |
| 5 | |
| 6 | /* |
| 7 | * Copyright (c) 2010 Michael J. Roberts. All Rights Reserved. |
| 8 | * |
| 9 | * Please see the accompanying license file, LICENSE.TXT, for information |
| 10 | * on using and copying this software. |
| 11 | */ |
| 12 | /* |
| 13 | Name |
| 14 | vmhttpreq.cpp - CVmObjHTTPRequest object |
| 15 | Function |
| 16 | |
| 17 | Notes |
| 18 | |
| 19 | Modified |
| 20 | MJRoberts - Creation |
| 21 | */ |
| 22 | |
| 23 | #include <stdlib.h> |
| 24 | #include <string.h> |
| 25 | #include <assert.h> |
| 26 | |
| 27 | #include "t3std.h" |
| 28 | #include "vmhttpreq.h" |
| 29 | #include "vmerr.h" |
| 30 | #include "vmerrnum.h" |
| 31 | #include "vmtype.h" |
| 32 | #include "vmglob.h" |
| 33 | #include "vmobj.h" |
| 34 | #include "vmundo.h" |
| 35 | #include "vmmcreg.h" |
| 36 | #include "vmfile.h" |
| 37 | #include "vmbif.h" |
| 38 | #include "vmmeta.h" |
| 39 | #include "vmstack.h" |
| 40 | #include "vmrun.h" |
| 41 | #include "vmstr.h" |
| 42 | #include "vmstrbuf.h" |
| 43 | #include "vmlst.h" |
| 44 | #include "vmlookup.h" |
| 45 | #include "utf8.h" |
| 46 | #include "vmnet.h" |
| 47 | #include "vmpredef.h" |
| 48 | #include "vmbytarr.h" |
| 49 | #include "charmap.h" |
| 50 | #include "vmfilobj.h" |
| 51 | #include "vmdatasrc.h" |
| 52 | #include "vmcset.h" |
| 53 | #include "vmimport.h" |
| 54 | |
| 55 | |
| 56 | |
| 57 | /* ------------------------------------------------------------------------ */ |
| 58 | /* |
| 59 | * Allocate an extension structure |
| 60 | */ |
| 61 | vm_httpreq_ext *vm_httpreq_ext::alloc_ext(VMG_ CVmObjHTTPRequest *self) |
| 62 | { |
| 63 | /* calculate how much space we need */ |
| 64 | size_t siz = sizeof(vm_httpreq_ext); |
| 65 | |
| 66 | /* allocate the memory */ |
| 67 | vm_httpreq_ext *ext = (vm_httpreq_ext *)G_mem->get_var_heap()->alloc_mem( |
| 68 | siz, self); |
| 69 | |
| 70 | /* we don't have a system message object yet */ |
| 71 | ext->req = 0; |
| 72 | |
| 73 | /* we have no reply cookies yet */ |
| 74 | ext->cookies = 0; |
| 75 | |
| 76 | /* return the new extension */ |
| 77 | return ext; |
| 78 | } |
| 79 | |
| 80 | /* ------------------------------------------------------------------------ */ |
| 81 | /* |
| 82 | * CVmObjHTTPRequest object statics |
| 83 | */ |
| 84 | |
| 85 | /* metaclass registration object */ |
| 86 | static CVmMetaclassHTTPRequest metaclass_reg_obj; |
| 87 | CVmMetaclass *CVmObjHTTPRequest::metaclass_reg_ = &metaclass_reg_obj; |
| 88 | |
| 89 | /* function table */ |
| 90 | int (CVmObjHTTPRequest::*CVmObjHTTPRequest::func_table_[])( |
| 91 | VMG_ vm_obj_id_t self, vm_val_t *retval, uint *argc) = |
| 92 | { |
| 93 | &CVmObjHTTPRequest::getp_undef, |
| 94 | &CVmObjHTTPRequest::getp_getServer, |
| 95 | &CVmObjHTTPRequest::getp_getVerb, |
| 96 | &CVmObjHTTPRequest::getp_getQuery, |
| 97 | &CVmObjHTTPRequest::getp_parseQuery, |
| 98 | &CVmObjHTTPRequest::getp_getQueryParam, |
| 99 | &CVmObjHTTPRequest::getp_getHeaders, |
| 100 | &CVmObjHTTPRequest::getp_getCookie, |
| 101 | &CVmObjHTTPRequest::getp_getCookies, |
| 102 | &CVmObjHTTPRequest::getp_getFormFields, |
| 103 | &CVmObjHTTPRequest::getp_getBody, |
| 104 | &CVmObjHTTPRequest::getp_getClientAddress, |
| 105 | &CVmObjHTTPRequest::getp_setCookie, |
| 106 | &CVmObjHTTPRequest::getp_sendReply, |
| 107 | &CVmObjHTTPRequest::getp_startChunkedReply, |
| 108 | &CVmObjHTTPRequest::getp_sendReplyChunk, |
| 109 | &CVmObjHTTPRequest::getp_endChunkedReply, |
| 110 | &CVmObjHTTPRequest::getp_sendReplyAsync |
| 111 | }; |
| 112 | |
| 113 | /* ------------------------------------------------------------------------ */ |
| 114 | /* |
| 115 | * CVmObjHTTPRequest intrinsic class implementation |
| 116 | */ |
| 117 | |
| 118 | /* |
| 119 | * construction |
| 120 | */ |
| 121 | CVmObjHTTPRequest::CVmObjHTTPRequest(VMG_ int) |
| 122 | { |
| 123 | /* allocate our extension structure */ |
| 124 | ext_ = (char *)vm_httpreq_ext::alloc_ext(vmg_ this); |
| 125 | } |
| 126 | |
| 127 | /* |
| 128 | * create |
| 129 | */ |
| 130 | vm_obj_id_t CVmObjHTTPRequest::create( |
| 131 | VMG_ int in_root_set, TadsHttpRequest *req, vm_obj_id_t server) |
| 132 | { |
| 133 | /* create the object - we have no gc-obj refs of any kind */ |
| 134 | vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE); |
| 135 | |
| 136 | /* requests are inherently transient */ |
| 137 | G_obj_table->set_obj_transient(id); |
| 138 | |
| 139 | /* create the C++ object and get its extension */ |
| 140 | CVmObjHTTPRequest *r = new (vmg_ id) CVmObjHTTPRequest(vmg_ TRUE); |
| 141 | vm_httpreq_ext *ext = r->get_ext(); |
| 142 | |
| 143 | /* save the system request object */ |
| 144 | if ((ext->req = req) != 0) |
| 145 | req->add_ref(); |
| 146 | |
| 147 | /* save the server object */ |
| 148 | ext->server = server; |
| 149 | |
| 150 | /* return the new object ID */ |
| 151 | return id; |
| 152 | } |
| 153 | |
| 154 | /* |
| 155 | * create dynamically using stack arguments |
| 156 | */ |
| 157 | vm_obj_id_t CVmObjHTTPRequest::create_from_stack( |
| 158 | VMG_ const uchar **pc_ptr, uint argc) |
| 159 | { |
| 160 | /* |
| 161 | * we can't be created with 'new' - we can only be created via the |
| 162 | * getNetEvent() intrinsic function |
| 163 | */ |
| 164 | err_throw(VMERR_BAD_DYNAMIC_NEW); |
| 165 | |
| 166 | /* not reached, but the compiler might not know that */ |
| 167 | AFTER_ERR_THROW(return VM_INVALID_OBJ;) |
| 168 | } |
| 169 | |
| 170 | /* |
| 171 | * notify of deletion |
| 172 | */ |
| 173 | void CVmObjHTTPRequest::notify_delete(VMG_ int /*in_root_set*/) |
| 174 | { |
| 175 | /* free our additional data, if we have any */ |
| 176 | vm_httpreq_ext *ext = get_ext(); |
| 177 | if (ext != 0) |
| 178 | { |
| 179 | /* release the message object */ |
| 180 | if (ext->req != 0) |
| 181 | ext->req->release_ref(); |
| 182 | |
| 183 | /* delete the cookies */ |
| 184 | if (ext->cookies != 0) |
| 185 | delete ext->cookies; |
| 186 | |
| 187 | /* delete the extension */ |
| 188 | G_mem->get_var_heap()->free_mem(ext_); |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /* |
| 193 | * Mark references |
| 194 | */ |
| 195 | void CVmObjHTTPRequest::mark_refs(VMG_ uint state) |
| 196 | { |
| 197 | /* if we have a server object, mark it */ |
| 198 | vm_httpreq_ext *ext = get_ext(); |
| 199 | if (ext->server != VM_INVALID_OBJ) |
| 200 | G_obj_table->mark_all_refs(ext->server, state); |
| 201 | } |
| 202 | |
| 203 | /* |
| 204 | * set a property |
| 205 | */ |
| 206 | void CVmObjHTTPRequest::set_prop(VMG_ class CVmUndo *undo, |
| 207 | vm_obj_id_t self, vm_prop_id_t prop, |
| 208 | const vm_val_t *val) |
| 209 | { |
| 210 | /* no settable properties - throw an error */ |
| 211 | err_throw(VMERR_INVALID_SETPROP); |
| 212 | } |
| 213 | |
| 214 | /* |
| 215 | * get a property |
| 216 | */ |
| 217 | int CVmObjHTTPRequest::get_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval, |
| 218 | vm_obj_id_t self, vm_obj_id_t *source_obj, |
| 219 | uint *argc) |
| 220 | { |
| 221 | |
| 222 | /* translate the property into a function vector index */ |
| 223 | uint func_idx = G_meta_table->prop_to_vector_idx( |
| 224 | metaclass_reg_->get_reg_idx(), prop); |
| 225 | |
| 226 | /* call the appropriate function */ |
| 227 | if ((this->*func_table_[func_idx])(vmg_ self, retval, argc)) |
| 228 | { |
| 229 | *source_obj = metaclass_reg_->get_class_obj(vmg0_); |
| 230 | return TRUE; |
| 231 | } |
| 232 | |
| 233 | /* inherit default handling from our base class */ |
| 234 | return CVmObject::get_prop(vmg_ prop, retval, self, source_obj, argc); |
| 235 | } |
| 236 | |
| 237 | /* |
| 238 | * load from an image file |
| 239 | */ |
| 240 | void CVmObjHTTPRequest::load_from_image(VMG_ vm_obj_id_t self, |
| 241 | const char *ptr, size_t siz) |
| 242 | { |
| 243 | /* load our image data */ |
| 244 | load_image_data(vmg_ ptr, siz); |
| 245 | |
| 246 | /* |
| 247 | * save our image data pointer in the object table, so that we can |
| 248 | * access it (without storing it ourselves) during a reload |
| 249 | */ |
| 250 | G_obj_table->save_image_pointer(self, ptr, siz); |
| 251 | } |
| 252 | |
| 253 | /* |
| 254 | * reload from the image file |
| 255 | */ |
| 256 | void CVmObjHTTPRequest::reload_from_image(VMG_ vm_obj_id_t self, |
| 257 | const char *ptr, size_t siz) |
| 258 | { |
| 259 | /* load our image data */ |
| 260 | load_image_data(vmg_ ptr, siz); |
| 261 | } |
| 262 | |
| 263 | /* |
| 264 | * load or reload data from the image |
| 265 | */ |
| 266 | void CVmObjHTTPRequest::load_image_data(VMG_ const char *ptr, size_t siz) |
| 267 | { |
| 268 | /* free our existing extension, if we have one */ |
| 269 | notify_delete(vmg_ FALSE); |
| 270 | |
| 271 | /* allocate the extension */ |
| 272 | vm_httpreq_ext *ext = vm_httpreq_ext::alloc_ext(vmg_ this); |
| 273 | ext_ = (char *)ext; |
| 274 | } |
| 275 | |
| 276 | |
| 277 | /* |
| 278 | * save to a file |
| 279 | */ |
| 280 | void CVmObjHTTPRequest::save_to_file(VMG_ class CVmFile *fp) |
| 281 | { |
| 282 | /* we're inherently transient, so we should never do this */ |
| 283 | assert(FALSE); |
| 284 | } |
| 285 | |
| 286 | /* |
| 287 | * restore from a file |
| 288 | */ |
| 289 | void CVmObjHTTPRequest::restore_from_file(VMG_ vm_obj_id_t self, |
| 290 | CVmFile *fp, CVmObjFixup *fixups) |
| 291 | { |
| 292 | /* we're transient, so this should never happen */ |
| 293 | } |
| 294 | |
| 295 | /* |
| 296 | * Create a new validated ASCII string. This converts any 8-bit characters |
| 297 | * to '?' to ensure that the result is well-formed UTF-8. |
| 298 | */ |
| 299 | static void new_ascii_string(VMG_ vm_val_t *ret, const char *str, size_t len) |
| 300 | { |
| 301 | |
| 302 | /* create and return a string for it */ |
| 303 | vm_obj_id_t strid = CVmObjString::create(vmg_ FALSE, str, len); |
| 304 | ret->set_obj(strid); |
| 305 | |
| 306 | /* |
| 307 | * We expected a plain ASCII string as input, so any character outside |
| 308 | * of the 7-bit ASCII range (0-127) is invalid. Scan the string and |
| 309 | * convert any invalid characters to '?' characters. If we didn't do |
| 310 | * this, any 8-bit characters could potentially trigger VM crashes, |
| 311 | * since we'd try to interpret them as multi-byte UTF-8 character |
| 312 | * components even though they might not form valid UTF-8 sequences. |
| 313 | * Eliminating any 8-bit characters up front thus protects us against |
| 314 | * errant or malicious clients by ensuring that we have a well-formed |
| 315 | * UTF-8 string in all cases (since any string containing only plain |
| 316 | * ASCII characters is inherently a well-formed UTF-8 string). |
| 317 | */ |
| 318 | CVmObjString *strp = (CVmObjString *)vm_objp(vmg_ strid); |
| 319 | for (char *p = strp->cons_get_buf() ; len != 0 ; ++p, --len) |
| 320 | { |
| 321 | /* convert anything outside of plain ASCII (0-127) to '?' */ |
| 322 | if (*(uchar *)p > 127) |
| 323 | *p = '?'; |
| 324 | } |
| 325 | } |
| 326 | static void new_ascii_string(VMG_ vm_val_t *ret, const char *str) |
| 327 | { |
| 328 | return new_ascii_string(vmg_ ret, str, strlen(str)); |
| 329 | } |
| 330 | |
| 331 | /* |
| 332 | * get the server (the HTTPServer object) |
| 333 | */ |
| 334 | int CVmObjHTTPRequest::getp_getServer(VMG_ vm_obj_id_t self, |
| 335 | vm_val_t *retval, uint *oargc) |
| 336 | { |
| 337 | static CVmNativeCodeDesc desc(0); |
| 338 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 339 | return TRUE; |
| 340 | |
| 341 | /* return the server object */ |
| 342 | retval->set_obj_or_nil(get_ext()->server); |
| 343 | |
| 344 | /* handled */ |
| 345 | return TRUE; |
| 346 | } |
| 347 | |
| 348 | /* |
| 349 | * get the HTTP verb |
| 350 | */ |
| 351 | int CVmObjHTTPRequest::getp_getVerb(VMG_ vm_obj_id_t self, |
| 352 | vm_val_t *retval, uint *oargc) |
| 353 | { |
| 354 | static CVmNativeCodeDesc desc(0); |
| 355 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 356 | return TRUE; |
| 357 | |
| 358 | /* return a validated ASCII string for the verb in the request */ |
| 359 | new_ascii_string(vmg_ retval, get_ext()->req->verb->get()); |
| 360 | |
| 361 | /* handled */ |
| 362 | return TRUE; |
| 363 | } |
| 364 | |
| 365 | /* |
| 366 | * get the query string |
| 367 | */ |
| 368 | int CVmObjHTTPRequest::getp_getQuery(VMG_ vm_obj_id_t self, |
| 369 | vm_val_t *retval, uint *oargc) |
| 370 | { |
| 371 | static CVmNativeCodeDesc desc(0); |
| 372 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 373 | return TRUE; |
| 374 | |
| 375 | /* create a validated ASCII string for the query string */ |
| 376 | new_ascii_string(vmg_ retval, get_ext()->req->resource_name->get()); |
| 377 | |
| 378 | /* handled */ |
| 379 | return TRUE; |
| 380 | } |
| 381 | |
| 382 | /* encoding modes for new_parsed_str */ |
| 383 | #define ENCMODE_NONE 0 /* no encoding */ |
| 384 | #define ENCMODE_URL 1 /* URL encoding - translate %xx codes */ |
| 385 | #define ENCMODE_FORM 2 /* form-data: translate %xx, and + to space */ |
| 386 | #define ENCMODE_MIME 3 /* MIME header: translate ?= strings */ |
| 387 | |
| 388 | /* |
| 389 | * Create a parsed URL string value. This converts %xx sequences to bytes, |
| 390 | * and ensures that the results are well-formed UTF-8 characters. |
| 391 | */ |
| 392 | static void new_parsed_str(VMG_ vm_val_t *ret, const char *str, size_t len, |
| 393 | int encmode) |
| 394 | { |
| 395 | char *src, *dst; |
| 396 | |
| 397 | /* create the raw string */ |
| 398 | ret->set_obj(CVmObjString::create(vmg_ FALSE, str, len)); |
| 399 | CVmObjString *s = (CVmObjString *)vm_objp(vmg_ ret->val.obj); |
| 400 | |
| 401 | /* get the string buffer */ |
| 402 | char *buf = s->cons_get_buf(); |
| 403 | char *bufend = buf + len; |
| 404 | |
| 405 | /* |
| 406 | * if desired, decode url-encoding: run through the string, converting |
| 407 | * '%xx' sequences to bytes, and '+' characters to spaces |
| 408 | */ |
| 409 | if (encmode == ENCMODE_URL || encmode == ENCMODE_FORM) |
| 410 | { |
| 411 | for (src = dst = buf ; src < bufend ; ) |
| 412 | { |
| 413 | /* if this is a '%xx' sequence, convert it */ |
| 414 | if (*src == '%' && src + 2 < bufend |
| 415 | && is_xdigit(*(src+1)) && is_xdigit(*(src+2))) |
| 416 | { |
| 417 | /* generate the character value */ |
| 418 | int c = (value_of_xdigit(*(src+1)) << 4) |
| 419 | | value_of_xdigit(*(src+2)); |
| 420 | |
| 421 | /* skip the three-character %xx sequence */ |
| 422 | src += 3; |
| 423 | |
| 424 | /* |
| 425 | * if this is an encoded CR, and an LF follows, decode the |
| 426 | * whole sequence to a single '\n' |
| 427 | */ |
| 428 | if (c == '\r' |
| 429 | && src + 2 < bufend |
| 430 | && memicmp(src, "%0a", 3) == 0) |
| 431 | { |
| 432 | /* change to '\n' */ |
| 433 | c = '\n'; |
| 434 | |
| 435 | /* skip the in the source */ |
| 436 | src += 3; |
| 437 | } |
| 438 | |
| 439 | /* set the character in the output */ |
| 440 | *dst++ = (char)(unsigned char)c; |
| 441 | } |
| 442 | else if (*src == '+' |
| 443 | && (encmode == ENCMODE_FORM || encmode == ENCMODE_URL)) |
| 444 | { |
| 445 | /* for form data, translate + to space */ |
| 446 | *dst++ = ' '; |
| 447 | ++src; |
| 448 | } |
| 449 | else if ((*src == '\r' || *src == '\n') |
| 450 | && encmode == ENCMODE_FORM) |
| 451 | { |
| 452 | /* for form data, strip out newlines */ |
| 453 | ++src; |
| 454 | } |
| 455 | else |
| 456 | { |
| 457 | /* ordinary character - copy as-is */ |
| 458 | *dst++ = *src++; |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | /* |
| 463 | * update the length - the string might have contracted, since |
| 464 | * '%xx' sequences might have turned into single bytes |
| 465 | */ |
| 466 | len = dst - buf; |
| 467 | bufend = dst; |
| 468 | s->cons_set_len(len); |
| 469 | } |
| 470 | else if (encmode == ENCMODE_MIME) |
| 471 | { |
| 472 | // $$$ decode the MIME ?= encoding |
| 473 | } |
| 474 | |
| 475 | /* ensure that the buffer has only well-formed UTF-8 characters */ |
| 476 | CCharmapToUni::validate(buf, bufend - buf); |
| 477 | } |
| 478 | |
| 479 | /* add a parsed query string element to a lookup table */ |
| 480 | static void add_parsed_val(VMG_ CVmObjLookupTable *tab, const vm_val_t *key, |
| 481 | const char *str, size_t len, int encmode) |
| 482 | { |
| 483 | /* stack the key for gc protection */ |
| 484 | G_stk->push(key); |
| 485 | |
| 486 | /* create a parsed string value to add to the table */ |
| 487 | vm_val_t val; |
| 488 | new_parsed_str(vmg_ &val, str, len, encmode); |
| 489 | G_stk->push(&val); |
| 490 | |
| 491 | /* add or extend the table entry */ |
| 492 | vm_val_t oldval; |
| 493 | const char *oldstr; |
| 494 | if (tab->index_check(vmg_ &oldval, key) |
| 495 | && (oldstr = oldval.get_as_string(vmg0_)) != 0) |
| 496 | { |
| 497 | /* |
| 498 | * it's already in the table - make it a comma-separated list by |
| 499 | * appending ", val" to the existing key |
| 500 | */ |
| 501 | |
| 502 | /* get the parsed string we're adding */ |
| 503 | const char *newstr = val.get_as_string(vmg0_); |
| 504 | |
| 505 | /* allocate the combined string as len1 + len2 + 2 (for the ", ") */ |
| 506 | vm_val_t cval; |
| 507 | size_t clen = vmb_get_len(oldstr) + vmb_get_len(newstr) + 2; |
| 508 | cval.set_obj(CVmObjString::create(vmg_ FALSE, clen)); |
| 509 | CVmObjString *cstr = (CVmObjString *)vm_objp(vmg_ cval.val.obj); |
| 510 | |
| 511 | /* build the new string */ |
| 512 | t3sprintf(cstr->cons_get_buf(), clen, "%.*s, %.*s", |
| 513 | (int)vmb_get_len(oldstr), oldstr + VMB_LEN, |
| 514 | (int)vmb_get_len(newstr), newstr + VMB_LEN); |
| 515 | |
| 516 | /* use the combined string as the value */ |
| 517 | G_stk->discard(); |
| 518 | val = cval; |
| 519 | G_stk->push(&val); |
| 520 | } |
| 521 | |
| 522 | /* it's not in the table yet - add it */ |
| 523 | tab->set_or_add_entry(vmg_ key, &val); |
| 524 | |
| 525 | /* discard the gc protection */ |
| 526 | G_stk->discard(2); |
| 527 | } |
| 528 | |
| 529 | /* add a parsed query string element under an integer key */ |
| 530 | static void add_parsed_val(VMG_ CVmObjLookupTable *tab, int key, |
| 531 | const char *str, size_t len, int encmode) |
| 532 | { |
| 533 | /* set up a vm_val_t with the integer key value */ |
| 534 | vm_val_t keyval; |
| 535 | keyval.set_int(key); |
| 536 | |
| 537 | /* add the value to the table */ |
| 538 | add_parsed_val(vmg_ tab, &keyval, str, len, encmode); |
| 539 | } |
| 540 | |
| 541 | /* add a parsed query string element under a string key */ |
| 542 | static void add_parsed_val(VMG_ CVmObjLookupTable *tab, |
| 543 | const char *keystr, size_t keylen, |
| 544 | const char *str, size_t len, |
| 545 | int encmode) |
| 546 | { |
| 547 | /* set up the key as a parsed string */ |
| 548 | vm_val_t key; |
| 549 | new_parsed_str(vmg_ &key, keystr, keylen, encmode); |
| 550 | |
| 551 | /* add the value */ |
| 552 | add_parsed_val(vmg_ tab, &key, str, len, encmode); |
| 553 | } |
| 554 | |
| 555 | /* |
| 556 | * Parse query parameters. This can be used for the part of a URL query |
| 557 | * string after the first '?', or for a message body with content-type |
| 558 | * application/x-www-form-urlencoded, since they have identical formats. |
| 559 | */ |
| 560 | static void parse_query_params(VMG_ CVmObjLookupTable *tab, const char *p, |
| 561 | int encmode) |
| 562 | { |
| 563 | /* parse the arguments */ |
| 564 | while (*p != '\0') |
| 565 | { |
| 566 | /* the end of this argument is at the next '&' */ |
| 567 | const char *amp = strchr(p, '&'); |
| 568 | if (amp == 0) |
| 569 | amp = p + strlen(p); |
| 570 | |
| 571 | /* find the '=', if any */ |
| 572 | const char *eq = strchr(p, '='); |
| 573 | if (eq == 0 || eq > amp) |
| 574 | eq = amp; |
| 575 | |
| 576 | /* add the resource name under the name key */ |
| 577 | add_parsed_val(vmg_ tab, p, eq - p, |
| 578 | eq + 1, eq == amp ? 0 : amp - eq - 1, encmode); |
| 579 | |
| 580 | /* move on to the next delimiter */ |
| 581 | p = amp; |
| 582 | if (*p != '\0') |
| 583 | ++p; |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | /* |
| 588 | * parse the query string into the resource name and parameter list |
| 589 | */ |
| 590 | int CVmObjHTTPRequest::getp_parseQuery(VMG_ vm_obj_id_t self, |
| 591 | vm_val_t *retval, uint *oargc) |
| 592 | { |
| 593 | static CVmNativeCodeDesc desc(0); |
| 594 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 595 | return TRUE; |
| 596 | |
| 597 | /* retrieve the query string from the request */ |
| 598 | TadsHttpRequest *req = get_ext()->req; |
| 599 | const char *q = req->resource_name->get(); |
| 600 | size_t ql = strlen(q); |
| 601 | |
| 602 | /* create a lookup table to hold the result; push it for gc protection */ |
| 603 | retval->set_obj(CVmObjLookupTable::create(vmg_ FALSE, 16, 32)); |
| 604 | G_stk->push(retval); |
| 605 | CVmObjLookupTable *tab = |
| 606 | (CVmObjLookupTable *)vm_objp(vmg_ retval->val.obj); |
| 607 | |
| 608 | /* |
| 609 | * the resource name is the part of the query up to the first '?', or |
| 610 | * the entire string if there's no '?' |
| 611 | */ |
| 612 | const char *qq = strchr(q, '?'); |
| 613 | if (qq == 0) |
| 614 | qq = q + ql; |
| 615 | |
| 616 | /* add the resource name under key [1] */ |
| 617 | add_parsed_val(vmg_ tab, 1, q, qq - q, ENCMODE_URL); |
| 618 | |
| 619 | /* parse the query parameters, starting after the '?' */ |
| 620 | if (*qq == '?') |
| 621 | parse_query_params(vmg_ tab, qq + 1, ENCMODE_URL); |
| 622 | |
| 623 | /* done with the gc protection */ |
| 624 | G_stk->discard(); |
| 625 | |
| 626 | /* handled */ |
| 627 | return TRUE; |
| 628 | } |
| 629 | |
| 630 | /* |
| 631 | * parse the query string and return a specified parametre |
| 632 | */ |
| 633 | int CVmObjHTTPRequest::getp_getQueryParam(VMG_ vm_obj_id_t self, |
| 634 | vm_val_t *retval, uint *oargc) |
| 635 | { |
| 636 | uint argc = (oargc != 0 ? *oargc : 0); |
| 637 | static CVmNativeCodeDesc desc(1); |
| 638 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 639 | return TRUE; |
| 640 | |
| 641 | /* get the target parameter name */ |
| 642 | const char *paramName = G_stk->get(0)->get_as_string(vmg0_); |
| 643 | if (paramName == 0) |
| 644 | err_throw(VMERR_STRING_VAL_REQD); |
| 645 | |
| 646 | /* get the length and buffer from the string */ |
| 647 | size_t paramLen = vmb_get_len(paramName); |
| 648 | paramName += VMB_LEN; |
| 649 | |
| 650 | /* retrieve the query string from the request */ |
| 651 | TadsHttpRequest *req = get_ext()->req; |
| 652 | const char *q = req->resource_name->get(); |
| 653 | size_t ql = strlen(q); |
| 654 | |
| 655 | /* presume we won't find the parameter we're looking for */ |
| 656 | retval->set_nil(); |
| 657 | |
| 658 | /* scan the parameters, if any */ |
| 659 | for (const char *qq = strchr(q, '?') ; qq != 0 && *qq != '\0' ; ) |
| 660 | { |
| 661 | /* skip this separator character */ |
| 662 | ++qq; |
| 663 | |
| 664 | /* find the end of this parameter */ |
| 665 | const char *amp = strchr(qq, '&'); |
| 666 | if (amp == 0) |
| 667 | amp = q + ql; |
| 668 | |
| 669 | /* find the value portion, if present */ |
| 670 | const char *eq = strchr(qq, '='); |
| 671 | if (eq == 0 || eq > amp) |
| 672 | eq = amp; |
| 673 | |
| 674 | /* |
| 675 | * Compare this to the name we're looking for. Note that URLs are |
| 676 | * either plain ASCII or UTF-8, so we can just do the comparison on |
| 677 | * a byte-by-byte basis as our paramName string is also UTF-8. |
| 678 | */ |
| 679 | if ((size_t)(eq - qq) == paramLen |
| 680 | && memcmp(qq, paramName, paramLen) == 0) |
| 681 | { |
| 682 | /* this is the one - create the value string */ |
| 683 | new_parsed_str(vmg_ retval, eq + 1, |
| 684 | eq == amp ? 0 : amp - eq - 1, ENCMODE_URL); |
| 685 | |
| 686 | /* done with our search */ |
| 687 | break; |
| 688 | } |
| 689 | |
| 690 | /* move on to the next separator */ |
| 691 | qq = amp; |
| 692 | } |
| 693 | |
| 694 | /* discard arguments */ |
| 695 | G_stk->discard(argc); |
| 696 | |
| 697 | /* handled */ |
| 698 | return TRUE; |
| 699 | } |
| 700 | |
| 701 | /* |
| 702 | * get the headers |
| 703 | */ |
| 704 | int CVmObjHTTPRequest::getp_getHeaders(VMG_ vm_obj_id_t self, |
| 705 | vm_val_t *retval, uint *oargc) |
| 706 | { |
| 707 | static CVmNativeCodeDesc desc(0); |
| 708 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 709 | return TRUE; |
| 710 | |
| 711 | /* retrieve the headers from the request */ |
| 712 | TadsHttpRequest *req = get_ext()->req; |
| 713 | TadsHttpRequestHeader *hdrs = req->hdr_list; |
| 714 | |
| 715 | /* create a lookup table to hold the result; push it for gc protection */ |
| 716 | retval->set_obj(CVmObjLookupTable::create(vmg_ FALSE, 32, 64)); |
| 717 | G_stk->push(retval); |
| 718 | CVmObjLookupTable *tab = |
| 719 | (CVmObjLookupTable *)vm_objp(vmg_ retval->val.obj); |
| 720 | |
| 721 | /* |
| 722 | * The first item in the list is the special "request line," with the |
| 723 | * HTTP verb and resource name; it's not really a header, as it doesn't |
| 724 | * have a name/value pair, so we file it under the key [1]. |
| 725 | */ |
| 726 | add_parsed_val(vmg_ tab, 1, hdrs->name, strlen(hdrs->name), ENCMODE_NONE); |
| 727 | |
| 728 | /* add the rest as key/value pairs */ |
| 729 | for (hdrs = hdrs->nxt ; hdrs != 0 ; hdrs = hdrs->nxt) |
| 730 | add_parsed_val(vmg_ tab, hdrs->name, strlen(hdrs->name), |
| 731 | hdrs->value, strlen(hdrs->value), ENCMODE_NONE); |
| 732 | |
| 733 | /* done with the gc protection */ |
| 734 | G_stk->discard(); |
| 735 | |
| 736 | /* handled */ |
| 737 | return TRUE; |
| 738 | } |
| 739 | |
| 740 | /* |
| 741 | * get an individual cookie |
| 742 | */ |
| 743 | int CVmObjHTTPRequest::getp_getCookie(VMG_ vm_obj_id_t self, |
| 744 | vm_val_t *retval, uint *oargc) |
| 745 | { |
| 746 | uint argc = (oargc != 0 ? *oargc : 0); |
| 747 | static CVmNativeCodeDesc desc(1); |
| 748 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 749 | return TRUE; |
| 750 | |
| 751 | /* retrieve the headers from the request */ |
| 752 | TadsHttpRequest *req = get_ext()->req; |
| 753 | TadsHttpRequestHeader *hdrs = req->hdr_list; |
| 754 | |
| 755 | /* get the cookie name argument */ |
| 756 | const char *cname = G_stk->get(0)->get_as_string(vmg0_); |
| 757 | if (cname == 0) |
| 758 | err_throw(VMERR_BAD_TYPE_BIF); |
| 759 | |
| 760 | /* presume we won't find a match */ |
| 761 | retval->set_nil(); |
| 762 | |
| 763 | /* scan for "Cookie" headers */ |
| 764 | for (hdrs = hdrs->nxt ; hdrs != 0 ; hdrs = hdrs->nxt) |
| 765 | { |
| 766 | /* if this is a Cookie: header, process it */ |
| 767 | if (stricmp(hdrs->name, "cookie") == 0) |
| 768 | { |
| 769 | /* scan the list of cookie name=value pairs */ |
| 770 | for (const char *p = hdrs->value ; *p != '\0' ; ) |
| 771 | { |
| 772 | /* skip leading whitespace */ |
| 773 | for ( ; isspace(*p) ; ++p) ; |
| 774 | |
| 775 | /* the cookie name ends at the '=', ';', ',', or null */ |
| 776 | const char *name = p; |
| 777 | for ( ; *p != '\0' && strchr("=;,", *p) == 0 ; ++p) ; |
| 778 | size_t namelen = p - name; |
| 779 | |
| 780 | /* if we found the '=', scan the value */ |
| 781 | const char *val = ""; |
| 782 | size_t vallen = 0; |
| 783 | if (*p == '=') |
| 784 | { |
| 785 | /* skip the '=' and scan for the end of the cookie */ |
| 786 | for (val = ++p ; *p != '\0' && strchr(" \t;,", *p) == 0 ; |
| 787 | ++p) ; |
| 788 | vallen = p - val; |
| 789 | } |
| 790 | |
| 791 | /* if this matches the name we're looking for, return it */ |
| 792 | if (namelen == vmb_get_len(cname) |
| 793 | && memcmp(name, cname + VMB_LEN, namelen) == 0) |
| 794 | { |
| 795 | /* it's a match - return the value as a string */ |
| 796 | new_parsed_str(vmg_ retval, val, vallen, ENCMODE_NONE); |
| 797 | |
| 798 | /* stop looking */ |
| 799 | goto done; |
| 800 | } |
| 801 | |
| 802 | /* scan ahead to the next non-delimiter */ |
| 803 | for ( ; *p != '\0' && strchr(" \t;,", *p) != 0 ; ++p) ; |
| 804 | } |
| 805 | } |
| 806 | } |
| 807 | |
| 808 | done: |
| 809 | /* done with the arguments */ |
| 810 | G_stk->discard(argc); |
| 811 | |
| 812 | /* handled */ |
| 813 | return TRUE; |
| 814 | } |
| 815 | |
| 816 | /* |
| 817 | * get the cookies |
| 818 | */ |
| 819 | int CVmObjHTTPRequest::getp_getCookies(VMG_ vm_obj_id_t self, |
| 820 | vm_val_t *retval, uint *oargc) |
| 821 | { |
| 822 | static CVmNativeCodeDesc desc(0); |
| 823 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 824 | return TRUE; |
| 825 | |
| 826 | /* retrieve the headers from the request */ |
| 827 | TadsHttpRequest *req = get_ext()->req; |
| 828 | TadsHttpRequestHeader *hdrs = req->hdr_list; |
| 829 | |
| 830 | /* create a lookup table to hold the result; push it for gc protection */ |
| 831 | retval->set_obj(CVmObjLookupTable::create(vmg_ FALSE, 32, 64)); |
| 832 | G_stk->push(retval); |
| 833 | CVmObjLookupTable *tab = |
| 834 | (CVmObjLookupTable *)vm_objp(vmg_ retval->val.obj); |
| 835 | |
| 836 | /* scan for "Cookie" headers */ |
| 837 | for (hdrs = hdrs->nxt ; hdrs != 0 ; hdrs = hdrs->nxt) |
| 838 | { |
| 839 | /* if this is a Cookie: header, process it */ |
| 840 | if (stricmp(hdrs->name, "cookie") == 0) |
| 841 | { |
| 842 | /* scan the list of cookie name=value pairs */ |
| 843 | for (const char *p = hdrs->value ; *p != '\0' ; ) |
| 844 | { |
| 845 | /* skip leading whitespace */ |
| 846 | for ( ; isspace(*p) ; ++p) ; |
| 847 | |
| 848 | /* the cookie name ends at the '=', ';', ',', or null */ |
| 849 | const char *name = p; |
| 850 | for ( ; *p != '\0' && strchr("=;,", *p) == 0 ; ++p) ; |
| 851 | size_t namelen = p - name; |
| 852 | |
| 853 | /* if we found the '=', scan the value */ |
| 854 | const char *val = ""; |
| 855 | size_t vallen = 0; |
| 856 | if (*p == '=') |
| 857 | { |
| 858 | /* skip the '=' and scan for the end of the cookie */ |
| 859 | for (val = ++p ; *p != '\0' && strchr(" \t;,", *p) == 0 ; |
| 860 | ++p) ; |
| 861 | vallen = p - val; |
| 862 | } |
| 863 | |
| 864 | /* add this cookie to the table */ |
| 865 | add_parsed_val(vmg_ tab, name, namelen, val, vallen, |
| 866 | ENCMODE_NONE); |
| 867 | |
| 868 | /* scan ahead to the next non-delimiter */ |
| 869 | for ( ; *p != '\0' && strchr(" \t;,", *p) != 0 ; ++p) ; |
| 870 | } |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | /* done with the gc protection */ |
| 875 | G_stk->discard(); |
| 876 | |
| 877 | /* handled */ |
| 878 | return TRUE; |
| 879 | } |
| 880 | |
| 881 | /* |
| 882 | * Find an attribute token in a content-type or similar header string. An |
| 883 | * attribute token is separated from preceding text by a ';', and has the |
| 884 | * form "name=value". The value can be in quotes, or can just be a token. |
| 885 | */ |
| 886 | static int parse_attr_token(const char *str, const char *attr_name, |
| 887 | const char *&val, size_t &vallen) |
| 888 | { |
| 889 | /* assume we won't find anything */ |
| 890 | val = 0; |
| 891 | vallen = 0; |
| 892 | |
| 893 | /* note the name length */ |
| 894 | size_t attr_name_len = strlen(attr_name); |
| 895 | |
| 896 | /* scan the string for attribute tokens, starting at the first ';' */ |
| 897 | for (const char *p = strchr(str, ';') ; p != 0 ; p = strchr(p, ';')) |
| 898 | { |
| 899 | /* skip spaces */ |
| 900 | for (++p ; isspace(*p) ; ++p) ; |
| 901 | |
| 902 | /* check to see if this is the desired attribute name */ |
| 903 | if (memicmp(p, attr_name, attr_name_len) != 0) |
| 904 | continue; |
| 905 | |
| 906 | /* skip the name and any subsequent spaces, and look for the '=' */ |
| 907 | for (p += attr_name_len ; isspace(*p) ; ++p) ; |
| 908 | if (*p != '=') |
| 909 | continue; |
| 910 | |
| 911 | /* skip the '=' and subsequent spaces */ |
| 912 | for (++p ; isspace(*p) ; ++p) ; |
| 913 | |
| 914 | /* |
| 915 | * Okay, we're at the attribute value. If there's a quote mark, |
| 916 | * the value is everything from here to the close quote. Otherwise |
| 917 | * it's everything up to the next space or semicolon. |
| 918 | */ |
| 919 | if (*p == '"') |
| 920 | { |
| 921 | /* skip the open quote, and find the close quote */ |
| 922 | for (val = ++p ; *p != '\0' && *p != '"' ; ++p) ; |
| 923 | } |
| 924 | else |
| 925 | { |
| 926 | /* it's from here to the next separator character */ |
| 927 | val = p; |
| 928 | for ( ; *p != '\0' && strchr(" \t;,", *p) == 0 ; ++p) ; |
| 929 | } |
| 930 | |
| 931 | /* note the length, and return success */ |
| 932 | vallen = p - val; |
| 933 | return TRUE; |
| 934 | } |
| 935 | |
| 936 | /* didn't find it - return failure */ |
| 937 | return FALSE; |
| 938 | } |
| 939 | |
| 940 | /* |
| 941 | * Match two attribute tokens |
| 942 | */ |
| 943 | static int match_attrs(const char *a, size_t alen, |
| 944 | const char *b, size_t blen) |
| 945 | { |
| 946 | /* if the lengths don't match, it's not a match */ |
| 947 | if (alen != blen) |
| 948 | return FALSE; |
| 949 | |
| 950 | /* if both are empty strings, it's a match */ |
| 951 | if (alen == 0 && blen == 0) |
| 952 | return TRUE; |
| 953 | |
| 954 | /* compare the strings */ |
| 955 | return memcmp(a, b, alen) == 0; |
| 956 | } |
| 957 | |
| 958 | /* |
| 959 | * send a cookie header |
| 960 | */ |
| 961 | int vm_httpreq_cookie::send(TadsServerThread *t) |
| 962 | { |
| 963 | /* send the Set-Cookie header */ |
| 964 | return (t->send("Set-Cookie: ") |
| 965 | && t->send(name) |
| 966 | && t->send("=") |
| 967 | && t->send(val) |
| 968 | && t->send("\r\n")); |
| 969 | } |
| 970 | |
| 971 | /* |
| 972 | * set a cookie in the reply |
| 973 | */ |
| 974 | int CVmObjHTTPRequest::getp_setCookie(VMG_ vm_obj_id_t self, |
| 975 | vm_val_t *retval, uint *oargc) |
| 976 | { |
| 977 | uint argc = (oargc != 0 ? *oargc : 0); |
| 978 | static CVmNativeCodeDesc desc(2); |
| 979 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 980 | return TRUE; |
| 981 | |
| 982 | /* get the cookie name and value */ |
| 983 | const char *cname = G_stk->get(0)->get_as_string(vmg0_); |
| 984 | const char *cval = G_stk->get(1)->get_as_string(vmg0_); |
| 985 | |
| 986 | /* check that we got string values */ |
| 987 | if (cname == 0 || cval == 0) |
| 988 | err_throw(VMERR_BAD_TYPE_BIF); |
| 989 | |
| 990 | /* get the name and value length and buffer */ |
| 991 | size_t cname_len = vmb_get_len(cname), cval_len = vmb_get_len(cval); |
| 992 | cname += VMB_LEN; |
| 993 | cval += VMB_LEN; |
| 994 | |
| 995 | /* get a null-terminated copy of the value, and parse out the 'path' */ |
| 996 | char *cbuf = lib_copy_str(cval, cval_len); |
| 997 | const char *cpath, *cdom; |
| 998 | size_t cpathlen, cdomlen; |
| 999 | parse_attr_token(cbuf, "path", cpath, cpathlen); |
| 1000 | parse_attr_token(cbuf, "domain", cdom, cdomlen); |
| 1001 | |
| 1002 | /* search for an existing cookie with this name */ |
| 1003 | vm_httpreq_cookie *cookie; |
| 1004 | for (cookie = get_ext()->cookies ; cookie != 0 ; cookie = cookie->nxt) |
| 1005 | { |
| 1006 | /* check for a match */ |
| 1007 | if (strlen(cookie->name) == cname_len |
| 1008 | && memcmp(cookie->name, cname, cname_len) == 0) |
| 1009 | { |
| 1010 | /* parse the current value's path and domain attributes */ |
| 1011 | const char *vpath, *vdom; |
| 1012 | size_t vpathlen, vdomlen; |
| 1013 | parse_attr_token(cookie->val, "path", vpath, vpathlen); |
| 1014 | parse_attr_token(cookie->val, "domain", vdom, vdomlen); |
| 1015 | |
| 1016 | /* |
| 1017 | * Check to see if the path and domain match. If not, this |
| 1018 | * counts as a distinct cookie. |
| 1019 | */ |
| 1020 | if (!match_attrs(vpath, vpathlen, cpath, cpathlen) |
| 1021 | || !match_attrs(vdom, vdomlen, cdom, cdomlen)) |
| 1022 | continue; |
| 1023 | |
| 1024 | /* it's already defined - redefine it with the new value */ |
| 1025 | lib_free_str(cookie->val); |
| 1026 | cookie->val = lib_copy_str(cval, cval_len); |
| 1027 | break; |
| 1028 | } |
| 1029 | } |
| 1030 | |
| 1031 | /* done with the allocated value copy */ |
| 1032 | lib_free_str(cbuf); |
| 1033 | |
| 1034 | /* if we didn't replace an existing entry, create a new one */ |
| 1035 | if (cookie == 0) |
| 1036 | { |
| 1037 | /* create the entry */ |
| 1038 | cookie = new vm_httpreq_cookie(cname, cname_len, cval, cval_len); |
| 1039 | |
| 1040 | /* link it into our list */ |
| 1041 | cookie->nxt = get_ext()->cookies; |
| 1042 | get_ext()->cookies = cookie; |
| 1043 | } |
| 1044 | |
| 1045 | /* done with the arguments */ |
| 1046 | G_stk->discard(argc); |
| 1047 | |
| 1048 | /* no return value */ |
| 1049 | retval->set_nil(); |
| 1050 | |
| 1051 | /* handled */ |
| 1052 | return TRUE; |
| 1053 | } |
| 1054 | |
| 1055 | /* |
| 1056 | * Find the charset property in a Content-Type header. Fills in 'cs' with |
| 1057 | * a mapper object if we find a text content type, otherwise nil. In the |
| 1058 | * nil case we set cs->val.obj = VM_INVALID_OBJ, so you can use that field |
| 1059 | * where a vm_obj_id_t is required in either case. We return the file mode |
| 1060 | * to use for a file opened on this content: VMOBJFILE_MODE_TEXT if we find |
| 1061 | * a character set, VMOBJFILE_MODE_RAW if not. |
| 1062 | */ |
| 1063 | static int get_charset_map(VMG_ const char *ct, vm_val_t *cs) |
| 1064 | { |
| 1065 | /* presume we won't create a mapper */ |
| 1066 | cs->set_nil(); |
| 1067 | cs->val.obj = VM_INVALID_OBJ; |
| 1068 | |
| 1069 | /* get the Content-Type header */ |
| 1070 | if (ct != 0 |
| 1071 | && (memcmp(ct, "text/", 5) == 0 |
| 1072 | || memcmp(ct, "application/x-www-form-urlencoded", 33) == 0)) |
| 1073 | { |
| 1074 | /* |
| 1075 | * It's a text content type, so we'll use a text mapping. Scan the |
| 1076 | * content-type string for a "charset" parameter. |
| 1077 | */ |
| 1078 | const char *cname; |
| 1079 | size_t cnamelen; |
| 1080 | if (parse_attr_token(ct, "charset", cname, cnamelen)) |
| 1081 | { |
| 1082 | /* got it - try loading the character mapper for the set name */ |
| 1083 | cs->set_obj(CVmObjCharSet::create(vmg_ FALSE, cname, cnamelen)); |
| 1084 | } |
| 1085 | |
| 1086 | /* if we didn't create a mapper, or it's not valid, use ASCII */ |
| 1087 | if (cs->typ == VM_NIL |
| 1088 | || ((CVmObjCharSet *)vm_objp(vmg_ cs->val.obj)) |
| 1089 | ->get_to_uni(vmg0_) == 0) |
| 1090 | { |
| 1091 | /* create a us-ascii mapper */ |
| 1092 | cs->set_obj(CVmObjCharSet::create(vmg_ FALSE, "us-ascii", 8)); |
| 1093 | } |
| 1094 | |
| 1095 | /* indicate that they should use text mode on the file */ |
| 1096 | return VMOBJFILE_MODE_TEXT; |
| 1097 | } |
| 1098 | else |
| 1099 | { |
| 1100 | /* it's not a text content type - use raw mode */ |
| 1101 | return VMOBJFILE_MODE_RAW; |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | /* |
| 1106 | * StringRef data source. This is a simple subclass of the basic string |
| 1107 | * data source; the only specialization is that we keep a reference to the |
| 1108 | * StringRef object, and release it on close. |
| 1109 | */ |
| 1110 | class CVmStringRefSource: public CVmStringSource |
| 1111 | { |
| 1112 | public: |
| 1113 | CVmStringRefSource(StringRef *s) |
| 1114 | : CVmStringSource(s->get(), s->getlen()) |
| 1115 | { |
| 1116 | /* keep a reference on the source */ |
| 1117 | this->s = s; |
| 1118 | s->add_ref(); |
| 1119 | } |
| 1120 | |
| 1121 | CVmStringRefSource(StringRef *s, long start_ofs, long len) |
| 1122 | : CVmStringSource(s->get() + start_ofs, len) |
| 1123 | { |
| 1124 | /* keep a reference on the source */ |
| 1125 | this->s = s; |
| 1126 | s->add_ref(); |
| 1127 | } |
| 1128 | |
| 1129 | virtual CVmDataSource *clone(VMG_ const char * /*mode*/) |
| 1130 | { return new CVmStringRefSource(s, mem - s->get(), memlen); } |
| 1131 | |
| 1132 | ~CVmStringRefSource() |
| 1133 | { |
| 1134 | /* release our reference on the underlying source */ |
| 1135 | s->release_ref(); |
| 1136 | } |
| 1137 | |
| 1138 | protected: |
| 1139 | /* our underlying StringRef object */ |
| 1140 | StringRef *s; |
| 1141 | }; |
| 1142 | |
| 1143 | /* |
| 1144 | * throw a network error |
| 1145 | */ |
| 1146 | static void throw_net_err(VMG_ const char *msg, int sock_err) |
| 1147 | { |
| 1148 | /* |
| 1149 | * Determine the exception class, based on the error code: |
| 1150 | * |
| 1151 | *. - ECONNRESET -> SocketDisconnectException |
| 1152 | *. - everything else -> the base NetException |
| 1153 | */ |
| 1154 | vm_obj_id_t cl = VM_INVALID_OBJ; |
| 1155 | switch (sock_err) |
| 1156 | { |
| 1157 | case OS_ECONNRESET: |
| 1158 | case OS_ECONNABORTED: |
| 1159 | cl = G_predef->net_reset_exception; |
| 1160 | break; |
| 1161 | } |
| 1162 | |
| 1163 | /* |
| 1164 | * if we didn't pick a special class for the error, or the class we |
| 1165 | * selected wasn't imported, use the base NetException class by default |
| 1166 | */ |
| 1167 | if (cl == VM_INVALID_OBJ) |
| 1168 | cl = G_predef->net_exception; |
| 1169 | |
| 1170 | /* throw new exceptionClass(msg, errno) */ |
| 1171 | int argc = 1; |
| 1172 | if (sock_err != 0) |
| 1173 | { |
| 1174 | G_stk->push_int(vmg_ sock_err); |
| 1175 | ++argc; |
| 1176 | } |
| 1177 | G_interpreter->push_string(vmg_ msg); |
| 1178 | G_interpreter->throw_new_class(vmg_ cl, argc, msg); |
| 1179 | } |
| 1180 | |
| 1181 | /* |
| 1182 | * Seek the next multi-part boundary |
| 1183 | */ |
| 1184 | static const char *next_boundary(const char *startp, const char *endp, |
| 1185 | const char *b, size_t blen, int need_crlf) |
| 1186 | { |
| 1187 | /* scan for the next boundary */ |
| 1188 | for (const char *p = startp ; p + 2 + blen <= endp ; ++p) |
| 1189 | { |
| 1190 | /* check for a match */ |
| 1191 | if (p[0] != '-' || p[1] != '-' || memcmp(p+2, b, blen) != 0) |
| 1192 | continue; |
| 1193 | |
| 1194 | /* if we need a newline prefix, check that it's there */ |
| 1195 | if (need_crlf && (p < startp + 2 || p[-2] != '\r' || p[-1] != '\n')) |
| 1196 | continue; |
| 1197 | |
| 1198 | /* it's a match - return the part after the '--' prefix */ |
| 1199 | return p + 2; |
| 1200 | } |
| 1201 | |
| 1202 | /* didn't find it */ |
| 1203 | return 0; |
| 1204 | } |
| 1205 | |
| 1206 | /* |
| 1207 | * Parse multi-part data. |
| 1208 | */ |
| 1209 | static void parse_multipart(VMG_ CVmObjLookupTable *tab, StringRef *body, |
| 1210 | const char *ct) |
| 1211 | { |
| 1212 | /* |
| 1213 | * find the "boundary" attribute in the content-type string; if it's |
| 1214 | * not present, we can't go on, since this is required to parse the |
| 1215 | * content sections |
| 1216 | */ |
| 1217 | const char *bndry; |
| 1218 | size_t bndry_len; |
| 1219 | if (!parse_attr_token(ct, "boundary", bndry, bndry_len)) |
| 1220 | return; |
| 1221 | |
| 1222 | /* scan the sections */ |
| 1223 | const char *p = body->get(); |
| 1224 | const char *endp = p + body->getlen(); |
| 1225 | for (p = next_boundary(p, endp, bndry, bndry_len, FALSE) ; p != 0 ; ) |
| 1226 | { |
| 1227 | /* no error for the section yet */ |
| 1228 | const char *errmsg = 0; |
| 1229 | |
| 1230 | /* skip ahead to the end of the boundary string */ |
| 1231 | p += bndry_len; |
| 1232 | |
| 1233 | /* if we're at a '--', we're done */ |
| 1234 | if (*p == '-' && *(p+1) == '-') |
| 1235 | break; |
| 1236 | |
| 1237 | /* otherwise, we should be at a newline; if not, give up */ |
| 1238 | for ( ; *p == ' ' || *p == '\t' ; ++p) ; |
| 1239 | if (*p++ != '\r' || *p++ != '\n') |
| 1240 | break; |
| 1241 | |
| 1242 | /* |
| 1243 | * Parse the headers for this section. To do this, we'll need to |
| 1244 | * make a separate writable copy of the header section - scan ahead |
| 1245 | * for the double CR-LF. |
| 1246 | */ |
| 1247 | const char *hdr_start = p; |
| 1248 | if ((p = strstr(p, "\r\n\r\n")) == 0) |
| 1249 | break; |
| 1250 | |
| 1251 | /* skip the double CR-LF to get to the section body */ |
| 1252 | const char *sbody = (p += 4); |
| 1253 | |
| 1254 | /* find the boundary at the end of this section */ |
| 1255 | if ((p = next_boundary(p, endp, bndry, bndry_len, TRUE)) == 0) |
| 1256 | break; |
| 1257 | |
| 1258 | /* |
| 1259 | * Note the length of the body - if exclude. The body excludes the |
| 1260 | * CR-LF and the "--" preceding the boundary marker, so deduct four |
| 1261 | * bytes from the current position. |
| 1262 | */ |
| 1263 | long sbody_len = p - sbody - 4; |
| 1264 | |
| 1265 | /* make a copy of the header section */ |
| 1266 | StringRef *hdr_copy = new StringRef(hdr_start, sbody - 4 - hdr_start); |
| 1267 | |
| 1268 | /* parse the headers */ |
| 1269 | TadsHttpRequestHeader *hdrs = 0, *hdrs_tail = 0; |
| 1270 | TadsHttpRequestHeader::parse_headers( |
| 1271 | hdrs, hdrs_tail, TRUE, hdr_copy, 0); |
| 1272 | |
| 1273 | /* get the content-disposition and content-type */ |
| 1274 | const char *scd = hdrs->find("content-disposition"); |
| 1275 | const char *sct = hdrs->find("content-type"); |
| 1276 | const char *fldname, *filename; |
| 1277 | size_t fldname_len, filename_len; |
| 1278 | vm_val_t fldval, keyval; |
| 1279 | int has_fname; |
| 1280 | |
| 1281 | /* |
| 1282 | * Use text/plain as the default content type. Since we send text |
| 1283 | * out in utf-8 mode, assume that responses come back in utf-8 |
| 1284 | * mode. |
| 1285 | */ |
| 1286 | if (sct == 0) |
| 1287 | sct = "text/plain; charset=utf-8"; |
| 1288 | |
| 1289 | /* make sure the content-disposition is "form-data" */ |
| 1290 | if (scd == 0 || memcmp(scd, "form-data", 9) != 0) |
| 1291 | goto section_done; |
| 1292 | |
| 1293 | /* |
| 1294 | * Get the "name" attribute - this is <INPUT> field's NAME value. |
| 1295 | * This is the table key for this section, so if it's not set we |
| 1296 | * can't do anything with this section. |
| 1297 | */ |
| 1298 | if (!parse_attr_token(scd, "name", fldname, fldname_len)) |
| 1299 | goto section_done; |
| 1300 | |
| 1301 | /* |
| 1302 | * Get the "filename" attribute. If this is an uploaded file, this |
| 1303 | * gives the name of the client-side file being uploaded. If it's |
| 1304 | * not present, this is a data <INPUT> field rather than a file |
| 1305 | * upload, so the content body is simply the field value. |
| 1306 | * |
| 1307 | * If the filename is empty and the file content has zero length, |
| 1308 | * it means that the user didn't select a file in this field. In |
| 1309 | * this case, use nil in place of the FileUpload object. |
| 1310 | */ |
| 1311 | has_fname = parse_attr_token(scd, "filename", filename, filename_len); |
| 1312 | if (has_fname && filename_len != 0 && sbody_len != 0) |
| 1313 | { |
| 1314 | /* |
| 1315 | * There's a "filename" attribute, so this is a file upload. |
| 1316 | * We'll represent this as a FileUpload object, with a |
| 1317 | * string-sourced File representing the body. |
| 1318 | * |
| 1319 | * If it's a text content type, we'll open the file in Text |
| 1320 | * mode with the character mapping specifed in the content type |
| 1321 | * parameter. Otherwise, we'll open it in raw mode. Start by |
| 1322 | * checking the mode implied by the content type parameter. |
| 1323 | */ |
| 1324 | vm_val_t charset; |
| 1325 | int mode = get_charset_map(vmg_ sct, &charset); |
| 1326 | int textmode = (mode == VMOBJFILE_MODE_TEXT); |
| 1327 | |
| 1328 | /* save the character set for gc protection */ |
| 1329 | G_stk->push(&charset); |
| 1330 | |
| 1331 | /* create the memory data source for the file */ |
| 1332 | CVmStringRefSource *ds = new CVmStringRefSource( |
| 1333 | body, sbody - body->get(), sbody_len); |
| 1334 | |
| 1335 | /* create the file object */ |
| 1336 | vm_val_t file; |
| 1337 | file.set_obj(CVmObjFile::create( |
| 1338 | vmg_ FALSE, 0, textmode ? charset.val.obj : VM_INVALID_OBJ, |
| 1339 | ds, mode, VMOBJFILE_ACCESS_READ, textmode)); |
| 1340 | |
| 1341 | /* |
| 1342 | * discard the gc protection for the character set (it's safely |
| 1343 | * ensconced in the file now), and push the new file object |
| 1344 | */ |
| 1345 | G_stk->discard(); |
| 1346 | G_stk->push(&file); |
| 1347 | |
| 1348 | /* make sure the FileUpload is defined */ |
| 1349 | if (G_predef->file_upload_cl == VM_INVALID_OBJ) |
| 1350 | { |
| 1351 | errmsg = "Parsing form fields: FileUpload class is missing"; |
| 1352 | goto section_done; |
| 1353 | } |
| 1354 | |
| 1355 | /* call FileUpload(file, contentType, filename) */ |
| 1356 | G_interpreter->push_string(vmg_ filename, filename_len); |
| 1357 | G_interpreter->push_string(vmg_ sct); |
| 1358 | G_interpreter->push(&file); |
| 1359 | vm_objp(vmg_ G_predef->file_upload_cl)->create_instance( |
| 1360 | vmg_ G_predef->file_upload_cl, 0, 3); |
| 1361 | |
| 1362 | /* the new object is in R0 */ |
| 1363 | fldval = *G_interpreter->get_r0(); |
| 1364 | |
| 1365 | /* discard the earlier gc protection; push the field value */ |
| 1366 | G_stk->discard(2); |
| 1367 | G_stk->push(&fldval); |
| 1368 | } |
| 1369 | else if (has_fname) |
| 1370 | { |
| 1371 | /* |
| 1372 | * We have a filename attribute, but it's empty, and there's no |
| 1373 | * content body. Use nil as the value. |
| 1374 | */ |
| 1375 | fldval.set_nil(); |
| 1376 | G_stk->push(&fldval); |
| 1377 | } |
| 1378 | else |
| 1379 | { |
| 1380 | /* |
| 1381 | * There's no filename attribute, so this is a simple data |
| 1382 | * field, with the section content body as the field value. |
| 1383 | */ |
| 1384 | new_parsed_str(vmg_ &fldval, sbody, sbody_len, ENCMODE_NONE); |
| 1385 | G_stk->push(&fldval); |
| 1386 | } |
| 1387 | |
| 1388 | /* create the field name string as the table key */ |
| 1389 | new_parsed_str(vmg_ &keyval, fldname, fldname_len, ENCMODE_MIME); |
| 1390 | G_stk->push(&keyval); |
| 1391 | |
| 1392 | /* save the key/value pair in the table */ |
| 1393 | tab->set_or_add_entry(vmg_ &keyval, &fldval); |
| 1394 | |
| 1395 | /* discard gc protection */ |
| 1396 | G_stk->discard(2); |
| 1397 | |
| 1398 | section_done: |
| 1399 | /* free the headers */ |
| 1400 | delete hdrs; |
| 1401 | hdr_copy->release_ref(); |
| 1402 | |
| 1403 | /* if there's an error, throw it */ |
| 1404 | if (errmsg != 0) |
| 1405 | throw_net_err(vmg_ errmsg, 0); |
| 1406 | } |
| 1407 | } |
| 1408 | |
| 1409 | |
| 1410 | /* |
| 1411 | * get the posted form fields |
| 1412 | */ |
| 1413 | int CVmObjHTTPRequest::getp_getFormFields(VMG_ vm_obj_id_t self, |
| 1414 | vm_val_t *retval, uint *oargc) |
| 1415 | { |
| 1416 | static CVmNativeCodeDesc desc(0); |
| 1417 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 1418 | return TRUE; |
| 1419 | |
| 1420 | /* retrieve the headers from the request */ |
| 1421 | TadsHttpRequest *req = get_ext()->req; |
| 1422 | TadsHttpRequestHeader *hdrs = req->hdr_list; |
| 1423 | StringRef *body = req->body; |
| 1424 | |
| 1425 | /* if the body was too large, return 'overflow' */ |
| 1426 | if (req->overflow) |
| 1427 | { |
| 1428 | retval->set_obj(CVmObjString::create(vmg_ FALSE, "overflow", 8)); |
| 1429 | return TRUE; |
| 1430 | } |
| 1431 | |
| 1432 | /* if there's no message body, there are no form fields */ |
| 1433 | if (body == 0) |
| 1434 | { |
| 1435 | retval->set_nil(); |
| 1436 | return TRUE; |
| 1437 | } |
| 1438 | |
| 1439 | /* find the content type header */ |
| 1440 | const char *ct = hdrs->find("content-type"); |
| 1441 | int typ; |
| 1442 | if (ct != 0) |
| 1443 | { |
| 1444 | /* check what we have */ |
| 1445 | if (memicmp(ct, "application/x-www-form-urlencoded", 33) == 0) |
| 1446 | typ = 0; |
| 1447 | else if (memicmp(ct, "multipart/form-data", 19) == 0) |
| 1448 | typ = 1; |
| 1449 | else |
| 1450 | { |
| 1451 | /* it's not a posted format we recognize - return nil */ |
| 1452 | retval->set_nil(); |
| 1453 | return TRUE; |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | /* create a lookup table to hold the result; push it for gc protection */ |
| 1458 | retval->set_obj(CVmObjLookupTable::create(vmg_ FALSE, 32, 64)); |
| 1459 | G_stk->push(retval); |
| 1460 | CVmObjLookupTable *tab = |
| 1461 | (CVmObjLookupTable *)vm_objp(vmg_ retval->val.obj); |
| 1462 | |
| 1463 | /* parse the content type that we found */ |
| 1464 | if (typ == 0) |
| 1465 | { |
| 1466 | /* |
| 1467 | * URL-encoded form data. This is the same format as a URL query |
| 1468 | * string, so we can just apply that parser to the message body. |
| 1469 | */ |
| 1470 | parse_query_params(vmg_ tab, body->get(), ENCMODE_FORM); |
| 1471 | } |
| 1472 | else if (typ == 1) |
| 1473 | { |
| 1474 | /* |
| 1475 | * Multipart form-data. Invoke our generic multipart parser. |
| 1476 | */ |
| 1477 | parse_multipart(vmg_ tab, body, ct); |
| 1478 | } |
| 1479 | |
| 1480 | /* done with the gc protection */ |
| 1481 | G_stk->discard(); |
| 1482 | |
| 1483 | /* handled */ |
| 1484 | return TRUE; |
| 1485 | } |
| 1486 | |
| 1487 | /* |
| 1488 | * get the request body |
| 1489 | */ |
| 1490 | int CVmObjHTTPRequest::getp_getClientAddress(VMG_ vm_obj_id_t self, |
| 1491 | vm_val_t *retval, uint *oargc) |
| 1492 | { |
| 1493 | static CVmNativeCodeDesc desc(0); |
| 1494 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 1495 | return TRUE; |
| 1496 | |
| 1497 | /* retrieve the request */ |
| 1498 | TadsHttpRequest *req = get_ext()->req; |
| 1499 | TadsServerThread *t = req->thread; |
| 1500 | |
| 1501 | /* set up the return list, using address information from the thread */ |
| 1502 | G_interpreter->push_int(vmg_ t->get_client_port()); |
| 1503 | G_interpreter->push_string(vmg_ t->get_client_ip()); |
| 1504 | retval->set_obj(CVmObjList::create_from_stack(vmg_ 0, 2)); |
| 1505 | |
| 1506 | /* handled */ |
| 1507 | return TRUE; |
| 1508 | } |
| 1509 | |
| 1510 | /* |
| 1511 | * get the request body |
| 1512 | */ |
| 1513 | int CVmObjHTTPRequest::getp_getBody(VMG_ vm_obj_id_t self, |
| 1514 | vm_val_t *retval, uint *oargc) |
| 1515 | { |
| 1516 | static CVmNativeCodeDesc desc(0); |
| 1517 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 1518 | return TRUE; |
| 1519 | |
| 1520 | /* retrieve the headers from the request */ |
| 1521 | TadsHttpRequest *req = get_ext()->req; |
| 1522 | TadsHttpRequestHeader *hdrs = req->hdr_list; |
| 1523 | StringRef *body = req->body; |
| 1524 | |
| 1525 | /* if the body was too large, return 'overflow' */ |
| 1526 | if (req->overflow) |
| 1527 | { |
| 1528 | retval->set_obj(CVmObjString::create(vmg_ FALSE, "overflow", 8)); |
| 1529 | return TRUE; |
| 1530 | } |
| 1531 | |
| 1532 | /* if there's no body, return nil */ |
| 1533 | if (body == 0) |
| 1534 | { |
| 1535 | retval->set_nil(); |
| 1536 | return TRUE; |
| 1537 | } |
| 1538 | |
| 1539 | /* create a data source for the body */ |
| 1540 | CVmStringRefSource *sbody = new CVmStringRefSource(body); |
| 1541 | |
| 1542 | /* for a text content type, get the character mapper */ |
| 1543 | vm_val_t charset; |
| 1544 | int mode = get_charset_map(vmg_ hdrs->find("content-type"), &charset); |
| 1545 | G_stk->push(&charset); |
| 1546 | |
| 1547 | /* create a File object to access the body data source */ |
| 1548 | retval->set_obj(CVmObjFile::create( |
| 1549 | vmg_ FALSE, 0, charset.val.obj, sbody, mode, |
| 1550 | VMOBJFILE_ACCESS_READ, TRUE)); |
| 1551 | |
| 1552 | /* discard the gc protection */ |
| 1553 | G_stk->discard(); |
| 1554 | |
| 1555 | /* handled */ |
| 1556 | return TRUE; |
| 1557 | } |
| 1558 | |
| 1559 | /* |
| 1560 | * look up a standard status code by number |
| 1561 | */ |
| 1562 | static const char *look_up_status(int n, size_t &len) |
| 1563 | { |
| 1564 | /* message table for the standard status codes */ |
| 1565 | static struct |
| 1566 | { |
| 1567 | int n; |
| 1568 | const char *msg; |
| 1569 | } msgs[] = |
| 1570 | { |
| 1571 | { 100, "100 Continue" }, |
| 1572 | { 101, "101 Switching Protocols" }, |
| 1573 | { 102, "102 Processing" }, |
| 1574 | { 200, "200 OK" }, |
| 1575 | { 201, "201 Created" }, |
| 1576 | { 202, "202 Accepted" }, |
| 1577 | { 203, "203 Non-Authoritative Information" }, |
| 1578 | { 204, "204 No Content" }, |
| 1579 | { 205, "205 Reset Content" }, |
| 1580 | { 206, "206 Partial Content" }, |
| 1581 | { 207, "207 Multi-Status" }, |
| 1582 | { 300, "300 Multiple Choices" }, |
| 1583 | { 301, "301 Moved Permanently" }, |
| 1584 | { 302, "302 Found" }, |
| 1585 | { 303, "303 See Other" }, |
| 1586 | { 304, "304 Not Modified" }, |
| 1587 | { 305, "305 Use Proxy" }, |
| 1588 | { 306, "306 Switch Proxy" }, |
| 1589 | { 307, "307 Temporary Redirect" }, |
| 1590 | { 400, "400 Bad Request" }, |
| 1591 | { 401, "401 Unauthorized" }, |
| 1592 | { 402, "402 Payment Required" }, |
| 1593 | { 403, "403 Forbidden" }, |
| 1594 | { 404, "404 Not Found" }, |
| 1595 | { 405, "405 Method Not Allowed" }, |
| 1596 | { 406, "406 Not Acceptable" }, |
| 1597 | { 407, "407 Proxy Authentication Required" }, |
| 1598 | { 408, "408 Request Timeout" }, |
| 1599 | { 409, "409 Conflict" }, |
| 1600 | { 410, "410 Gone" }, |
| 1601 | { 411, "411 Length Required" }, |
| 1602 | { 412, "412 Precondition Failed" }, |
| 1603 | { 413, "413 Request Entity Too Large" }, |
| 1604 | { 414, "414 Request-URI Too Long" }, |
| 1605 | { 415, "415 Unsupported Media Type" }, |
| 1606 | { 416, "416 Requested Range Not Satisfiable" }, |
| 1607 | { 417, "417 Expectation Failed" }, |
| 1608 | { 418, "418 I'm a teapot" }, |
| 1609 | { 421, "421 There are too many connections from your internet address" }, |
| 1610 | { 422, "422 Unprocessable Entity" }, |
| 1611 | { 423, "423 Locked" }, |
| 1612 | { 424, "424 Failed Dependency" }, |
| 1613 | { 425, "425 Unordered Collection" }, |
| 1614 | { 426, "426 Upgrade Required" }, |
| 1615 | { 449, "449 Retry With" }, |
| 1616 | { 450, "450 Blocked by Windows Parental Controls" }, |
| 1617 | { 500, "500 Internal Server Error" }, |
| 1618 | { 501, "501 Not Implemented" }, |
| 1619 | { 502, "502 Bad Gateway" }, |
| 1620 | { 503, "503 Service Unavailable" }, |
| 1621 | { 504, "504 Gateway Timeout" }, |
| 1622 | { 505, "505 HTTP Version Not Supported" }, |
| 1623 | { 506, "506 Variant Also Negotiates" }, |
| 1624 | { 507, "507 Insufficient Storage" }, |
| 1625 | { 509, "509 Bandwidth Limit Exceeded" }, |
| 1626 | { 510, "510 Not Extended" }, |
| 1627 | { 530, "530 User access denied" } |
| 1628 | }; |
| 1629 | |
| 1630 | /* search the list */ |
| 1631 | for (int i = 0 ; i < countof(msgs) ; ++i) |
| 1632 | { |
| 1633 | /* check for a match to the given status code */ |
| 1634 | if (msgs[i].n == n) |
| 1635 | { |
| 1636 | /* it's a match - set the length and return the message */ |
| 1637 | len = strlen(msgs[i].msg); |
| 1638 | return msgs[i].msg; |
| 1639 | } |
| 1640 | } |
| 1641 | |
| 1642 | /* didn't find a match - throw an error */ |
| 1643 | err_throw(VMERR_BAD_VAL_BIF); |
| 1644 | AFTER_ERR_THROW(return 0); |
| 1645 | } |
| 1646 | |
| 1647 | /* |
| 1648 | * look up an HTTP status message by code number |
| 1649 | */ |
| 1650 | static const char *get_status_arg(VMG_ int body_status_code, |
| 1651 | int argn, int argc, size_t &len) |
| 1652 | { |
| 1653 | /* if a body status code was given, it overrides the status argument */ |
| 1654 | if (body_status_code != 0) |
| 1655 | return look_up_status(body_status_code, len); |
| 1656 | |
| 1657 | /* if the argument isn't present, use the default "200 OK" */ |
| 1658 | if (argn >= argc) |
| 1659 | { |
| 1660 | len = 6; |
| 1661 | return "200 OK"; |
| 1662 | } |
| 1663 | |
| 1664 | /* check the type of the argument value */ |
| 1665 | const vm_val_t *argp = G_stk->get(argn); |
| 1666 | const char *status; |
| 1667 | switch (argp->typ) |
| 1668 | { |
| 1669 | case VM_INT: |
| 1670 | /* it's an integer - look up the full message */ |
| 1671 | return look_up_status(argp->val.intval, len); |
| 1672 | |
| 1673 | case VM_NIL: |
| 1674 | /* nil - use the default 200 */ |
| 1675 | len = 6; |
| 1676 | return "200 OK"; |
| 1677 | |
| 1678 | default: |
| 1679 | /* it's not an integer, so it has to be a string */ |
| 1680 | if ((status = argp->get_as_string(vmg0_)) == 0) |
| 1681 | err_throw(VMERR_STRING_VAL_REQD); |
| 1682 | |
| 1683 | /* get the length and return the buffer pointer */ |
| 1684 | len = vmb_get_len(status); |
| 1685 | return status + VMB_LEN; |
| 1686 | } |
| 1687 | } |
| 1688 | |
| 1689 | /* |
| 1690 | * send headers |
| 1691 | */ |
| 1692 | static void send_custom_headers(VMG_ TadsServerThread *t, |
| 1693 | const vm_val_t *headers) |
| 1694 | { |
| 1695 | /* send each header */ |
| 1696 | int cnt = headers->ll_length(vmg0_); |
| 1697 | for (int i = 1 ; i <= cnt ; ++i) |
| 1698 | { |
| 1699 | /* get this list element */ |
| 1700 | vm_val_t ele; |
| 1701 | headers->ll_index(vmg_ &ele, i); |
| 1702 | |
| 1703 | /* it has to be a string */ |
| 1704 | const char *h = ele.get_as_string(vmg0_); |
| 1705 | if (h == 0) |
| 1706 | err_throw(VMERR_STRING_VAL_REQD); |
| 1707 | |
| 1708 | /* send the header string and the CR-LF */ |
| 1709 | if (!t->send(h + VMB_LEN, vmb_get_len(h)) || !t->send("\r\n")) |
| 1710 | throw_net_err(vmg_ "HTTPRequest: error sending headers", |
| 1711 | t->last_error()); |
| 1712 | } |
| 1713 | } |
| 1714 | |
| 1715 | /* error info for HTTPReplySender::send() */ |
| 1716 | struct http_reply_err |
| 1717 | { |
| 1718 | /* OS_Exxx error number (see osifcnet.h) */ |
| 1719 | int sock_err; |
| 1720 | |
| 1721 | /* descriptive message (as a static const string - not allocated) */ |
| 1722 | const char *msg; |
| 1723 | |
| 1724 | /* set the error - returns FALSE status code for caller to return */ |
| 1725 | int set(int err, const char *msg) |
| 1726 | { |
| 1727 | this->sock_err = err; |
| 1728 | this->msg = msg; |
| 1729 | return FALSE; |
| 1730 | } |
| 1731 | |
| 1732 | int set(TadsServerThread *t, const char *msg) |
| 1733 | { return set(t->last_error(), msg); } |
| 1734 | }; |
| 1735 | |
| 1736 | /* |
| 1737 | * Body argument descriptor. This handles the various different source |
| 1738 | * types we handle for body values - strings, ByteArrays, StringBuffers. |
| 1739 | */ |
| 1740 | struct bodyArg |
| 1741 | { |
| 1742 | /* load from the stack */ |
| 1743 | bodyArg(VMG_ int argn) |
| 1744 | { |
| 1745 | /* first clear everything out */ |
| 1746 | none = FALSE; |
| 1747 | str = 0; |
| 1748 | stralo = FALSE; |
| 1749 | strbuf = 0; |
| 1750 | bytarr = 0; |
| 1751 | len = 0; |
| 1752 | status_code = 0; |
| 1753 | init_err = 0; |
| 1754 | datasource = 0; |
| 1755 | gv = 0; |
| 1756 | |
| 1757 | /* get the argument value pointer out of the stack */ |
| 1758 | srcval = *G_stk->get(argn); |
| 1759 | |
| 1760 | /* try the various types */ |
| 1761 | if ((str = srcval.get_as_string(vmg0_)) != 0) |
| 1762 | { |
| 1763 | /* it's a string - get the length and buffer pointer */ |
| 1764 | len = vmb_get_len(str); |
| 1765 | str += VMB_LEN; |
| 1766 | } |
| 1767 | else if (srcval.typ == VM_OBJ |
| 1768 | && CVmObjByteArray::is_byte_array(vmg_ srcval.val.obj)) |
| 1769 | { |
| 1770 | /* it's a byte array */ |
| 1771 | bytarr = (CVmObjByteArray *)vm_objp(vmg_ srcval.val.obj); |
| 1772 | len = bytarr->get_element_count(); |
| 1773 | } |
| 1774 | else if (srcval.typ == VM_OBJ |
| 1775 | && CVmObjStringBuffer::is_string_buffer_obj( |
| 1776 | vmg_ srcval.val.obj)) |
| 1777 | { |
| 1778 | /* it's a string buffer object */ |
| 1779 | strbuf = (CVmObjStringBuffer *)vm_objp(vmg_ srcval.val.obj); |
| 1780 | len = strbuf->utf8_length(); |
| 1781 | } |
| 1782 | else if (srcval.typ == VM_OBJ |
| 1783 | && CVmObjFile::is_file_obj(vmg_ srcval.val.obj)) |
| 1784 | { |
| 1785 | /* it's a file object - cast it */ |
| 1786 | file = (CVmObjFile *)vm_objp(vmg_ srcval.val.obj); |
| 1787 | |
| 1788 | /* note the size */ |
| 1789 | len = file->get_file_size(vmg0_); |
| 1790 | |
| 1791 | /* |
| 1792 | * Get the data source and file spec. Use the file spec as the |
| 1793 | * source object, not the File itself; it's the spec that we |
| 1794 | * want to keep around, since we're directly accessing a data |
| 1795 | * source based on the spec rather than the File. |
| 1796 | */ |
| 1797 | datasource = file->get_datasource(); |
| 1798 | file->get_filespec(&srcval); |
| 1799 | |
| 1800 | /* it's an error if the file isn't open or valid */ |
| 1801 | if (len < 0) |
| 1802 | init_err = VMERR_READ_FILE; |
| 1803 | } |
| 1804 | else if (srcval.typ == VM_INT) |
| 1805 | { |
| 1806 | /* |
| 1807 | * Integer value - treat this as an HTTP status code. The |
| 1808 | * content body is a generated HTML page for the status code. |
| 1809 | */ |
| 1810 | status_code = (int)srcval.val.intval; |
| 1811 | |
| 1812 | /* generate the HTML page */ |
| 1813 | size_t len; |
| 1814 | const char *msg = look_up_status(status_code, len); |
| 1815 | |
| 1816 | /* make sure it's a valid status code */ |
| 1817 | if (len == 0) |
| 1818 | err_throw(VMERR_BAD_VAL_BIF); |
| 1819 | |
| 1820 | /* generate the page */ |
| 1821 | str = t3sprintf_alloc("<html><title>%s</title>" |
| 1822 | "<body><h1>%s</h1></body></html>", |
| 1823 | msg, strchr(msg, ' ') + 1); |
| 1824 | stralo = TRUE; |
| 1825 | } |
| 1826 | else if (srcval.typ == VM_NIL) |
| 1827 | { |
| 1828 | /* no content body */ |
| 1829 | none = TRUE; |
| 1830 | } |
| 1831 | else |
| 1832 | { |
| 1833 | /* it's a type we can't handle */ |
| 1834 | init_err = VMERR_BAD_TYPE_BIF; |
| 1835 | } |
| 1836 | } |
| 1837 | |
| 1838 | ~bodyArg() |
| 1839 | { |
| 1840 | /* free the string, if we allocated it */ |
| 1841 | if (stralo) |
| 1842 | lib_free_str((char *)str); |
| 1843 | } |
| 1844 | |
| 1845 | /* is this a text resource? */ |
| 1846 | int is_text(VMG0_) |
| 1847 | { |
| 1848 | /* check the type */ |
| 1849 | if (str != 0 || strbuf != 0) |
| 1850 | { |
| 1851 | /* strings and string buffers are always sent as text */ |
| 1852 | return TRUE; |
| 1853 | } |
| 1854 | else if (bytarr != 0) |
| 1855 | { |
| 1856 | /* byte arrays are always sent as binary */ |
| 1857 | return FALSE; |
| 1858 | } |
| 1859 | else if (file != 0) |
| 1860 | { |
| 1861 | /* files are sent according to their mode */ |
| 1862 | return file->get_file_mode(vmg0_) == VMOBJFILE_MODE_TEXT; |
| 1863 | } |
| 1864 | else |
| 1865 | { |
| 1866 | /* there shouldn't be anything else, but just in case... */ |
| 1867 | return FALSE; |
| 1868 | } |
| 1869 | } |
| 1870 | |
| 1871 | /* |
| 1872 | * prepare for async use |
| 1873 | */ |
| 1874 | void init_async(VMG0_) |
| 1875 | { |
| 1876 | /* if we have a data source, clone it */ |
| 1877 | if (datasource != 0) |
| 1878 | datasource = datasource->clone(vmg_ "rb"); |
| 1879 | |
| 1880 | /* |
| 1881 | * If we have a string buffer or byte array, make a private copy. |
| 1882 | * These objects aren't designed to be thread-safe, so we can't |
| 1883 | * access them from the background thread. |
| 1884 | */ |
| 1885 | if (strbuf != 0 || bytarr != 0) |
| 1886 | { |
| 1887 | /* allocate the string buffer */ |
| 1888 | char *buf = lib_alloc_str(len); |
| 1889 | |
| 1890 | /* extract the contents into the buffer */ |
| 1891 | int32_t ofs = 0; |
| 1892 | extract(buf, ofs, len); |
| 1893 | |
| 1894 | /* use this as the string buffer */ |
| 1895 | str = buf; |
| 1896 | stralo = TRUE; |
| 1897 | |
| 1898 | /* forget the original object */ |
| 1899 | strbuf = 0; |
| 1900 | bytarr = 0; |
| 1901 | |
| 1902 | /* we don't even need gc protection for the original any more */ |
| 1903 | srcval.set_nil(); |
| 1904 | } |
| 1905 | |
| 1906 | /* |
| 1907 | * if the source value is an object, create a VM global for gc |
| 1908 | * protection as long as the background thread is running |
| 1909 | */ |
| 1910 | if (srcval.typ == VM_OBJ) |
| 1911 | { |
| 1912 | gv = G_obj_table->create_global_var(); |
| 1913 | gv->val = srcval; |
| 1914 | } |
| 1915 | } |
| 1916 | |
| 1917 | /* clean up from async use */ |
| 1918 | void term_async(VMG0_) |
| 1919 | { |
| 1920 | /* delete our data source */ |
| 1921 | if (datasource != 0) |
| 1922 | delete datasource; |
| 1923 | |
| 1924 | /* delete our VM global */ |
| 1925 | if (gv != 0) |
| 1926 | G_obj_table->delete_global_var(gv); |
| 1927 | } |
| 1928 | |
| 1929 | /* |
| 1930 | * Send the body data |
| 1931 | */ |
| 1932 | int send(TadsServerThread *t, http_reply_err *err) |
| 1933 | { |
| 1934 | /* send the data according to the source type */ |
| 1935 | if (str != 0) |
| 1936 | { |
| 1937 | /* send the string's contents */ |
| 1938 | if (!t->send(str, (size_t)len)) |
| 1939 | return err->set(t, "error sending content body"); |
| 1940 | } |
| 1941 | else if (bytarr != 0 || strbuf != 0) |
| 1942 | { |
| 1943 | /* send the byte array or string buffer contents */ |
| 1944 | char buf[1024]; |
| 1945 | int32_t ofs = 0; |
| 1946 | for (;;) |
| 1947 | { |
| 1948 | /* get the next chunk */ |
| 1949 | int32_t len = sizeof(buf); |
| 1950 | const char *p = extract(buf, ofs, len); |
| 1951 | |
| 1952 | /* if we're out of material, we're done */ |
| 1953 | if (len == 0) |
| 1954 | break; |
| 1955 | |
| 1956 | /* send this chunk */ |
| 1957 | if (!t->send(p, (size_t)len)) |
| 1958 | return err->set(t, "error sending content body"); |
| 1959 | } |
| 1960 | } |
| 1961 | else if (datasource != 0) |
| 1962 | { |
| 1963 | /* seek to the start of the file */ |
| 1964 | datasource->seek(0, OSFSK_SET); |
| 1965 | |
| 1966 | /* copy the file to the socket */ |
| 1967 | for (;;) |
| 1968 | { |
| 1969 | /* get the next chunk */ |
| 1970 | char buf[1024]; |
| 1971 | int32_t len = sizeof(buf); |
| 1972 | len = datasource->readc(buf, len); |
| 1973 | |
| 1974 | /* if we're out of material, we're done */ |
| 1975 | if (len == 0) |
| 1976 | break; |
| 1977 | |
| 1978 | /* send this chunk */ |
| 1979 | if (!t->send(buf, (size_t)len)) |
| 1980 | return err->set(t, "error sending content body"); |
| 1981 | } |
| 1982 | } |
| 1983 | |
| 1984 | /* success */ |
| 1985 | return TRUE; |
| 1986 | } |
| 1987 | |
| 1988 | /* |
| 1989 | * Extract a portion of the contents. If possible, we'll simply return |
| 1990 | * a direct pointer to the buffer containing the data; if this isn't |
| 1991 | * possible, we'll copy the data to the caller's buffer. |
| 1992 | * |
| 1993 | * On input, 'ofs' is the starting offset of the extraction. The |
| 1994 | * meaning varies according to the underlying data type, so this should |
| 1995 | * always be either 0 (for the start of the string) or the output value |
| 1996 | * of a previous call to this routine. 'ofs' is an in-out variable: on |
| 1997 | * return, we've updated it to reflect the starting offset of the next |
| 1998 | * character after the chunk we extract here. |
| 1999 | * |
| 2000 | * 'len' is also an in-out variable. On input, this is the size in |
| 2001 | * bytes of the buffer. On output, it reflects the actual number of |
| 2002 | * bytes copied to the buffer. This might be smaller than the |
| 2003 | * requested size (never larger), because (a) we won't copy past the |
| 2004 | * end of the data source, and (b) some data sources will stop short of |
| 2005 | * the end of the buffer if filling the buffer exactly would require |
| 2006 | * copying a fractional utf-8 character. Note, however, that we make |
| 2007 | * no guarantee that a fractional character won't be copied: some data |
| 2008 | * sources won't do this, but others will. |
| 2009 | */ |
| 2010 | const char *extract(char *buf, int32_t &ofs, int32_t &len) |
| 2011 | { |
| 2012 | /* assume we'll have to copy into the caller's buffer */ |
| 2013 | const char *ret = buf; |
| 2014 | |
| 2015 | /* determine what to do based on the source type */ |
| 2016 | if (str != 0) |
| 2017 | { |
| 2018 | /* limit the length to the actual source length */ |
| 2019 | if (len > this->len) |
| 2020 | len = this->len; |
| 2021 | |
| 2022 | /* get a pointer to the requested substring */ |
| 2023 | ret = str + ofs; |
| 2024 | |
| 2025 | /* move the offset past the requested portion */ |
| 2026 | ofs += len; |
| 2027 | } |
| 2028 | else if (strbuf != 0) |
| 2029 | { |
| 2030 | /* |
| 2031 | * for a string buffer, we have to translate to utf8 - this |
| 2032 | * updates 'idx' and 'len' per our interface |
| 2033 | */ |
| 2034 | strbuf->to_utf8(buf, ofs, len); |
| 2035 | } |
| 2036 | else if (bytarr != 0) |
| 2037 | { |
| 2038 | /* |
| 2039 | * It's a byte array - copy bytes to the caller's buffer. Note |
| 2040 | * that we use 0-based offsets, and the byte array uses 1-based |
| 2041 | * offsets, so adjust accordingly. |
| 2042 | */ |
| 2043 | len = bytarr->copy_to_buf((unsigned char *)buf, ofs + 1, len); |
| 2044 | |
| 2045 | /* adjust the offset for the actual copied size */ |
| 2046 | ofs += len; |
| 2047 | } |
| 2048 | else if (file != 0) |
| 2049 | { |
| 2050 | /* |
| 2051 | * It's a File object - read bytes from the file into the |
| 2052 | * caller's buffer. |
| 2053 | */ |
| 2054 | datasource->seek(ofs, OSFSK_SET); |
| 2055 | len = datasource->readc(buf, len); |
| 2056 | |
| 2057 | /* adjust the offset for the actual copied size */ |
| 2058 | ofs += len; |
| 2059 | } |
| 2060 | else |
| 2061 | { |
| 2062 | /* didn't read anything */ |
| 2063 | len = 0; |
| 2064 | } |
| 2065 | |
| 2066 | /* return the result pointer */ |
| 2067 | return ret; |
| 2068 | } |
| 2069 | |
| 2070 | /* true -> no content body */ |
| 2071 | int none; |
| 2072 | |
| 2073 | /* construction error code, if applicable */ |
| 2074 | int init_err; |
| 2075 | |
| 2076 | /* if it's a string, the string */ |
| 2077 | const char *str; |
| 2078 | |
| 2079 | /* flag: we allocated the string */ |
| 2080 | int stralo; |
| 2081 | |
| 2082 | /* if it's a string buffer, the string buffer */ |
| 2083 | CVmObjStringBuffer *strbuf; |
| 2084 | |
| 2085 | /* if it's a byte array, the byte array */ |
| 2086 | CVmObjByteArray *bytarr; |
| 2087 | |
| 2088 | /* if it's a File object, the File object and data source */ |
| 2089 | CVmObjFile *file; |
| 2090 | CVmDataSource *datasource; |
| 2091 | |
| 2092 | /* source value */ |
| 2093 | vm_val_t srcval; |
| 2094 | |
| 2095 | /* if it's an HTTP status code, the status code; otherwise 0 */ |
| 2096 | int status_code; |
| 2097 | |
| 2098 | /* length in bytes of the underlying data source */ |
| 2099 | int32_t len; |
| 2100 | |
| 2101 | /* VM global, for async use */ |
| 2102 | vm_globalvar_t *gv; |
| 2103 | }; |
| 2104 | |
| 2105 | /* |
| 2106 | * Compare two strings, skipping spaces in the source string. |
| 2107 | */ |
| 2108 | static int eq_skip_sp(const char *src, size_t len, const char *ref) |
| 2109 | { |
| 2110 | /* skip leading spaces */ |
| 2111 | utf8_ptr srcp((char *)src); |
| 2112 | for ( ; len != 0 && is_space(srcp.getch()) ; srcp.inc(&len)) ; |
| 2113 | |
| 2114 | /* keep going until we run out of one string or the other */ |
| 2115 | for (utf8_ptr srcp((char *)src) ; len != 0 && *ref != '\0' ; ++ref) |
| 2116 | { |
| 2117 | /* |
| 2118 | * if this source character is a space, match any run of |
| 2119 | * whitespace; otherwise we must match exactly |
| 2120 | */ |
| 2121 | wchar_t c = to_lower(srcp.getch()); |
| 2122 | if (*ref == ' ' && is_space(c)) |
| 2123 | { |
| 2124 | /* |
| 2125 | * we have a whitespace match - skip any additional whitespace |
| 2126 | * in the source string |
| 2127 | */ |
| 2128 | for (srcp.inc(&len) ; len != 0 && is_space(srcp.getch()) ; |
| 2129 | srcp.inc(&len)) ; |
| 2130 | } |
| 2131 | else if (*ref == c) |
| 2132 | { |
| 2133 | /* we have a match - skip one source character */ |
| 2134 | srcp.inc(&len); |
| 2135 | } |
| 2136 | else |
| 2137 | { |
| 2138 | /* this character doesn't match, so the whole match fails */ |
| 2139 | return FALSE; |
| 2140 | } |
| 2141 | } |
| 2142 | |
| 2143 | /* |
| 2144 | * if we ran out of the reference string, we have a match; otherwise we |
| 2145 | * must have run out of the source string first, in which case we don't |
| 2146 | * match because we have additional unmatched reference characters |
| 2147 | */ |
| 2148 | return (*ref == '\0'); |
| 2149 | } |
| 2150 | |
| 2151 | /* |
| 2152 | * send the cookie headers |
| 2153 | */ |
| 2154 | static void send_cookies(VMG_ TadsServerThread *t, vm_httpreq_cookie *c) |
| 2155 | { |
| 2156 | /* send each cookie in the list */ |
| 2157 | for ( ; c != 0 ; c = c->nxt) |
| 2158 | { |
| 2159 | if (!c->send(t)) |
| 2160 | { |
| 2161 | /* failed - throw an error */ |
| 2162 | throw_net_err(vmg_ "error sending cookies", t->last_error()); |
| 2163 | } |
| 2164 | } |
| 2165 | } |
| 2166 | |
| 2167 | /* |
| 2168 | * send a reply |
| 2169 | */ |
| 2170 | int CVmObjHTTPRequest::getp_sendReply( |
| 2171 | VMG_ vm_obj_id_t self, vm_val_t *retval, uint *oargc) |
| 2172 | { |
| 2173 | return common_sendReply(vmg_ self, retval, oargc, TRUE); |
| 2174 | } |
| 2175 | |
| 2176 | /* |
| 2177 | * send a reply asynchronously |
| 2178 | */ |
| 2179 | int CVmObjHTTPRequest::getp_sendReplyAsync( |
| 2180 | VMG_ vm_obj_id_t self, vm_val_t *retval, uint *oargc) |
| 2181 | { |
| 2182 | return common_sendReply(vmg_ self, retval, oargc, FALSE); |
| 2183 | } |
| 2184 | |
| 2185 | /* reply sender thread */ |
| 2186 | class HTTPReplySenderThread: public OS_Thread |
| 2187 | { |
| 2188 | public: |
| 2189 | HTTPReplySenderThread(class HTTPReplySender *sender); |
| 2190 | ~HTTPReplySenderThread(); |
| 2191 | |
| 2192 | virtual void thread_main(); |
| 2193 | |
| 2194 | class HTTPReplySender *sender; |
| 2195 | }; |
| 2196 | |
| 2197 | /* custom header list */ |
| 2198 | struct http_header |
| 2199 | { |
| 2200 | static http_header *create(VMG_ const vm_val_t *lstval) |
| 2201 | { |
| 2202 | /* start with an empty list */ |
| 2203 | http_header *head = 0, **tailp = &head; |
| 2204 | |
| 2205 | /* parse the value list */ |
| 2206 | int cnt = lstval->ll_length(vmg0_); |
| 2207 | for (int i = 1 ; i <= cnt ; ++i) |
| 2208 | { |
| 2209 | /* get this list element */ |
| 2210 | vm_val_t ele; |
| 2211 | lstval->ll_index(vmg_ &ele, i); |
| 2212 | |
| 2213 | /* it has to be a string */ |
| 2214 | const char *h = ele.get_as_string(vmg0_); |
| 2215 | if (h == 0) |
| 2216 | err_throw(VMERR_STRING_VAL_REQD); |
| 2217 | |
| 2218 | /* add a new header */ |
| 2219 | *tailp = new http_header(h + VMB_LEN, vmb_get_len(h)); |
| 2220 | tailp = &(*tailp)->nxt; |
| 2221 | } |
| 2222 | |
| 2223 | /* return the list head */ |
| 2224 | return head; |
| 2225 | } |
| 2226 | |
| 2227 | http_header(const char *str, size_t len) |
| 2228 | { |
| 2229 | /* allocate the string, with two extra bytes for the CR-LF */ |
| 2230 | this->len = len + 2; |
| 2231 | this->str = lib_alloc_str(this->len); |
| 2232 | |
| 2233 | /* copy the string */ |
| 2234 | memcpy(this->str, str, len); |
| 2235 | |
| 2236 | /* add the CR-LF */ |
| 2237 | this->str[len] = '\r'; |
| 2238 | this->str[len+1] = '\n'; |
| 2239 | |
| 2240 | /* we're not in a list yet */ |
| 2241 | nxt = 0; |
| 2242 | } |
| 2243 | |
| 2244 | ~http_header() |
| 2245 | { |
| 2246 | lib_free_str(str); |
| 2247 | if (nxt != 0) |
| 2248 | delete nxt; |
| 2249 | } |
| 2250 | |
| 2251 | /* string and length */ |
| 2252 | char *str; |
| 2253 | size_t len; |
| 2254 | |
| 2255 | /* next in list */ |
| 2256 | http_header *nxt; |
| 2257 | }; |
| 2258 | |
| 2259 | /* |
| 2260 | * Asynchronous HTTP reply result event |
| 2261 | */ |
| 2262 | class TadsHttpReplyResult: public TadsEventMessage |
| 2263 | { |
| 2264 | public: |
| 2265 | TadsHttpReplyResult(VMG_ TadsHttpRequest *req, vm_globalvar_t *reqvar, |
| 2266 | bodyArg *body, int sock_err, const char *msg) |
| 2267 | : TadsEventMessage(0) |
| 2268 | { |
| 2269 | /* save the VM globals for use in the main thread */ |
| 2270 | this->vmg = VMGLOB_ADDR; |
| 2271 | |
| 2272 | /* remember our parameters */ |
| 2273 | this->req = req; |
| 2274 | this->reqvar = reqvar; |
| 2275 | this->body = body; |
| 2276 | this->sock_err = sock_err; |
| 2277 | this->msg = lib_copy_str(msg); |
| 2278 | } |
| 2279 | |
| 2280 | ~TadsHttpReplyResult() |
| 2281 | { |
| 2282 | /* establish global variable access */ |
| 2283 | VMGLOB_PTR(vmg); |
| 2284 | |
| 2285 | /* done with the request object */ |
| 2286 | if (req != 0) |
| 2287 | req->release_ref(); |
| 2288 | |
| 2289 | /* done with the request object ID global */ |
| 2290 | if (reqvar != 0) |
| 2291 | G_obj_table->delete_global_var(reqvar); |
| 2292 | |
| 2293 | /* done with 'body' - clean up from async mode and delete it */ |
| 2294 | if (body != 0) |
| 2295 | { |
| 2296 | body->term_async(vmg0_); |
| 2297 | delete body; |
| 2298 | } |
| 2299 | |
| 2300 | /* free the message text */ |
| 2301 | lib_free_str(msg); |
| 2302 | } |
| 2303 | |
| 2304 | /* prepare a bytecode event object when we're read from the queue */ |
| 2305 | virtual vm_obj_id_t prep_event_obj(VMG_ int *argc, int *evt_type) |
| 2306 | { |
| 2307 | /* push the socket error */ |
| 2308 | G_stk->push()->set_int(sock_err); |
| 2309 | |
| 2310 | /* push the result message */ |
| 2311 | G_stk->push_string(vmg_ msg, msg != 0 ? strlen(msg) : 0); |
| 2312 | |
| 2313 | /* push the request object ID */ |
| 2314 | if (reqvar != 0) |
| 2315 | G_stk->push(&reqvar->val); |
| 2316 | else |
| 2317 | G_stk->push()->set_nil(); |
| 2318 | |
| 2319 | /* relay our added argument count to the caller */ |
| 2320 | *argc = 3; |
| 2321 | |
| 2322 | /* set the event type to NetEvReplyDone (6 - see include/tadsnet.h) */ |
| 2323 | *evt_type = 6; |
| 2324 | |
| 2325 | /* the event subclass is NetReplyDoneEvent */ |
| 2326 | return G_predef->net_reply_done_event; |
| 2327 | } |
| 2328 | |
| 2329 | /* VM globals, for use in main thread only */ |
| 2330 | vm_globals *vmg; |
| 2331 | |
| 2332 | /* the request object for the request we replied to */ |
| 2333 | TadsHttpRequest *req; |
| 2334 | |
| 2335 | /* VM global for the request object value */ |
| 2336 | vm_globalvar_t *reqvar; |
| 2337 | |
| 2338 | /* the content body of the reply */ |
| 2339 | bodyArg *body; |
| 2340 | |
| 2341 | /* socket error from reply data transfer */ |
| 2342 | int sock_err; |
| 2343 | |
| 2344 | /* result message text */ |
| 2345 | char *msg; |
| 2346 | }; |
| 2347 | |
| 2348 | |
| 2349 | /* |
| 2350 | * Reply sender object. This encapsulates a reply's data and the code to |
| 2351 | * send the reply. This can be used to send a reply synchronously or |
| 2352 | * asynchronously. |
| 2353 | */ |
| 2354 | class HTTPReplySender: public CVmRefCntObj |
| 2355 | { |
| 2356 | friend class HTTPReplySenderThread; |
| 2357 | |
| 2358 | public: |
| 2359 | HTTPReplySender() |
| 2360 | { |
| 2361 | vmg = 0; |
| 2362 | queue = 0; |
| 2363 | reqid = VM_INVALID_OBJ; |
| 2364 | req = 0; |
| 2365 | reqvar = 0; |
| 2366 | status = 0; |
| 2367 | status_len = 0; |
| 2368 | headers = 0; |
| 2369 | body = 0; |
| 2370 | cont_type = 0; |
| 2371 | cont_type_len = 0; |
| 2372 | cookies = 0; |
| 2373 | async = FALSE; |
| 2374 | } |
| 2375 | |
| 2376 | void set_params(VMG_ vm_obj_id_t reqid, TadsHttpRequest *req, |
| 2377 | const char *status, size_t status_len, |
| 2378 | const vm_val_t *headers, bodyArg *body, |
| 2379 | const char *cont_type, size_t cont_type_len, |
| 2380 | vm_httpreq_cookie *cookies) |
| 2381 | { |
| 2382 | /* |
| 2383 | * Save the values. For reference types (string buffers, etc), |
| 2384 | * just keep pointers to the originals; for synchronous replies, |
| 2385 | * the caller will block on the send, so these will stay around for |
| 2386 | * the send. For asynchronous (threaded) replies, we'll make |
| 2387 | * private copies when we start the new thread. |
| 2388 | */ |
| 2389 | this->reqid = reqid; |
| 2390 | this->req = req; |
| 2391 | this->status = status; |
| 2392 | this->status_len = status_len; |
| 2393 | this->headers = 0; |
| 2394 | this->body = body; |
| 2395 | this->cont_type = cont_type; |
| 2396 | this->cont_type_len = cont_type_len; |
| 2397 | this->cookies = cookies; |
| 2398 | |
| 2399 | /* parse the headers list */ |
| 2400 | if (headers != 0) |
| 2401 | this->headers = http_header::create(vmg_ headers); |
| 2402 | |
| 2403 | /* add a reference on the request object */ |
| 2404 | req->add_ref(); |
| 2405 | } |
| 2406 | |
| 2407 | ~HTTPReplySender() |
| 2408 | { |
| 2409 | /* if we're in async mode, delete our private parameter data */ |
| 2410 | if (async) |
| 2411 | { |
| 2412 | lib_free_str((char *)status); |
| 2413 | lib_free_str((char *)cont_type); |
| 2414 | if (cookies != 0) |
| 2415 | delete cookies; |
| 2416 | } |
| 2417 | |
| 2418 | /* delete the headers (we always copy these) */ |
| 2419 | if (headers != 0) |
| 2420 | delete headers; |
| 2421 | |
| 2422 | /* release the net event queue */ |
| 2423 | if (queue != 0) |
| 2424 | queue->release_ref(); |
| 2425 | |
| 2426 | /* done with the request object and VM global */ |
| 2427 | if (req != 0) |
| 2428 | req->release_ref(); |
| 2429 | if (reqvar != 0) |
| 2430 | { |
| 2431 | VMGLOB_PTR(vmg); |
| 2432 | G_obj_table->delete_global_var(reqvar); |
| 2433 | } |
| 2434 | |
| 2435 | /* done with the body object */ |
| 2436 | if (body != 0) |
| 2437 | delete body; |
| 2438 | } |
| 2439 | |
| 2440 | /* |
| 2441 | * send the reply; returns true on success, false on failure (and fills |
| 2442 | * in '*err' with error information on failure) |
| 2443 | */ |
| 2444 | int send(http_reply_err *err) |
| 2445 | { |
| 2446 | /* presume success */ |
| 2447 | int ok = TRUE; |
| 2448 | |
| 2449 | /* |
| 2450 | * We've gathered all of the information, so send the reply. Start |
| 2451 | * with the status code. |
| 2452 | */ |
| 2453 | TadsServerThread *t = req->thread; |
| 2454 | if (!t->send("HTTP/1.1 ") |
| 2455 | || !t->send(status, status_len) |
| 2456 | || !t->send("\r\n")) |
| 2457 | ok = err->set(t, "error sending status"); |
| 2458 | |
| 2459 | /* send the custom headers, if any */ |
| 2460 | if (ok && headers != 0) |
| 2461 | { |
| 2462 | for (http_header *h = headers ; ok && h != 0 ; h = h->nxt) |
| 2463 | { |
| 2464 | if (!t->send(h->str, h->len)) |
| 2465 | ok = err->set(t, "error sending headers"); |
| 2466 | } |
| 2467 | } |
| 2468 | |
| 2469 | /* if there's a body, send Content-Type and Content-Length headers */ |
| 2470 | if (ok && !body->none) |
| 2471 | { |
| 2472 | /* if it's a "text/" type, add a utf-8 "charset" parameter */ |
| 2473 | const char *charset = ""; |
| 2474 | if (cont_type_len > 5 && memicmp(cont_type, "text/", 5) == 0) |
| 2475 | charset = "; charset=utf-8"; |
| 2476 | |
| 2477 | /* send the standard headers: Content-Type, Content-Length */ |
| 2478 | char hbuf[256]; |
| 2479 | t3sprintf(hbuf, sizeof(hbuf), |
| 2480 | "Content-Type: %.*s%s\r\n" |
| 2481 | "Content-Length: %lu\r\n", |
| 2482 | (int)cont_type_len, cont_type, charset, |
| 2483 | (ulong)body->len); |
| 2484 | if (!t->send(hbuf)) |
| 2485 | ok = err->set(t, "error sending headers"); |
| 2486 | } |
| 2487 | |
| 2488 | /* send the cookies */ |
| 2489 | for (vm_httpreq_cookie *c = cookies ; ok && c != 0 ; c = c->nxt) |
| 2490 | { |
| 2491 | if (!c->send(t)) |
| 2492 | ok = err->set(t, "error sending cookies"); |
| 2493 | } |
| 2494 | |
| 2495 | /* send the blank line at the end of the headers */ |
| 2496 | if (ok && !t->send("\r\n")) |
| 2497 | ok = err->set(t, "error sending headers"); |
| 2498 | |
| 2499 | /* send the reply body */ |
| 2500 | if (ok && !body->send(t, err)) |
| 2501 | ok = FALSE; |
| 2502 | |
| 2503 | /* mark the request as completed */ |
| 2504 | req->complete(); |
| 2505 | |
| 2506 | /* return the status indication */ |
| 2507 | return ok; |
| 2508 | } |
| 2509 | |
| 2510 | /* reply error codes */ |
| 2511 | static const int ErrThread = -8; /* thread launch failed */ |
| 2512 | |
| 2513 | /* start a thread to send the reply asynchronously */ |
| 2514 | void start_thread(VMG0_) |
| 2515 | { |
| 2516 | /* save the globals for use in the 'done' event */ |
| 2517 | vmg = VMGLOB_ADDR; |
| 2518 | |
| 2519 | /* remember the net event queue, and record our reference on it */ |
| 2520 | if ((queue = G_net_queue) != 0) |
| 2521 | queue->add_ref(); |
| 2522 | |
| 2523 | /* |
| 2524 | * remove the original parametres from our member variables before |
| 2525 | * we set async mode, in case we throw an error in the course of |
| 2526 | * making copies - we wouldn't want to delete the originals, as |
| 2527 | * those are owned by the main thread |
| 2528 | */ |
| 2529 | const char *ostatus = status; status = 0; |
| 2530 | const char *ocont_type = cont_type; cont_type = 0; |
| 2531 | vm_httpreq_cookie *ocookies = cookies; cookies = 0; |
| 2532 | |
| 2533 | /* note that we're now in async mode */ |
| 2534 | async = TRUE; |
| 2535 | |
| 2536 | /* install copies in our member variables */ |
| 2537 | status = lib_copy_str(ostatus, status_len); |
| 2538 | cont_type = lib_copy_str(ocont_type, cont_type_len); |
| 2539 | if (ocookies != 0) |
| 2540 | cookies = ocookies->clone(); |
| 2541 | |
| 2542 | /* initialize async mode in the body object */ |
| 2543 | body->init_async(vmg0_); |
| 2544 | |
| 2545 | /* |
| 2546 | * create a global variable for the request object ID, to keep it |
| 2547 | * around until the request is completed |
| 2548 | */ |
| 2549 | reqvar = G_obj_table->create_global_var(); |
| 2550 | reqvar->val.set_obj(reqid); |
| 2551 | |
| 2552 | /* create and launch a thread to handle the data transfer */ |
| 2553 | HTTPReplySenderThread *t = new HTTPReplySenderThread(this); |
| 2554 | if (!t->launch()) |
| 2555 | { |
| 2556 | /* |
| 2557 | * the thread failed - post a 'finished' event with an error, |
| 2558 | * since the thread can't do this on its own if it never runs |
| 2559 | */ |
| 2560 | post_done_event(0, "unable to launch thread"); |
| 2561 | } |
| 2562 | |
| 2563 | /* we're done with the thread */ |
| 2564 | t->release_ref(); |
| 2565 | } |
| 2566 | |
| 2567 | protected: |
| 2568 | /* handle the main thread action */ |
| 2569 | void thread_main() |
| 2570 | { |
| 2571 | /* send the reply */ |
| 2572 | http_reply_err err; |
| 2573 | if (send(&err)) |
| 2574 | { |
| 2575 | /* post the successful 'finished' event */ |
| 2576 | post_done_event(0, 0); |
| 2577 | } |
| 2578 | else |
| 2579 | { |
| 2580 | /* post the error */ |
| 2581 | post_done_event(err.sock_err, err.msg); |
| 2582 | } |
| 2583 | } |
| 2584 | |
| 2585 | /* post the "finished" event for an asynchronous reply */ |
| 2586 | void post_done_event(int sock_err, const char *msg) |
| 2587 | { |
| 2588 | /* establish the global context */ |
| 2589 | VMGLOB_PTR(vmg); |
| 2590 | |
| 2591 | /* create the result event */ |
| 2592 | TadsHttpReplyResult *evt = new TadsHttpReplyResult( |
| 2593 | vmg_ req, reqvar, body, sock_err, msg); |
| 2594 | |
| 2595 | /* queue the event (this transfers ownership to the queue) */ |
| 2596 | queue->post(evt); |
| 2597 | |
| 2598 | /* forget the items that the event object took ownership of */ |
| 2599 | req = 0; |
| 2600 | body = 0; |
| 2601 | reqvar = 0; |
| 2602 | } |
| 2603 | |
| 2604 | /* |
| 2605 | * VM globals (we need these for the "finished" event object) - note |
| 2606 | * that the background thread isn't allowed to access VM globals since |
| 2607 | * they're not thread safe and thus are restricted to the main thread |
| 2608 | */ |
| 2609 | vm_globals *vmg; |
| 2610 | |
| 2611 | /* network event queue */ |
| 2612 | TadsMessageQueue *queue; |
| 2613 | |
| 2614 | /* request object ID (an HTTPRequest object) */ |
| 2615 | vm_obj_id_t reqid; |
| 2616 | vm_globalvar_t *reqvar; |
| 2617 | |
| 2618 | /* the underlying network request object */ |
| 2619 | TadsHttpRequest *req; |
| 2620 | |
| 2621 | /* status string */ |
| 2622 | const char *status; |
| 2623 | size_t status_len; |
| 2624 | |
| 2625 | /* headers */ |
| 2626 | http_header *headers; |
| 2627 | |
| 2628 | /* content body */ |
| 2629 | bodyArg *body; |
| 2630 | |
| 2631 | /* content type string */ |
| 2632 | const char *cont_type; |
| 2633 | size_t cont_type_len; |
| 2634 | |
| 2635 | /* cookie list head */ |
| 2636 | vm_httpreq_cookie *cookies; |
| 2637 | |
| 2638 | /* |
| 2639 | * Are we sending the reply asynchronously? If this is true, the |
| 2640 | * parameters that point to memory buffers are private copies. |
| 2641 | */ |
| 2642 | int async; |
| 2643 | }; |
| 2644 | |
| 2645 | HTTPReplySenderThread::HTTPReplySenderThread(class HTTPReplySender *sender) |
| 2646 | { |
| 2647 | (this->sender = sender)->add_ref(); |
| 2648 | } |
| 2649 | |
| 2650 | HTTPReplySenderThread::~HTTPReplySenderThread() |
| 2651 | { |
| 2652 | sender->release_ref(); |
| 2653 | } |
| 2654 | |
| 2655 | void HTTPReplySenderThread::thread_main() |
| 2656 | { |
| 2657 | sender->thread_main(); |
| 2658 | } |
| 2659 | |
| 2660 | /* |
| 2661 | * Common handler for sendReply and sendReplyAsync. |
| 2662 | */ |
| 2663 | int CVmObjHTTPRequest::common_sendReply( |
| 2664 | VMG_ vm_obj_id_t self, vm_val_t *retval, uint *oargc, int wait) |
| 2665 | { |
| 2666 | uint argc = (oargc != 0 ? *oargc : 0); |
| 2667 | static CVmNativeCodeDesc desc(1, 3); |
| 2668 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 2669 | return TRUE; |
| 2670 | |
| 2671 | /* get the request */ |
| 2672 | TadsHttpRequest *req = get_ext()->req; |
| 2673 | |
| 2674 | /* if the request is already completed, this is an error */ |
| 2675 | if (req->completed) |
| 2676 | throw_net_err(vmg_ "request already completed", 0); |
| 2677 | |
| 2678 | /* get the 'body' argument (leave it on the stack for gc protection) */ |
| 2679 | bodyArg *body = new bodyArg(vmg_ 0); |
| 2680 | |
| 2681 | /* no reply sender yet */ |
| 2682 | HTTPReplySender *sender = 0; |
| 2683 | |
| 2684 | err_try |
| 2685 | { |
| 2686 | /* get the content type, if present */ |
| 2687 | const char *cont_type = 0; |
| 2688 | size_t cont_type_len = 0; |
| 2689 | if (body->init_err != 0) |
| 2690 | { |
| 2691 | err_throw(body->init_err); |
| 2692 | } |
| 2693 | else if (body->status_code != 0) |
| 2694 | { |
| 2695 | /* we're using a generated HTML reply, so it's always text/html */ |
| 2696 | cont_type = "text/html"; |
| 2697 | cont_type_len = 9; |
| 2698 | } |
| 2699 | else if (body->none) |
| 2700 | { |
| 2701 | /* no body -> no content type */ |
| 2702 | cont_type = 0; |
| 2703 | cont_type_len = 0; |
| 2704 | } |
| 2705 | else if (argc >= 2 && G_stk->get(1)->typ != VM_NIL) |
| 2706 | { |
| 2707 | /* retrieve the content type - this must be a string */ |
| 2708 | cont_type = G_stk->get(1)->get_as_string(vmg0_); |
| 2709 | if (cont_type == 0) |
| 2710 | err_throw(VMERR_STRING_VAL_REQD); |
| 2711 | |
| 2712 | /* get the length and buffer pointer */ |
| 2713 | cont_type_len = vmb_get_len(cont_type); |
| 2714 | cont_type += VMB_LEN; |
| 2715 | } |
| 2716 | else |
| 2717 | { |
| 2718 | /* |
| 2719 | * There's no content type argument, so we need to infer the |
| 2720 | * type from the 'body' argument. First, extract the initial |
| 2721 | * section of the content to check for common signatures. |
| 2722 | */ |
| 2723 | char buf[512]; |
| 2724 | int32_t ofs = 0, len = sizeof(buf); |
| 2725 | const char *bufp = body->extract(buf, ofs, len); |
| 2726 | |
| 2727 | /* check to see if the body is text or binary */ |
| 2728 | if (body->is_text(vmg0_)) |
| 2729 | { |
| 2730 | /* |
| 2731 | * it's text data, so check for tell-tale signs of HTML and |
| 2732 | * XML, after skipping leading whitespace and HTML-style |
| 2733 | * comments |
| 2734 | */ |
| 2735 | utf8_ptr p((char *)bufp); |
| 2736 | size_t rem = (size_t)len; |
| 2737 | while (rem != 0) |
| 2738 | { |
| 2739 | /* if we're at a comment starter, skip the comment */ |
| 2740 | if (rem >= 4 && memcmp(p.getptr(), "<!--", 4) == 0) |
| 2741 | { |
| 2742 | /* skip to the closing sequence */ |
| 2743 | for ( ; rem != 0 ; p.inc(&rem)) |
| 2744 | { |
| 2745 | if (rem >= 3 && memcmp(p.getptr(), "-->", 3) == 0) |
| 2746 | { |
| 2747 | /* skip it and stop looking */ |
| 2748 | p.inc(&rem); |
| 2749 | p.inc(&rem); |
| 2750 | p.inc(&rem); |
| 2751 | break; |
| 2752 | } |
| 2753 | } |
| 2754 | |
| 2755 | /* continue scanning */ |
| 2756 | continue; |
| 2757 | } |
| 2758 | |
| 2759 | /* if we're at any whitespace character, just skip it */ |
| 2760 | if (t3_is_whitespace(p.getch())) |
| 2761 | { |
| 2762 | p.inc(&rem); |
| 2763 | continue; |
| 2764 | } |
| 2765 | |
| 2766 | /* otherwise stop scanning */ |
| 2767 | break; |
| 2768 | } |
| 2769 | |
| 2770 | /* check for <HTML or <?XML prefixes */ |
| 2771 | if ((rem > 5 && memicmp(p.getptr(), "<html", 5) == 0) |
| 2772 | || eq_skip_sp(p.getptr(), rem, "<!doctype html ")) |
| 2773 | { |
| 2774 | /* it looks like HTML */ |
| 2775 | cont_type = "text/html"; |
| 2776 | } |
| 2777 | else if (rem > 5 && memicmp(p.getptr(), "<?xml", 5) == 0) |
| 2778 | { |
| 2779 | /* it looks like XML */ |
| 2780 | cont_type = "text/xml"; |
| 2781 | } |
| 2782 | else |
| 2783 | { |
| 2784 | /* it doesn't look like HTML or XML, so use plain text */ |
| 2785 | cont_type = "text/plain"; |
| 2786 | } |
| 2787 | } |
| 2788 | else |
| 2789 | { |
| 2790 | /* |
| 2791 | * Treat it as binary data. Check the first few bytes to |
| 2792 | * see if the file signature matches a known media type. |
| 2793 | */ |
| 2794 | if (len > 10 |
| 2795 | && (unsigned char)bufp[0] == 0xff |
| 2796 | && (unsigned char)bufp[1] == 0xd8 |
| 2797 | && memcmp(bufp+6, "JFIF", 4) == 0) |
| 2798 | { |
| 2799 | /* it's a JPEG image */ |
| 2800 | cont_type = "image/jpeg"; |
| 2801 | } |
| 2802 | else if (len > 6 |
| 2803 | && (memcmp(bufp, "GIF87a", 6) == 0 |
| 2804 | || memcmp(bufp, "GIF89a", 6) == 0)) |
| 2805 | { |
| 2806 | /* it's a GIF image */ |
| 2807 | cont_type = "image/gif"; |
| 2808 | } |
| 2809 | else if (len > 6 && memcmp(bufp, "\211PNG\r\n\032\n", 6) == 0) |
| 2810 | { |
| 2811 | /* it's a PNG image */ |
| 2812 | cont_type = "image/png"; |
| 2813 | } |
| 2814 | else if (len > 3 && memcmp(bufp, "ID3", 3) == 0) |
| 2815 | { |
| 2816 | /* MP3 file */ |
| 2817 | cont_type = "audio/mpeg"; |
| 2818 | } |
| 2819 | else if (len > 14 && memcmp( |
| 2820 | bufp, "OggS\000\002\000\000\000\000\000\000\000\000", 14) |
| 2821 | == 0) |
| 2822 | { |
| 2823 | /* Ogg Vorbis audio */ |
| 2824 | cont_type = "application/ogg"; |
| 2825 | } |
| 2826 | else if (len > 4 && memcmp(bufp, "MThD", 4) == 0) |
| 2827 | { |
| 2828 | /* MIDI */ |
| 2829 | cont_type = "audio/midi"; |
| 2830 | } |
| 2831 | else if (len > 8 |
| 2832 | && (memcmp(bufp, "FWS", 3) == 0 |
| 2833 | || memcmp(bufp, "CWS", 3) == 0)) |
| 2834 | { |
| 2835 | /* shockwave flash */ |
| 2836 | cont_type = "application/x-shockwave-flash"; |
| 2837 | } |
| 2838 | else |
| 2839 | { |
| 2840 | /* we don't recognize it; use generic binary */ |
| 2841 | cont_type = "application/octet-stream"; |
| 2842 | } |
| 2843 | } |
| 2844 | |
| 2845 | /* get the length of the content type string we selected */ |
| 2846 | cont_type_len = strlen(cont_type); |
| 2847 | } |
| 2848 | |
| 2849 | /* get the result code, if present */ |
| 2850 | size_t status_len; |
| 2851 | const char *status = get_status_arg(vmg_ body->status_code, |
| 2852 | 2, argc, status_len); |
| 2853 | |
| 2854 | /* get the headers argument */ |
| 2855 | vm_val_t *headers = 0; |
| 2856 | if (argc >= 4 && G_stk->get(3)->typ != VM_NIL) |
| 2857 | { |
| 2858 | /* get the headers value */ |
| 2859 | headers = G_stk->get(3); |
| 2860 | |
| 2861 | /* make sure it's a list */ |
| 2862 | if (!headers->is_listlike(vmg0_)) |
| 2863 | err_throw(VMERR_LIST_VAL_REQD); |
| 2864 | } |
| 2865 | |
| 2866 | /* set up a reply sender object */ |
| 2867 | sender = new HTTPReplySender(); |
| 2868 | sender->set_params( |
| 2869 | vmg_ self, req, status, status_len, headers, body, |
| 2870 | cont_type, cont_type_len, get_ext()->cookies); |
| 2871 | |
| 2872 | /* the sender now owns our 'body' object */ |
| 2873 | body = 0; |
| 2874 | |
| 2875 | /* send the reply, either directly or in a new thread */ |
| 2876 | if (wait) |
| 2877 | { |
| 2878 | /* waiting for completion - send in the current thread */ |
| 2879 | http_reply_err err; |
| 2880 | if (!sender->send(&err)) |
| 2881 | throw_net_err(vmg_ err.msg, err.sock_err); |
| 2882 | } |
| 2883 | else |
| 2884 | { |
| 2885 | /* sending asynchronously - send in a new thread */ |
| 2886 | sender->start_thread(vmg0_); |
| 2887 | } |
| 2888 | } |
| 2889 | err_finally |
| 2890 | { |
| 2891 | /* done with the body */ |
| 2892 | if (body != 0) |
| 2893 | delete body; |
| 2894 | |
| 2895 | /* done with the reply sender */ |
| 2896 | if (sender != 0) |
| 2897 | sender->release_ref(); |
| 2898 | } |
| 2899 | err_end; |
| 2900 | |
| 2901 | /* discard arguments */ |
| 2902 | G_stk->discard(argc); |
| 2903 | |
| 2904 | /* no result */ |
| 2905 | retval->set_nil(); |
| 2906 | |
| 2907 | /* handled */ |
| 2908 | return TRUE; |
| 2909 | } |
| 2910 | |
| 2911 | /* |
| 2912 | * start a chunked reply |
| 2913 | */ |
| 2914 | int CVmObjHTTPRequest::getp_startChunkedReply( |
| 2915 | VMG_ vm_obj_id_t self, vm_val_t *retval, uint *oargc) |
| 2916 | { |
| 2917 | uint argc = (oargc != 0 ? *oargc : 0); |
| 2918 | static CVmNativeCodeDesc desc(1, 3); |
| 2919 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 2920 | return TRUE; |
| 2921 | |
| 2922 | /* get the request */ |
| 2923 | TadsHttpRequest *req = get_ext()->req; |
| 2924 | |
| 2925 | /* if the request is already completed, this is an error */ |
| 2926 | if (req->completed) |
| 2927 | throw_net_err(vmg_ "request already completed", 0); |
| 2928 | |
| 2929 | /* get the content type argument */ |
| 2930 | const char *cont_type = G_stk->get(0)->get_as_string(vmg0_); |
| 2931 | if (cont_type == 0) |
| 2932 | err_throw(VMERR_STRING_VAL_REQD); |
| 2933 | |
| 2934 | /* get the length and buffer pointer */ |
| 2935 | size_t cont_type_len = vmb_get_len(cont_type); |
| 2936 | cont_type += VMB_LEN; |
| 2937 | |
| 2938 | /* get the result code, if present */ |
| 2939 | size_t status_len; |
| 2940 | const char *status = get_status_arg(vmg_ 0, 1, argc, status_len); |
| 2941 | |
| 2942 | /* get the headers argument */ |
| 2943 | const vm_val_t *headers = 0; |
| 2944 | if (argc >= 3) |
| 2945 | { |
| 2946 | /* get the headers value */ |
| 2947 | headers = G_stk->get(2); |
| 2948 | |
| 2949 | /* make sure it's a list */ |
| 2950 | if (!headers->is_listlike(vmg0_)) |
| 2951 | err_throw(VMERR_LIST_VAL_REQD); |
| 2952 | } |
| 2953 | |
| 2954 | /* |
| 2955 | * Send the headers, starting with the status code |
| 2956 | */ |
| 2957 | TadsServerThread *t = req->thread; |
| 2958 | if (!t->send("HTTP/1.1 ") |
| 2959 | || !t->send(status, status_len) |
| 2960 | || !t->send("\r\n")) |
| 2961 | throw_net_err(vmg_ "error sending status", t->last_error()); |
| 2962 | |
| 2963 | /* send the custom headers, if any */ |
| 2964 | if (headers != 0) |
| 2965 | send_custom_headers(vmg_ t, headers); |
| 2966 | |
| 2967 | /* send the cookies, if any */ |
| 2968 | send_cookies(vmg_ t, get_ext()->cookies); |
| 2969 | |
| 2970 | /* send the standard headers: Content-Type, Transfer-Encoding */ |
| 2971 | char hbuf[256]; |
| 2972 | t3sprintf(hbuf, sizeof(hbuf), |
| 2973 | "Content-Type: %.*s\r\n" |
| 2974 | "Transfer-Encoding: chunked\r\n" |
| 2975 | "\r\n", |
| 2976 | (int)cont_type_len, cont_type); |
| 2977 | if (!t->send(hbuf)) |
| 2978 | throw_net_err(vmg_ "error sending headers", t->last_error()); |
| 2979 | |
| 2980 | /* discard arguments */ |
| 2981 | G_stk->discard(argc); |
| 2982 | |
| 2983 | /* no result */ |
| 2984 | retval->set_nil(); |
| 2985 | |
| 2986 | /* handled */ |
| 2987 | return TRUE; |
| 2988 | } |
| 2989 | |
| 2990 | /* |
| 2991 | * send a piece of a chunked reply |
| 2992 | */ |
| 2993 | int CVmObjHTTPRequest::getp_sendReplyChunk(VMG_ vm_obj_id_t self, |
| 2994 | vm_val_t *retval, uint *oargc) |
| 2995 | { |
| 2996 | uint argc = (oargc != 0 ? *oargc : 0); |
| 2997 | static CVmNativeCodeDesc desc(1); |
| 2998 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 2999 | return TRUE; |
| 3000 | |
| 3001 | /* get the request and thread */ |
| 3002 | TadsHttpRequest *req = get_ext()->req; |
| 3003 | TadsServerThread *t = req->thread; |
| 3004 | |
| 3005 | /* if the request is already completed, this is an error */ |
| 3006 | if (req->completed) |
| 3007 | throw_net_err(vmg_ "request already completed", 0); |
| 3008 | |
| 3009 | /* retrieve the 'body' argument */ |
| 3010 | bodyArg *body = new bodyArg(vmg_ 0); |
| 3011 | |
| 3012 | err_try |
| 3013 | { |
| 3014 | /* make sure we initialized the body correctly */ |
| 3015 | if (body->init_err != 0) |
| 3016 | err_throw(body->init_err); |
| 3017 | |
| 3018 | /* send the length prefix */ |
| 3019 | char lbuf[20]; |
| 3020 | t3sprintf(lbuf, sizeof(lbuf), "%lx\r\n", (long)body->len); |
| 3021 | if (!t->send(lbuf)) |
| 3022 | throw_net_err(vmg_ "error sending length prefix", t->last_error()); |
| 3023 | |
| 3024 | /* send the body */ |
| 3025 | http_reply_err err; |
| 3026 | if (!body->send(t, &err)) |
| 3027 | throw_net_err(vmg_ err.msg, err.sock_err); |
| 3028 | |
| 3029 | /* send the CR-LF suffix */ |
| 3030 | if (!t->send("\r\n")) |
| 3031 | throw_net_err(vmg_ "error sending suffix", t->last_error()); |
| 3032 | } |
| 3033 | err_finally |
| 3034 | { |
| 3035 | /* done with the body */ |
| 3036 | delete body; |
| 3037 | } |
| 3038 | err_end; |
| 3039 | |
| 3040 | /* discard arguments */ |
| 3041 | G_stk->discard(argc); |
| 3042 | |
| 3043 | /* no result */ |
| 3044 | retval->set_nil(); |
| 3045 | |
| 3046 | /* handled */ |
| 3047 | return TRUE; |
| 3048 | } |
| 3049 | |
| 3050 | /* |
| 3051 | * finish a chunked reply |
| 3052 | */ |
| 3053 | int CVmObjHTTPRequest::getp_endChunkedReply(VMG_ vm_obj_id_t self, |
| 3054 | vm_val_t *retval, uint *oargc) |
| 3055 | { |
| 3056 | uint argc = (oargc != 0 ? *oargc : 0); |
| 3057 | static CVmNativeCodeDesc desc(0, 1); |
| 3058 | if (get_prop_check_argc(retval, oargc, &desc)) |
| 3059 | return TRUE; |
| 3060 | |
| 3061 | /* get the request and the thread */ |
| 3062 | TadsHttpRequest *req = get_ext()->req; |
| 3063 | TadsServerThread *t = req->thread; |
| 3064 | |
| 3065 | /* if the request is already completed, this is an error */ |
| 3066 | if (req->completed) |
| 3067 | throw_net_err(vmg_ "request already completed", 0); |
| 3068 | |
| 3069 | /* send the "0" length prefix to indicate we're done */ |
| 3070 | if (!t->send("0\r\n")) |
| 3071 | throw_net_err(vmg_ "error sending end-of-stream", t->last_error()); |
| 3072 | |
| 3073 | /* get the headers argument */ |
| 3074 | const vm_val_t *headers = 0; |
| 3075 | if (argc >= 1) |
| 3076 | { |
| 3077 | /* get the headers value */ |
| 3078 | headers = G_stk->get(0); |
| 3079 | |
| 3080 | /* make sure it's a list */ |
| 3081 | if (!headers->is_listlike(vmg0_)) |
| 3082 | err_throw(VMERR_LIST_VAL_REQD); |
| 3083 | |
| 3084 | /* send the headers */ |
| 3085 | send_custom_headers(vmg_ t, headers); |
| 3086 | } |
| 3087 | |
| 3088 | /* send the closing CR-LF */ |
| 3089 | if (!t->send("\r\n")) |
| 3090 | throw_net_err(vmg_ "error sending suffix", t->last_error()); |
| 3091 | |
| 3092 | /* mark the request as completed */ |
| 3093 | req->complete(); |
| 3094 | |
| 3095 | /* discard arguments */ |
| 3096 | G_stk->discard(argc); |
| 3097 | |
| 3098 | /* no result */ |
| 3099 | retval->set_nil(); |
| 3100 | |
| 3101 | /* handled */ |
| 3102 | return TRUE; |
| 3103 | } |
| 3104 | |
| 3105 | |
| 3106 | /* ------------------------------------------------------------------------ */ |
| 3107 | /* |
| 3108 | * HTTP request object |
| 3109 | */ |
| 3110 | |
| 3111 | /* |
| 3112 | * Prepare the event object. This creates an HTTPRequest object (the |
| 3113 | * intrinsic class representing an incoming HTTP request), and sets up a |
| 3114 | * NetRequestEvent (the byte-code object representing a request) to wrap |
| 3115 | * it. |
| 3116 | */ |
| 3117 | vm_obj_id_t TadsHttpRequest::prep_event_obj(VMG_ int *argc, int *evt_type) |
| 3118 | { |
| 3119 | /* get the HTTPServer object that created the listener thread */ |
| 3120 | vm_obj_id_t srv_obj = thread->get_listener()->get_server_obj(); |
| 3121 | |
| 3122 | /* create and push the HTTPRequest object */ |
| 3123 | G_interpreter->push_obj( |
| 3124 | vmg_ CVmObjHTTPRequest::create(vmg_ FALSE, this, srv_obj)); |
| 3125 | |
| 3126 | /* we added one argument to the constructor */ |
| 3127 | *argc = 1; |
| 3128 | |
| 3129 | /* the event type is NetEvRequest (1 - see include/tadsnet.h) */ |
| 3130 | *evt_type = 1; |
| 3131 | |
| 3132 | /* the event subclass is NetRequestEvent */ |
| 3133 | return G_predef->net_request_event; |
| 3134 | } |
| 3135 |