Debian Codegraph @

terps/tads/tads3/vmbifnet.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header$";
4 #endif
5
6 /* Copyright (c) 2005 by Michael J. Roberts. All Rights Reserved. */
7 /*
8 Name
9 vmbifnet.cpp - TADS networking function set
10 Function
11
12 Notes
13
14 Modified
15 04/20/2010 MJRoberts - Creation
16 */
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <time.h>
21
22 #include "t3std.h"
23 #include "os.h"
24 #include "utf8.h"
25 #include "charmap.h"
26 #include "vmbifnet.h"
27 #include "vmtype.h"
28 #include "vmstack.h"
29 #include "vmerr.h"
30 #include "vmerrnum.h"
31 #include "vmglob.h"
32 #include "vmpool.h"
33 #include "vmobj.h"
34 #include "vmstr.h"
35 #include "vmlst.h"
36 #include "vmrun.h"
37 #include "vmhost.h"
38 #include "vmconsol.h"
39 #include "vmvec.h"
40 #include "vmnet.h"
41 #include "vmimport.h"
42 #include "vmpredef.h"
43 #include "vmhttpsrv.h"
44 #include "vmdatasrc.h"
45 #include "vmbytarr.h"
46 #include "vmfilobj.h"
47 #include "vmcset.h"
48 #include "vmlookup.h"
49 #include "vmtobj.h"
50 #include "vmlog.h"
51
52
53 /* ------------------------------------------------------------------------ */
54 /*
55 * NetEvent.evType values
56 */
57 #define VMBN_EVT_REQUEST 1
58 #define VMBN_EVT_TIMEOUT 2
59 #define VMBN_EVT_DBGBRK 3
60
61
62 /* ------------------------------------------------------------------------ */
63 /*
64 * Static initialization
65 */
66 void CVmBifNet::attach(VMG0_)
67 {
68 /* initialize the network layer */
69 os_net_init(G_net_config);
70
71 /* create the network message queue */
72 G_net_queue = new TadsMessageQueue(0);
73 }
74
75 /*
76 * Static cleanup
77 */
78 void CVmBifNet::detach(VMG0_)
79 {
80 /* done with the message queue - flush it and release our reference */
81 G_net_queue->flush();
82 G_net_queue->release_ref();
83 G_net_queue = 0;
84 }
85
86 /* ------------------------------------------------------------------------ */
87 /*
88 * Connect to the Web UI
89 */
90 void CVmBifNet::connect_ui(VMG_ uint oargc)
91 {
92 /* check arguments */
93 check_argc(vmg_ oargc, 2);
94
95 /* get the server object */
96 vm_val_t *srv = G_stk->get(0);
97 if (srv->typ != VM_OBJ
98 || !CVmObjHTTPServer::is_httpsrv_obj(vmg_ srv->val.obj))
99 err_throw(VMERR_BAD_TYPE_BIF);
100
101 /* get the object pointer properly cast */
102 CVmObjHTTPServer *srvp = (CVmObjHTTPServer *)vm_objp(vmg_ srv->val.obj);
103
104 /* get the URL path */
105 const char *path = G_stk->get(1)->get_as_string(vmg0_);
106 if (path == 0)
107 err_throw(VMERR_BAD_TYPE_BIF);
108
109 /* make a null-terminated copy of the path */
110 char *pathb = lib_copy_str(path + VMB_LEN, vmb_get_len(path));
111
112 /* get the server network address information */
113 char *errmsg = 0;
114 char *addr = 0, *ip = 0;
115 int port;
116 int ok = srvp->get_listener_addr(addr, ip, port);
117
118 /*
119 * If we don't have a network configuration yet, create one. This
120 * notifies other subsystems that we have an active web UI; for
121 * example, the presence of a network UI disables the regular console
122 * UI, since all UI actions have to go through the web UI once it's
123 * established.
124 *
125 * The interpreter startup creates a network configuration if it
126 * receives command-line information telling it that the game was
127 * launched by a Web server in response to an incoming client request.
128 * When the user launches the game in stand-alone mode directly from
129 * the operating system shell, there's no Web server launch
130 * information, so the startup code doesn't create a net config object.
131 * So, if we get here and find we don't have this object, it means that
132 * we're running in local standalone mode.
133 */
134 if (G_net_config == 0)
135 G_net_config = new TadsNetConfig();
136
137 /* connect */
138 if (ok)
139 {
140 /* connect */
141 ok = osnet_connect_webui(vmg_ addr, port, pathb, &errmsg);
142 }
143 else
144 {
145 /* couldn't get the server address */
146 errmsg = lib_copy_str(
147 "No address information available for HTTPServer");
148 }
149
150 /* free strings */
151 lib_free_str(pathb);
152 lib_free_str(addr);
153 lib_free_str(ip);
154
155 /* if there's an error, throw it */
156 if (!ok)
157 {
158 G_interpreter->push_string(vmg_ errmsg);
159 lib_free_str(errmsg);
160 G_interpreter->throw_new_class(vmg_ G_predef->net_exception, 1,
161 "Error connecting to Web UI");
162 }
163
164 /* no return value */
165 retval_nil(vmg0_);
166 }
167
168 /* ------------------------------------------------------------------------ */
169 /*
170 * Get a network event
171 */
172 void CVmBifNet::get_event(VMG_ uint oargc)
173 {
174 /* check arguments */
175 check_argc_range(vmg_ oargc, 0, 1);
176
177 /* get the timeout, if present */
178 long timeout = OS_FOREVER;
179 if (oargc >= 1)
180 {
181 if (G_stk->get(0)->typ == VM_NIL)
182 G_stk->discard();
183 else
184 timeout = pop_int_val(vmg0_);
185 }
186
187 /* we don't know the NetEvent subclass yet, so presume the base class */
188 vm_obj_id_t ev_cl = G_predef->net_event;
189 int argc;
190
191 /* get the next message */
192 TadsMessage *msg = 0;
193 int wret = G_net_queue->wait(vmg_ timeout, &msg);
194
195 /* cast the message */
196 TadsEventMessage *evtmsg = cast_tads_message(TadsEventMessage, msg);
197
198 /* make sure we release the message before exiting */
199 err_try
200 {
201 /* check the wait result */
202 const char *err;
203 switch (wret)
204 {
205 case OSWAIT_EVENT + 0:
206 /* we got a message */
207 if (evtmsg != 0)
208 {
209 /* ask the message to set up a new NetRequestEvent */
210 int evt_code;
211 ev_cl = evtmsg->prep_event_obj(vmg_ &argc, &evt_code);
212
213 /* add the event type argument */
214 G_interpreter->push_int(vmg_ evt_code);
215 ++argc;
216 }
217 else
218 {
219 /* unrecognized message type */
220 err = "getNetEvent(): unexpected message type in queue";
221 goto evt_error;
222 }
223 break;
224
225 case OSWAIT_EVENT + 1:
226 /* 'quit' event - return an error */
227 err = "getNetEvent(): queue terminated";
228 goto evt_error;
229
230 case OSWAIT_EVENT + 2:
231 /* debug break - return a NetEvent with the interrupt code */
232 argc = 1;
233 G_interpreter->push_int(vmg_ VMBN_EVT_DBGBRK);
234 break;
235
236 case OSWAIT_TIMEOUT:
237 /* the timeout expired - return a NetTimeoutEvent */
238 ev_cl = G_predef->net_timeout_event;
239 argc = 1;
240 G_interpreter->push_int(vmg_ VMBN_EVT_TIMEOUT);
241 break;
242
243 case OSWAIT_ERROR:
244 default:
245 /* the wait failed */
246 err = "getNetEvent(): error waiting for request message";
247
248 evt_error:
249 /* on error, throw a NetException describing the problem */
250 G_interpreter->push_string(vmg_ err);
251 G_interpreter->throw_new_class(
252 vmg_ G_predef->net_exception, 1, err);
253 AFTER_ERR_THROW(break;)
254 }
255
256 /*
257 * if the specific event type subclass isn't defined, fall back on
258 * the base NetEvent class
259 */
260 if (ev_cl == VM_INVALID_OBJ)
261 ev_cl = G_predef->net_event;
262
263 /*
264 * construct the NetEvent subclass, or a generic list if we don't
265 * even have the NetEvent class defined
266 */
267 if (ev_cl != VM_INVALID_OBJ)
268 vm_objp(vmg_ ev_cl)->create_instance(vmg_ ev_cl, 0, argc);
269 else
270 retval_obj(vmg_ CVmObjList::create_from_stack(vmg_ 0, argc));
271 }
272 err_finally
273 {
274 /* we're done with the message object */
275 if (msg != 0)
276 msg->release_ref();
277 }
278 err_end;
279 }
280
281 /* ------------------------------------------------------------------------ */
282 /*
283 * Get the local host name
284 */
285 void CVmBifNet::get_hostname(VMG_ uint oargc)
286 {
287 /* check arguments */
288 check_argc(vmg_ oargc, 0);
289
290 /* check the network safety levels */
291 int client_level, server_level;
292 G_host_ifc->get_net_safety(&client_level, &server_level);
293
294 /*
295 * If the network safety level doesn't allow outside network access for
296 * either client or server, return "localhost". If they don't allow
297 * any network access at all, return nil.
298 *
299 * If there's a host name defined in the web configuration, return that
300 * host name. Otherwise, return the default host name from the OS.
301 */
302 if (client_level >= VM_NET_SAFETY_MAXIMUM
303 && server_level >= VM_NET_SAFETY_MAXIMUM)
304 {
305 /* no network access is allowed - return nil */
306 retval_nil(vmg0_);
307 }
308 else if (client_level >= VM_NET_SAFETY_LOCALHOST
309 && server_level >= VM_NET_SAFETY_LOCALHOST)
310 {
311 /* localhost access only - return "localhost" */
312 retval_str(vmg_ "localhost");
313 }
314 else
315 {
316 /*
317 * the network safety level allows outside network access, so we
318 * can return the actual host name - get it from the system
319 */
320 char buf[256];
321 if (os_get_hostname(buf, sizeof(buf)))
322 {
323 /* got it - return the string */
324 retval_ui_str(vmg_ buf);
325 }
326 else
327 {
328 /* no host name available - return nil */
329 retval_nil(vmg0_);
330 }
331 }
332 }
333
334 /* ------------------------------------------------------------------------ */
335 /*
336 * Get the local host IP address
337 */
338 void CVmBifNet::get_host_ip(VMG_ uint oargc)
339 {
340 /* check arguments */
341 check_argc(vmg_ oargc, 0);
342
343 /* check the network safety levels */
344 int client_level, server_level;
345 G_host_ifc->get_net_safety(&client_level, &server_level);
346
347 /*
348 * If the network safety level doesn't allow outside network access for
349 * either client or server, return "localhost". If they don't allow
350 * any network access at all, return nil.
351 */
352 if (client_level >= VM_NET_SAFETY_MAXIMUM
353 && server_level >= VM_NET_SAFETY_MAXIMUM)
354 {
355 /* no network access is allowed - return nil */
356 retval_nil(vmg0_);
357 }
358 else if (client_level >= VM_NET_SAFETY_LOCALHOST
359 && server_level >= VM_NET_SAFETY_LOCALHOST)
360 {
361 /* localhost access only - return the standard localhost IP address */
362 retval_str(vmg_ "127.0.0.1");
363 }
364 else
365 {
366 /* retrieve the host IP address for the default host */
367 char buf[256];
368 if (os_get_local_ip(buf, sizeof(buf), 0))
369 {
370 /* got it - return the string */
371 retval_ui_str(vmg_ buf);
372 }
373 else
374 {
375 /* no host name available - return nil */
376 retval_nil(vmg0_);
377 }
378 }
379 }
380
381
382 /* ------------------------------------------------------------------------ */
383 /*
384 * Get the network storage server URL.
385 */
386
387 /* get the storage server URL */
388 void CVmBifNet::get_storage_url(VMG_ uint oargc)
389 {
390 /* check arguments */
391 check_argc(vmg_ oargc, 1);
392
393 /* set a default nil return in case we can't build the path */
394 retval_nil(vmg0_);
395
396 /* get the resource name */
397 const char *page = G_stk->get(0)->get_as_string(vmg0_);
398 if (page == 0)
399 err_throw(VMERR_STRING_VAL_REQD);
400
401 /* get the resource name length and buffer pointer */
402 size_t pagelen = vmb_get_len(page);
403 page += VMB_LEN;
404
405 /* if there's a network configuration, build the resource path */
406 const char *host = 0, *rootpath = 0;
407 if (G_net_config != 0)
408 {
409 /* get the storage server host name and root path */
410 host = G_net_config->get("storage.domain");
411 rootpath = G_net_config->get("storage.rootpath", "/");
412 }
413
414 /* we must have a host name to proceed */
415 if (host != 0)
416 {
417 /* build the full string */
418 G_interpreter->push_stringf(vmg_ "http://%s%s%.*s",
419 host, rootpath,
420 (int)pagelen, page);
421
422 /* pop it into R0 */
423 G_stk->pop(G_interpreter->get_r0());
424 }
425
426 /* discard arguments */
427 G_stk->discard();
428 }
429
430
431 /* ------------------------------------------------------------------------ */
432 /*
433 * Get the launching host address
434 */
435 void CVmBifNet::get_launch_host_addr(VMG_ uint oargc)
436 {
437 /* check arguments */
438 check_argc(vmg_ oargc, 0);
439
440 /* get the launch host name from the network configuration */
441 const char *host = (G_net_config != 0
442 ? G_net_config->get("hostname")
443 : 0);
444
445 /* if there's a host name, return it, otherwise return nil */
446 if (host != 0)
447 retval_str(vmg_ host);
448 else
449 retval_nil(vmg0_);
450 }
451
452 /* ------------------------------------------------------------------------ */
453 /*
454 * Get a configuration variable
455 */
456 #if 0 // leave this out for now
457 void CVmBifNet::get_net_config(VMG_ uint oargc)
458 {
459 /* check arguments */
460 check_argc(vmg_ oargc, 1);
461
462 /* get the variable name */
463 char name[256];
464 pop_str_val_buf(vmg_ name, sizeof(name));
465
466 /* look up the name */
467 const char *val = 0;
468 if (G_net_config != 0)
469 val = G_net_config->get(name);
470
471 /* if we found a value, return it; otherwise return nil */
472 if (val != 0)
473 retval_str(vmg_ val);
474 else
475 retval_nil(vmg0_);
476 }
477 #endif
478
479
480 /* ------------------------------------------------------------------------ */
481 /*
482 * Send a network request - result event.
483 */
484 class TadsHttpReqResult: public TadsEventMessage
485 {
486 public:
487 TadsHttpReqResult(VMG_ vm_globalvar_t *idg, int status,
488 CVmDataSource *reply, char *hdrs, char *loc)
489 : TadsEventMessage(0)
490 {
491 /* save the VM globals */
492 vmg = VMGLOB_ADDR;
493
494 /* save the ID global */
495 this->idg = idg;
496
497 /* remember the status */
498 this->status = status;
499
500 /* take ownership of the reply, headers, and location objects */
501 this->reply = reply;
502 this->hdrs = hdrs;
503 this->loc = loc;
504 }
505
506 ~TadsHttpReqResult()
507 {
508 /* establish the global context */
509 VMGLOB_PTR(vmg);
510
511 /* delete our ID global */
512 G_obj_table->delete_global_var(idg);
513
514 /* delete the reply object */
515 if (reply != 0)
516 delete reply;
517
518 /* free the reply headers */
519 if (hdrs != 0)
520 delete [] hdrs;
521
522 /* free the redirect location string, if we have one */
523 if (loc != 0)
524 lib_free_str(loc);
525 }
526
527 /* prepare a bytecode event object when we're read from the queue */
528 virtual vm_obj_id_t prep_event_obj(VMG_ int *argc, int *evt_type)
529 {
530 /* push the location string (or nil) */
531 G_interpreter->push_string(vmg_ loc, loc != 0 ? strlen(loc) : 0);
532
533 /* push the header string (or nil) */
534 G_interpreter->push_string(vmg_ hdrs, hdrs != 0 ? strlen(hdrs) : 0);
535
536 /* if we have reply data, push it as a File object */
537 if (reply != 0)
538 {
539 /*
540 * Look for a content-type header, to determine the format of
541 * the reply body. If the header starts with "text/", it's a
542 * text type; otherwise it's a binary type.
543 */
544 int mode = VMOBJFILE_MODE_RAW;
545 const char *charset = "ISO-8859-1";
546 size_t cslen = 10;
547 const char *ct = find_header("content-type");
548 if (ct != 0 && memcmp(ct, "text/", 5) == 0)
549 {
550 /* it's a textual type */
551 mode = VMOBJFILE_MODE_TEXT;
552
553 /* look for a 'charset' attribute */
554 for (;;)
555 {
556 /* scan ahead to the next ';' before end of line */
557 for ( ; *ct != '\0' && *ct != '\r'
558 && *ct != '\n' && *ct != ';' ; ++ct) ;
559 if (*ct != ';')
560 break;
561
562 /* skip the ';' and spaces */
563 for (ct += 1 ; *ct != '\0' && is_space(*ct) ; ++ct) ;
564
565 /* check for "charset" */
566 if (memcmp(ct, "charset=", 8) == 0)
567 {
568 /* note the "charset" attribute, and find the end */
569 for (ct += 8, charset = ct ;
570 *ct != '\r' && *ct != '\n' && *ct != ';'
571 && !is_space(*ct) ; ++ct) ;
572
573 /* note the character set name length */
574 cslen = ct - charset;
575
576 /* look no further */
577 break;
578 }
579 }
580 }
581
582 /* if it's a text-mode file, create a character mapper */
583 vm_obj_id_t csobj = VM_INVALID_OBJ;
584 if (mode == VMOBJFILE_MODE_TEXT)
585 csobj = CVmObjCharSet::create(vmg_ FALSE, charset, cslen);
586
587 /* seek to the beginning of the reply stream */
588 reply->seek(0, OSFSK_SET);
589
590 /* create a File object from the Data Source */
591 vm_obj_id_t fileobj = CVmObjFile::create(
592 vmg_ FALSE, 0, csobj, reply, mode,
593 VMOBJFILE_ACCESS_READ, TRUE);
594
595 /* push the file object */
596 G_interpreter->push_obj(vmg_ fileobj);
597
598 /*
599 * the File object owns the data source, which owns the reply
600 * stream, so forget about the reply stream
601 */
602 reply = 0;
603 }
604 else
605 {
606 /* no reply data - push nil */
607 G_interpreter->push_nil(vmg0_);
608 }
609
610 /* push the network status code */
611 G_interpreter->push_int(vmg_ status);
612
613 /* push the caller's ID value */
614 G_stk->push(&idg->val);
615
616 /* relay our added argument count to the caller */
617 *argc = 5;
618
619 /* set the event type to NetEvReply (5 - see include/tadsnet.h) */
620 *evt_type = 5;
621
622 /* the event subclass is NetReplyEvent */
623 return G_predef->net_reply_event;
624 }
625
626 protected:
627 /* find a header */
628 const char *find_header(const char *name)
629 {
630 /* remember the name length */
631 size_t namelen = strlen(name);
632
633 /* scan the headers */
634 for (const char *p = hdrs ; p != 0 ; p = next_header(p))
635 {
636 /* skip spaces */
637 for ( ; *p != '\0' && is_space(*p) ; ++p) ;
638
639 /* check for a match */
640 if (memicmp(p, name, namelen) == 0)
641 {
642 /* skip the name and any subsequent spaces */
643 for (p += namelen ; *p != '\0' && is_space(*p) ; ++p) ;
644
645 /* make sure we have a ':' */
646 if (*p == ':')
647 {
648 /* skip the ':' and subsequent spaces */
649 for (p += 1 ; *p != '\0' && is_space(*p) ; ++p) ;
650
651 /* this is the start of the header value */
652 return p;
653 }
654 }
655 }
656
657 /* didn't find it */
658 return 0;
659 }
660
661 /* find the next header */
662 const char *next_header(const char *p)
663 {
664 /* scan ahead to the next \r\n sequence */
665 for ( ; *p != '\0' ; ++p)
666 {
667 /* if this is a CR-LF sequence, it's the end of this header */
668 if (*p == '\r' && *(p+1) == '\n')
669 {
670 /* skip spaces */
671 for (p += 2 ; *p != '\0' && is_space(*p) ; ++p) ;
672
673 /* if this was a blank line, we're out of headers */
674 if (*p == '\0' || (*p == '\r' && *(p+1) == '\n'))
675 return 0;
676
677 /* this is the next header */
678 return p;
679 }
680 }
681
682 /* no more headers */
683 return 0;
684 }
685
686 /* VM globals */
687 vm_globals *vmg;
688
689 /*
690 * VM global variable for the ID value. We need to hang on to the ID
691 * value until the request completes, since we have to pass it back to
692 * the program via the NetEvent we generate at completion. Since the
693 * thread isn't a garbage-collected object, we have to explicitly
694 * register our reference on the ID value via a VM global variable.
695 */
696 vm_globalvar_t *idg;
697
698 /* HTTP status (or OS_HttpClient::ErrXxx code, if negative) */
699 int status;
700
701 /* the reply content body */
702 CVmDataSource *reply;
703
704 /* reply headers */
705 char *hdrs;
706
707 /* redirect location */
708 char *loc;
709 };
710
711 /* ------------------------------------------------------------------------ */
712 /*
713 * Request option flags
714 */
715 #define NetReqNoRedirect 0x0001
716
717 /* form body lookup table iterator context */
718 struct iter_body_table_ctx
719 {
720 iter_body_table_ctx(class HttpReqThread *self, const vm_rcdesc *rc)
721 : self(self), rc(rc) { }
722 class HttpReqThread *self;
723 const vm_rcdesc *rc;
724 };
725
726 /* ------------------------------------------------------------------------ */
727 /*
728 * Send a network request - HTTP client thread. This is the worker thread
729 * we launch to asynchronously send an HTTP request to a remote server.
730 */
731 class HttpReqThread: public OS_Thread
732 {
733 public:
734 /*
735 * Set up the thread. All string parameters are provided in internal
736 * string format, with VMB_LEN length prefixes.
737 */
738 HttpReqThread(VMG_ const vm_val_t *id, const char *url,
739 const char *verb, int32_t options,
740 const char *hdrs, vm_val_t *body, const char *body_type,
741 const vm_rcdesc *rc)
742 {
743 /* save the VM globals */
744 vmg = VMGLOB_ADDR;
745
746 /* add a reference on the net event queue */
747 if ((queue = G_net_queue) != 0)
748 queue->add_ref();
749
750 /* create a global for the ID value */
751 idg = G_obj_table->create_global_var();
752 idg->val = *id;
753
754 /* save the option flags */
755 this->options = options;
756
757 /* set up to parse the URL */
758 size_t urll = vmb_get_len(url);
759 url += VMB_LEN;
760
761 /* note whether the scheme is plain http or https */
762 https = (urll >= 8 && memcmp(url, "https://", 8) == 0);
763
764 /* we don't have any URL pieces yet */
765 host = 0;
766 resource = 0;
767 port = (https ? 443 : 80);
768
769 /* skip the scheme prefix */
770 size_t pfx = (urll >= 7 && memcmp(url, "http://", 7) == 0 ? 7 :
771 urll >= 8 && memcmp(url, "https://", 8) == 0 ? 8 : 0);
772 url += pfx, urll -= pfx;
773
774 /* the host name is the part up to the ':', '/', or end of string */
775 const char *start;
776 for (start = url ; urll > 0 && *url != ':' && *url != '/' ;
777 ++url, --urll) ;
778
779 /* save the host name */
780 host = lib_copy_str(start, url - start);
781
782 /* parse the port, if present */
783 if (urll > 0 && *url == ':')
784 {
785 /* parse the port number string */
786 for (--urll, start = ++url, port = 0 ; urll > 0 && *url != '/' ;
787 ++url, --urll)
788 {
789 if (is_digit(*url))
790 port = port*10 + value_of_digit(*url);
791 }
792 }
793
794 /*
795 * The rest (including the '/') is the resource string. If there's
796 * nothing left, the resource is implicitly '/'.
797 */
798 if (urll > 0)
799 resource = lib_copy_str(url, urll);
800 else
801 resource = lib_copy_str("/");
802
803 /* make null-terminated copies of the various strings */
804 this->verb = lib_copy_str(verb + VMB_LEN, vmb_get_len(verb));
805 this->hdrs = (hdrs == 0 ? 0 :
806 lib_copy_str(hdrs + VMB_LEN, vmb_get_len(hdrs)));
807
808 /* if there's a content body, set up the payload */
809 this->body = 0;
810 if (body != 0)
811 {
812 /* set up an empty payload */
813 this->body = new OS_HttpPayload();
814
815 /*
816 * Convert the body to a stream payload, if it's a string or
817 * ByteArray. If it's a LookupTable, it's a set of form
818 * fields.
819 */
820 if (body->typ == VM_OBJ
821 && CVmObjLookupTable::is_lookup_table_obj(vmg_ body->val.obj))
822 {
823 /*
824 * The body is a LookupTable, so we have a set of form
825 * fields to encode as HTML form data.
826 */
827
828 /* cast the object value */
829 CVmObjLookupTable *tab =
830 (CVmObjLookupTable *)vm_objp(vmg_ body->val.obj);
831
832 /* add each key in the table as a form field */
833 iter_body_table_ctx ctx(this, rc);
834 tab->for_each(vmg_ iter_body_table, &ctx);
835 }
836 else
837 {
838 /*
839 * It's not a lookup table, so it must be bytes to upload,
840 * as a string or ByteArray.
841 */
842 const char *def_mime_type = 0;
843 CVmDataSource *s = val_to_ds(vmg_ body, &def_mime_type);
844
845 /* presume we're going to use the default mime type */
846 const char *mime_type = def_mime_type;
847 size_t mime_type_len =
848 (mime_type != 0 ? strlen(mime_type) : 0);
849
850 /* if the caller specified a mime type, use it instead */
851 if (body_type != 0)
852 {
853 mime_type = body_type + VMB_LEN;
854 mime_type_len = vmb_get_len(body_type);
855 }
856
857 /* add the stream */
858 this->body->add(
859 "", 0, "", 0, mime_type, mime_type_len, s);
860 }
861 }
862 }
863
864 ~HttpReqThread()
865 {
866 /* establish the global context */
867 VMGLOB_PTR(vmg);
868
869 /* delete copied strings */
870 lib_free_str(host);
871 lib_free_str(resource);
872 lib_free_str(verb);
873 lib_free_str(hdrs);
874
875 /* delete the content body */
876 if (body != 0)
877 delete body;
878
879 /* release the message queue */
880 if (queue != 0)
881 queue->release_ref();
882
883 /* delete our ID global, if we still own it */
884 if (idg != 0)
885 G_obj_table->delete_global_var(idg);
886
887 }
888
889 /* main thread entrypoint */
890 void thread_main()
891 {
892 /* if they want redirections, set up to receive the location */
893 char *loc = 0;
894 char **locp = ((options & NetReqNoRedirect) != 0 ? &loc : 0);
895
896 /* set up a memory stream object to hold the reply */
897 CVmMemorySource *reply = new CVmMemorySource(128);
898
899 /* no reply headers yet */
900 char *reply_hdrs = 0;
901
902 /* figure the request option flags */
903 int rflags = 0;
904 if (https)
905 rflags |= OS_HttpClient::OptHTTPS;
906
907 /* get the length of the custom headers, if we have any */
908 size_t hdrs_len = (hdrs != 0 ? strlen(hdrs) : 0);
909
910 /* send the request */
911 int status = OS_HttpClient::request(
912 rflags, host, port, verb, resource, hdrs, hdrs_len, body,
913 reply, &reply_hdrs, locp, 0);
914
915 /*
916 * if the status is negative, a system-level error occurred, so
917 * there's no reply data - delete and forget the reply stream
918 */
919 if (status < 0)
920 {
921 delete reply;
922 reply = 0;
923 }
924
925 /*
926 * Always post a result event, even on failure, since the event is
927 * the way we transmit the status information back to the caller.
928 * Note that the event object takes ownership of the reply stream,
929 * headers string, and location string, and will free the
930 * underlying memory when the event object is deleted.
931 */
932 post_result(status, reply, reply_hdrs, loc);
933 }
934
935 /* post the result */
936 void post_result(int status, CVmDataSource *reply, char *hdrs, char *loc)
937 {
938 /* establish the global context */
939 VMGLOB_PTR(vmg);
940
941 /* create the result event */
942 TadsHttpReqResult *evt = new TadsHttpReqResult(
943 vmg_ idg, status, reply, hdrs, loc);
944
945 /* post the event (this transfers ownership to the queue) */
946 queue->post(evt);
947
948 /* the result event now owns our ID global 'idg', so forget it */
949 idg = 0;
950 }
951
952 protected:
953 /*
954 * Convert a string or ByteArray object to a data stream
955 */
956 static CVmDataSource *val_to_ds(VMG_ const vm_val_t *val,
957 const char **def_mime_type)
958 {
959 /* try it as a string */
960 const char *bstr = val->get_as_string(vmg0_);
961 if (bstr != 0)
962 {
963 /* assume this is text/plain */
964 *def_mime_type = "text/plain; charset=utf-8";
965
966 /* create a stream with a private copy of the string */
967 return new CVmPrivateStringSource(
968 bstr + VMB_LEN, vmb_get_len(bstr));
969 }
970 else if (val->typ == VM_OBJ
971 && CVmObjByteArray::is_byte_array(vmg_ val->val.obj))
972 {
973 /* assume this is binary data */
974 *def_mime_type = "application/octet-stream";
975
976 /* cast the ByteArray object value */
977 CVmObjByteArray *barr =
978 (CVmObjByteArray *)vm_objp(vmg_ val->val.obj);
979
980 /* create a stream copy of the byte array's contents */
981 unsigned long arrlen = barr->get_element_count();
982 CVmDataSource *s = new CVmMemorySource(arrlen);
983
984 /* copy the array's contents to the stream */
985 const size_t BLOCKLEN = 1024;
986 char block[BLOCKLEN];
987 for (unsigned long idx = 1 ; idx <= arrlen ; idx += BLOCKLEN)
988 {
989 /* read as much as remains */
990 unsigned long rem = arrlen - idx + 1;
991 size_t cur = (rem < BLOCKLEN ? (size_t)rem : BLOCKLEN);
992
993 /* copy the data */
994 barr->copy_to_buf((unsigned char *)block, idx, cur);
995 s->write(block, cur);
996 }
997
998 /*
999 * rewind the stream to the start, so that the network code
1000 * reads the entire contents from the beginning
1001 */
1002 s->seek(0, OSFSK_SET);
1003
1004 /* return the stream */
1005 return s;
1006 }
1007 else
1008 {
1009 /* we can't convert other types */
1010 return 0;
1011 }
1012 }
1013
1014 /*
1015 * Lookup Table for_each callback for building a form payload. When
1016 * the caller specifies the body as a lookup table, we'll iterate over
1017 * the table's contents using this callback, which adds each field to
1018 * the payload object.
1019 */
1020 static void iter_body_table(
1021 VMG_ const vm_val_t *key, const vm_val_t *val, void *ctx0)
1022 {
1023 /* get the context */
1024 iter_body_table_ctx *ctx = (iter_body_table_ctx *)ctx0;
1025
1026 /* the key must be a string giving the field name */
1027 const char *field_name = key->get_as_string(vmg0_);
1028 if (field_name == 0)
1029 return;
1030
1031 /*
1032 * the value must be either a string giving the simple form field
1033 * value, or a FileUpload object giving a file to upload
1034 */
1035 if (val->is_instance_of(vmg_ G_predef->file_upload_cl))
1036 {
1037 /*
1038 * It's a FileUpload object. The 'file' property is the
1039 * content object, which must be provided as a string or
1040 * ByteArray; the 'filename' and 'contentType' properties are
1041 * strings giving us details on how to treat the content data.
1042 */
1043
1044 /* retrieve the property values we're interested in */
1045 vm_val_t file_val, ctype_val, fname_val;
1046 G_interpreter->get_prop(
1047 vmg_ &file_val, val, G_predef->file_upload_fileObj, 0,
1048 ctx->rc);
1049 G_interpreter->get_prop(
1050 vmg_ &ctype_val, val, G_predef->file_upload_contentType, 0,
1051 ctx->rc);
1052 G_interpreter->get_prop(
1053 vmg_ &fname_val, val, G_predef->file_upload_filename, 0,
1054 ctx->rc);
1055
1056 /* wrap the 'file' value in a datasource */
1057 const char *def_ctype = 0;
1058 CVmDataSource *src = val_to_ds(vmg_ &file_val, &def_ctype);
1059
1060 /* if we have a contentType string, override the default */
1061 const char *ctype = ctype_val.get_as_string(vmg0_);
1062 size_t ctype_len;
1063 if (ctype != 0)
1064 {
1065 /* they specified a content type - use their value */
1066 ctype_len = vmb_get_len(ctype);
1067 ctype += VMB_LEN;
1068 }
1069 else
1070 {
1071 /* use the default */
1072 ctype = def_ctype;
1073 ctype_len = strlen(def_ctype);
1074 }
1075
1076 /* get the filename string, if they provided one */
1077 const char *fname = fname_val.get_as_string(vmg0_);
1078 size_t fname_len = (fname != 0 ? vmb_get_len(fname) : 0);
1079 fname += (fname != 0 ? VMB_LEN : 0);
1080
1081 /* add the field */
1082 ctx->self->body->add(
1083 field_name + VMB_LEN, vmb_get_len(field_name),
1084 fname, fname_len, ctype, ctype_len, src);
1085 }
1086 else
1087 {
1088 /* get a string interpretation of the value */
1089 vm_val_t new_str;
1090 const char *field_val = val->cast_to_string(vmg_ &new_str);
1091 if (field_val == 0)
1092 return;
1093
1094 /* add the field to the payload */
1095 ctx->self->body->add_tstr(field_name, field_val);
1096 }
1097 }
1098
1099 /* VM globals */
1100 vm_globals *vmg;
1101
1102 /* event message queue */
1103 TadsMessageQueue *queue;
1104
1105 /* option flags */
1106 int32_t options;
1107
1108 /* parsed URL information */
1109 int https;
1110 char *host;
1111 char *resource;
1112 unsigned short port;
1113
1114 /* the verb */
1115 char *verb;
1116
1117 /* custom headers */
1118 char *hdrs;
1119
1120 /* the content body */
1121 OS_HttpPayload *body;
1122
1123 /*
1124 * VM global variable for the ID value. We need to hang on to the ID
1125 * value until the request completes, since we have to pass it back to
1126 * the program via the NetEvent we generate at completion. Since the
1127 * thread isn't a garbage-collected object, we have to explicitly
1128 * register our reference on the ID value via a VM global variable.
1129 */
1130 vm_globalvar_t *idg;
1131 };
1132
1133
1134 /* ------------------------------------------------------------------------ */
1135 /*
1136 * Match a domain name in a URL to the given string
1137 */
1138 static int match_url_domain(const char *url, size_t urll, const char *domain)
1139 {
1140 /* note the length of the domain name we're matching */
1141 size_t domainl = strlen(domain);
1142
1143 /* scan to the end of the scheme name */
1144 for ( ; urll > 0 ; ++url, --urll)
1145 {
1146 /* the scheme name ends in "://" */
1147 if (urll > 3 && memcmp(url, "://", 3) == 0)
1148 {
1149 /* skip the :// sequence */
1150 url += 3;
1151 urll -= 3;
1152
1153 /*
1154 * we have a match if the domain name follows, and either it's
1155 * the whole rest of the string, or the next character after
1156 * the domain name is '/' or ':'
1157 */
1158 return (urll >= domainl
1159 && memicmp(url, domain, domainl) == 0
1160 && (urll == domainl
1161 || url[domainl] == ':'
1162 || url[domainl] == '/'));
1163 }
1164 }
1165
1166 /* didn't find the end of the scheme name - fail */
1167 return FALSE;
1168 }
1169
1170 /* ------------------------------------------------------------------------ */
1171 /*
1172 * Send a network request
1173 */
1174 void CVmBifNet::send_net_request(VMG_ uint argc)
1175 {
1176 /* check arguments - we need (id, url), and after that it varies */
1177 check_argc_range(vmg_ argc, 2, 32767);
1178
1179 /*
1180 * set up a recursive VM context, in case we need it (we might, for
1181 * evaluating FileUpload properties in a form body lookup table)
1182 */
1183 vm_rcdesc rc(vmg_ "sendNetRequest", CVmBifNet::bif_table, 6,
1184 G_stk->get(0), argc);
1185
1186 /* get the network safety levels */
1187 int client_level, server_level;
1188 G_host_ifc->get_net_safety(&client_level, &server_level);
1189
1190 /* if the client safety level doesn't allow client operations, fail */
1191 if (client_level >= VM_NET_SAFETY_MAXIMUM)
1192 err_throw(VMERR_NETWORK_SAFETY);
1193
1194 /* retrieve the ID value - any type is allowed here */
1195 vm_val_t *id = G_stk->get(0);
1196
1197 /* retrieve the URL - this must be a string */
1198 const char *url = get_str_val(vmg_ G_stk->get(1));
1199 size_t urll = vmb_get_len(url);
1200 url += VMB_LEN;
1201
1202 /* get the image URL, for logging purposes */
1203 const char *image_url = "<image URL unknown>";
1204 if (G_net_config != 0)
1205 image_url = G_net_config->get("image.url", "<image URL unknown>");
1206
1207 /* map the URL to the local file character set */
1208 char *lurl;
1209 size_t lurll = G_cmap_to_file->map_utf8_alo(&lurl, url, urll);
1210
1211 /* log the request */
1212 vm_log_fmt(vmg_ "client request to %.*s by %s",
1213 (int)lurll, lurl, image_url);
1214
1215 /* done with the local version of the URL */
1216 t3free(lurl);
1217
1218 /* check the protocol */
1219 if (urll >= 7
1220 && (memcmp(url, "http://", 7) == 0
1221 || memcmp(url, "https://", 8) == 0))
1222 {
1223 /* HTTP or HTTPS */
1224
1225 /*
1226 * if we're restricted to local access, verify that the domain is
1227 * "localhost" or "127.0.0.1"
1228 */
1229 if (client_level == VM_NET_SAFETY_LOCALHOST)
1230 {
1231 /* get a pointer to the domain */
1232 if (!match_url_domain(url, urll, "localhost")
1233 && !match_url_domain(url, urll, "127.0.0.1"))
1234 err_throw(VMERR_NETWORK_SAFETY);
1235 }
1236
1237 /* get the verb - this must be a string */
1238 const char *verb = get_str_val(vmg_ G_stk->get(2));
1239
1240 /* get the option flags, if present */
1241 int32_t options = 0;
1242 if (argc >= 4 && G_stk->get(3)->typ != VM_NIL)
1243 options = G_stk->get(3)->num_to_int(vmg0_);
1244
1245 /* get the headers, if present */
1246 const char *hdrs = 0;
1247 if (argc >= 5 && G_stk->get(4)->typ != VM_NIL)
1248 hdrs = get_str_val(vmg_ G_stk->get(4));
1249
1250 /* get the content body, if present */
1251 vm_val_t *body = 0;
1252 if (argc >= 6 && G_stk->get(5)->typ != VM_NIL)
1253 {
1254 /* get the body value */
1255 body = G_stk->get(5);
1256
1257 /*
1258 * verify the body type - this must be a string, byte array, or
1259 * lookup table
1260 */
1261 if (body->get_as_string(vmg0_) != 0
1262 || (body->typ == VM_OBJ
1263 && (CVmObjByteArray::is_byte_array(vmg_ body->val.obj)
1264 || CVmObjLookupTable::is_lookup_table_obj(
1265 vmg_ body->val.obj))))
1266 {
1267 /* acceptable body type */
1268 }
1269 else
1270 {
1271 /* invalid body type */
1272 err_throw(VMERR_BAD_TYPE_BIF);
1273 }
1274 }
1275
1276 /* get the body's MIME type, if present */
1277 const char *body_type = 0;
1278 if (argc >= 7 && G_stk->get(6)->typ != VM_NIL)
1279 body_type = get_str_val(vmg_ G_stk->get(6));
1280
1281 /* create the request processor thread */
1282 HttpReqThread *th = new HttpReqThread(
1283 vmg_ id, url - VMB_LEN, verb, options, hdrs, body, body_type, &rc);
1284
1285 /* launch the thread */
1286 if (!th->launch())
1287 {
1288 /*
1289 * We couldn't launch the thread - post a result event
1290 * indicating failure. We have to post the result event
1291 * ourselves because (a) a result event always has to be
1292 * posted, even when the request fails, as it's the way that we
1293 * transmit all status information back to the caller, and (b)
1294 * the thread would normally post the result, but it won't be
1295 * doing so because it never got started.
1296 */
1297 th->post_result(OS_HttpClient::ErrThread, 0, 0, 0);
1298 }
1299
1300 /* done with the thread object */
1301 th->release_ref();
1302 }
1303 else
1304 {
1305 /* unknown protocol - it's an error */
1306 err_throw(VMERR_BAD_VAL_BIF);
1307 }
1308
1309 /* pop the arguments */
1310 G_stk->discard(argc);
1311
1312 /* there's no return value, but return nil to clear out any old data */
1313 retval_nil(vmg0_);
1314 }