Debian Codegraph @

terps/tads/tads3/vmnet.h

raw symbols SCIP
1 /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */
2 /*
3 Name
4 vmnet.h - TADS 3 networking
5 Function
6 Defines the networking layer for TADS 3. This is used for the web server
7 configurations. This is portable code implementing high-level network
8 operations, such as an HTTP server, using the low-level socket and thread
9 API defined in osifcnet.h.
10 Notes
11
12 Modified
13 04/11/10 MJRoberts - Creation
14 */
15
16 #ifndef VMNET_H
17 #define VMNET_H
18
19
20 /* include this module only if the networking subsystem is enabled */
21 #ifdef TADSNET
22
23 #include <time.h>
24 #include <wchar.h>
25
26 #include "osifcnet.h"
27 #include "t3std.h"
28 #include "vmtype.h"
29 #include "vmglob.h"
30 #include "vmerr.h"
31 #include "vmdbg.h"
32 #include "vmglob.h"
33 #include "vmstrref.h"
34
35
36 /* ------------------------------------------------------------------------ */
37 /*
38 * Web server configuration. We create a global singleton of this
39 * structure when the interpreter reads a web configuration file at
40 * startup.
41 */
42 class TadsNetConfig
43 {
44 public:
45 TadsNetConfig()
46 {
47 first_var = 0;
48 last_var = 0;
49 }
50
51 ~TadsNetConfig();
52
53 /* read a config file */
54 void read(osfildef *fp, class CVmMainClientIfc *clientifc);
55
56 /* look up a configuration variable */
57 const char *get(const char *name) const;
58
59 /* look up a configuration variable, applying a default if not defined */
60 const char *get(const char *name, const char *defval)
61 {
62 const char *val = get(name);
63 return (val != 0 ? val : defval);
64 }
65
66 /* does the given configuration variable equal the given string? */
67 const int match(const char *name, const char *strval)
68 {
69 const char *val = get(name, "");
70 return strcmp(val, strval) == 0;
71 }
72
73 /*
74 * Does the given configuration variable equal the given integer? If
75 * the configuration variable isn't defined, returns false. Otherwise,
76 * converts the configuration string value to an integer with atoi(),
77 * and compares the result to the given value.
78 */
79 const int match(const char *name, int intval)
80 {
81 const char *val = get(name);
82 return (val != 0 ? atoi(val) == intval : FALSE);
83 }
84
85 /* set a variable */
86 class TadsNetConfigVar *set(const char *name, const char *val);
87
88 protected:
89 /* look up a variable */
90 class TadsNetConfigVar *getvar(const char *name) const;
91
92 /* head/tail of list of variables */
93 class TadsNetConfigVar *first_var;
94 class TadsNetConfigVar *last_var;
95 };
96
97 /* variable entry in a TadsNetConfig */
98 class TadsNetConfigVar
99 {
100 public:
101 TadsNetConfigVar(const char *name, const char *val)
102 {
103 this->name = lib_copy_str(name);
104 this->val = lib_copy_str(val);
105 this->nxt = 0;
106 }
107
108 ~TadsNetConfigVar()
109 {
110 lib_free_str(name);
111 lib_free_str(val);
112 }
113
114 /* get the name/value */
115 const char *getname() const { return name; }
116 const char *getval() const { return val; }
117
118 /* change the value */
119 void setval(const char *val)
120 {
121 lib_free_str(this->val);
122 this->val = lib_copy_str(val);
123 }
124
125 /* does our name match the given name? */
126 int matchname(const char *name)
127 { return stricmp(name, this->name) == 0; }
128
129 /* get/set the next item pointer */
130 TadsNetConfigVar *getnext() const { return nxt; }
131 void setnext(TadsNetConfigVar *nxt) { this->nxt = nxt; }
132
133 protected:
134 char *name;
135 char *val;
136 TadsNetConfigVar *nxt;
137 };
138
139
140
141 /* ------------------------------------------------------------------------ */
142 /*
143 * Check a storage server API reply, and throw an error if appropriate.
144 * Storage server API replies conventionally are plain text buffers of the
145 * form:
146 *
147 * Code Message
148 *
149 * where 'Code' is an alphanumeric token giving an error code, and Message
150 * is a human-readable result message. On success, the Code token is "OK";
151 * other token strings indicate errors.
152 *
153 * Functions that also return regular body data (such as GETFILE) return
154 * the status message in an X-IFDBStorage-Status header instead of the
155 * body. If the status header is present, we'll use that rather than
156 * checking the reply body.
157 *
158 * If the HTML status, headers, or reply indicates an error, we'll throw a
159 * storage server run-time error, so this won't return. On success, we
160 * simply return.
161 */
162 void vmnet_check_storagesrv_reply(VMG_ int htmlstat, CVmDataSource *reply,
163 const char *headers);
164
165 /*
166 * Retrieve the storage server status from the reply. This returns an
167 * allocated string buffer containing the status code as the first
168 * space-delimited token, with a printable error message following.
169 *
170 * The status code is "OK" on success. If the request failed due to a
171 * storage server error, the first token is a non-numeric error ID. If the
172 * request failed due to an HTTP, the first token is the numeric HTTP
173 * status. If the request failed due to a lower-level network error, the
174 * code is a negative numeric code giving the internal OS_HttpClient ErrXxx
175 * code.
176 *
177 * The caller must delete the returned buffer with t3free().
178 */
179 char *vmnet_get_storagesrv_stat(VMG_ int htmlstat, CVmDataSource *reply,
180 const char *headers);
181
182 /*
183 * Check the reply code returned by vmnet_get_storagesrv_reply(). On
184 * success, frees the status code buffer and returns. On failure, frees
185 * the status code buffer and throws a StorageServerError exception. Note
186 * that we free the buffer in either case.
187 */
188 void vmnet_check_storagesrv_stat(VMG_ char *stat);
189
190
191 /* ------------------------------------------------------------------------ */
192 /*
193 * Master thread list. This is a portable helper object for keeping a list
194 * of threads. The OS implementation can use this to maintain a list of
195 * all of the threads the program has started. This is useful mainly so
196 * that the program can wait for background threads to exit on their own
197 * before terminating the overall process. It could also be useful for
198 * debugging purposes, such as to display a list of active threads on the
199 * console at various times.
200 *
201 * If the OS layer uses this object, OS_Thread should register each new
202 * thread in its constructor, and unregister each outgoing thread in its
203 * destructor. Doing so is optional - it's purely for the OS layer's
204 * benefit, so if the OS layer doesn't need the master thread list
205 * information, it can ignore this object.
206 */
207
208 /*
209 * thread list link
210 */
211 struct TadsThreadLink
212 {
213 TadsThreadLink(OS_Thread *thread, TadsThreadLink *nxt)
214 {
215 /* save a weak reference to the thread */
216 this->thread = thread->get_weak_ref();
217 this->nxt = nxt;
218 }
219
220 ~TadsThreadLink()
221 {
222 thread->release_ref();
223 }
224
225 OS_Thread *get_thread()
226 {
227 return (OS_Thread *)thread->ref();
228 }
229
230 /* weak reference to our thread */
231 CVmWeakRef *thread;
232
233 /* next link in list */
234 TadsThreadLink *nxt;
235 };
236
237
238 /*
239 * thread list
240 */
241 class TadsThreadList: public CVmRefCntObj
242 {
243 public:
244 TadsThreadList()
245 {
246 mu = new OS_Mutex();
247 head = 0;
248 }
249
250 ~TadsThreadList()
251 {
252 mu->release_ref();
253 }
254
255 /*
256 * add a thread to the master list - the OS_Thread constructor must
257 * call this
258 */
259 void add(OS_Thread *thread)
260 {
261 /* lock the list */
262 mu->lock();
263
264 /* link the thread into our list */
265 head = new TadsThreadLink(thread, head);
266
267 /* done with the list lock */
268 mu->unlock();
269 }
270
271 /* clean the list - clear dead threads */
272 void clean()
273 {
274 /* lock the list */
275 mu->lock();
276
277 /*
278 * Unlink the thread from the list. It's possible that it's not in
279 * the list any longer, since wait_all() removes threads before
280 * waiting for them to exit.
281 */
282 TadsThreadLink *cur, *prv, *nxt;
283 for (prv = 0, cur = head ; cur != 0 ; cur = nxt)
284 {
285 /* remember the next thread */
286 nxt = cur->nxt;
287
288 /* check to see if this thread is still alive */
289 if (cur->thread->test())
290 {
291 /* it's still alive - keep it in the list */
292 prv = cur;
293 }
294 else
295 {
296 /* this thread is gone - remove the link */
297 if (prv != 0)
298 prv->nxt = nxt;
299 else
300 head = nxt;
301
302 /* delete the link */
303 delete cur;
304 }
305 }
306
307 /* done with the list lock */
308 mu->unlock();
309 }
310
311 /*
312 * Wait for all threads to exit. The 'timeout' (given in milliseconds)
313 * is applied to each individual thread. Returns true if all threads
314 * exited successfully, false if one or more threads timed out.
315 */
316 int wait_all(long timeout)
317 {
318 /* presume success */
319 int ok = TRUE;
320
321 /* keep going until we're out of threads */
322 for (;;)
323 {
324 /* lock the list and pull off the first thread */
325 mu->lock();
326 TadsThreadLink *link = head;
327
328 /* if we got an element, remove it from the list */
329 if (link != 0)
330 {
331 /*
332 * Unlink it from the list. Note that our local variable
333 * 't' has now assumed the reference count that the list
334 * previously held on the thread.
335 */
336 head = link->nxt;
337 }
338
339 /* done with the list lock */
340 mu->unlock();
341
342 /* if there are no more threads, we're done */
343 if (link == 0)
344 break;
345
346 /* if this thread is still alive, wait for it to exit */
347 OS_Thread *t = link->get_thread();
348 if (t != 0)
349 {
350 /* wait for this thread to exit */
351 if (t->wait(timeout) != OSWAIT_EVENT)
352 {
353 /*
354 * the wait timed out or failed - note that we have at
355 * least one thread that didn't exit successfully
356 * within the timeout
357 */
358 ok = FALSE;
359 }
360
361 /* we're done with the thread */
362 t->release_ref();
363 }
364
365 /* delete the link */
366 delete link;
367 }
368
369 /* return the status result */
370 return ok;
371 }
372
373 protected:
374 /* head of thread list */
375 TadsThreadLink *head;
376
377 /* list mutex */
378 OS_Mutex *mu;
379 };
380
381
382
383
384 /* ------------------------------------------------------------------------ */
385 /*
386 * Network service registration.
387 *
388 * The usual way that a client finds a server on the Web is via an Internet
389 * address and a "well-known" port number. For example, any time you
390 * connect to a Web server, you generally connect to port 80, which is the
391 * standard port for HTTP servers.
392 *
393 * TADS games DON'T use these standard well-known ports. This is an
394 * important part of the design, because it allows many TADS games to run
395 * on a single shared server. If each game tried to take over the same
396 * well-known port for its network listener, you could only run one game
397 * per machine (or per network adapter, anyway). Instead of using
398 * well-known ports, then, TADS game servers use port numbers assigned
399 * dynamically by the operating system. A game can't know its port number
400 * until it's actually running. Therefore, we need some mechanism to
401 * convey the port number to the client so that the client knows where to
402 * connect.
403 *
404 * Registration is the solution. When a game starts a server, it registers
405 * that server, by sending its IP address and listening port number to a
406 * registration server. The registration server makes an entry in its
407 * database of active servers, and then makes this information available to
408 * clients through its own well-known port. The registration server CAN
409 * use a well-known port because we only need one registration server per
410 * machine.
411 */
412
413
414 /* ------------------------------------------------------------------------ */
415 /*
416 * Server manager. This is the global object that manages all of the
417 * servers in the process.
418 */
419 class TadsServerManager: public CVmRefCntObj
420 {
421 public:
422 TadsServerManager();
423 ~TadsServerManager();
424
425 /*
426 * Generate a random ID string - this can be used for anything
427 * requiring a universally unique identifier, such as a session ID.
428 *
429 * 'obj' is a pointer to the object on whose behalf we're constructing
430 * the string. This is used to contribute to the randomness of the
431 * result, but can be null if no object is involved.
432 *
433 * This returns an allocated buffer, which the caller must free with
434 * lib_free_str() when done with it.
435 */
436 static char *gen_rand_id(void *obj);
437
438 /* get a random number */
439 ulong rand();
440
441 protected:
442 /* our ISAAC random number generator */
443 struct isaacctx *ic;
444
445 /* resource protection mutex */
446 OS_Mutex *mutex;
447 };
448
449
450 /* ------------------------------------------------------------------------ */
451 /*
452 * Network listener. This object creates a thread that binds to a network
453 * port and listens for incoming connections.
454 */
455 class TadsListener: public CVmRefCntObj
456 {
457 public:
458 /*
459 * Create a web server listener. This binds to the given network port,
460 * then launches the given listener thread to listen for new
461 * connections on the port.
462 */
463 static TadsListener *launch(const char *hostname, ushort portno,
464 class TadsListenerThread *thread);
465
466 /*
467 * Shut down the listener. This sends a control message to the
468 * listener thread telling it to shut down. The listener will close
469 * its network port and exit its thread.
470 *
471 * This returns immediately without waiting for the listener to finish
472 * shutting down. If you want to wait until the thread has exited,
473 * wait for the thread object.
474 */
475 void shutdown();
476
477 /* the listener thread object */
478 class TadsListenerThread *get_thread() const { return thread; }
479
480 protected:
481 /*
482 * construction - this is protected because callers create this object
483 * via the static method launch()
484 */
485 TadsListener(TadsListenerThread *thread);
486
487 /* deletion - protected because we're managed by reference counting */
488 ~TadsListener();
489
490 /* my thread object */
491 class TadsListenerThread *thread;
492 };
493
494 /*
495 * Listener thread. This is the generic class for listener threads; it
496 * must be subclassed for each specific type of network object.
497 */
498 class TadsListenerThread: public OS_Thread
499 {
500 friend class TadsListener;
501 friend class TadsServerThread;
502
503 public:
504 /* construction */
505 TadsListenerThread(OS_Event *quit_evt)
506 {
507 /* no port yet */
508 port = 0;
509
510 /* no error message yet */
511 errmsg = 0;
512
513 /*
514 * use the caller's quit event, if they supplied one, otherwise
515 * create our own; if we create one, it's sticky - once signaled,
516 * it stays signaled, no matter how many threads are waiting on it
517 */
518 if (quit_evt == 0)
519 this->quit_evt = new OS_Event(TRUE);
520 else
521 (this->quit_evt = quit_evt)->add_ref();
522
523 /* create our private shutdown event */
524 shutdown_evt = new OS_Event(TRUE);
525
526 /* create our resource protection mutex */
527 mutex = new OS_Mutex();
528
529 /* we haven't started any server threads yet */
530 servers = 0;
531
532 /* note the time we started running */
533 os_time(&start_time);
534
535 /* start with thread #1 */
536 next_thread_id = 1;
537
538 /* generate a random password */
539 password = TadsServerManager::gen_rand_id(this);
540 }
541
542 /* destruction */
543 ~TadsListenerThread();
544
545 /*
546 * Create the server thread object. This must be subclassed for each
547 * type of server to create the appropriate thread subclass.
548 */
549 virtual class TadsServerThread *create_server_thread(OS_Socket *s) = 0;
550
551 /* get the IP address and port number */
552 int get_local_addr(char *&ip, int &portno) const
553 { return port != 0 ? port->get_local_addr(ip, portno) : 0; }
554
555 /* set the listener port - we assume the caller's reference */
556 void set_port(OS_Listener *p) { port = p; }
557
558 /* main thread entrypoint */
559 void thread_main();
560
561 /*
562 * Check for an error message. If the server encounters an error it
563 * can't recover from, it'll store a status message and exit the
564 * listener thread.
565 */
566 const char *get_errmsg() const { return errmsg; }
567
568 /* generate a human-readable status report listing my threads */
569 void list_threads(struct NetString *buf);
570
571 /* get the control password */
572 const char *get_password() const { return password; }
573
574 /* get the start time as an ASCII string */
575 const char *asc_start_time() const
576 { return asctime(os_localtime(&start_time)); }
577
578 /* get the application-wide 'quit' event object */
579 OS_Event *get_quit_evt() const { return quit_evt; }
580
581 /* get the listener shutdown event */
582 OS_Event *get_shutdown_evt() const { return shutdown_evt; }
583
584 protected:
585 /* add a thread to our list */
586 void add_thread(class TadsServerThread *t);
587
588 /* remove a thread from our list */
589 void remove_thread(class TadsServerThread *t);
590
591 /* time the server started running */
592 os_time_t start_time;
593
594 /*
595 * Password: this is a random string generated at startup, to secure
596 * network access to control functions. The idea is that the server
597 * displays this on its console, so only someone with console access to
598 * the server will be able to also gain remote access to the server
599 * control functions.
600 */
601 char *password;
602
603 /* next thread serial number */
604 int next_thread_id;
605
606 /* our listener port object */
607 OS_Listener *port;
608
609 /*
610 * Application-wide quit event. This is the global event object that
611 * signals application termination. We'll abort any blocking operation
612 * when this event is signaled so that we can promptly terminate the
613 * listener thread when the application is being terminated.
614 */
615 OS_Event *quit_evt;
616
617 /*
618 * Listener shutdown event. This is the local event object that lets
619 * our owner tell us to shut down the listener thread. This only
620 * applies to this thread, not to the rest of the application, so it
621 * can be used to selectively terminate this single listener while
622 * leaving other server threads running.
623 */
624 OS_Event *shutdown_evt;
625
626 /*
627 * error message - if the server encounters an error that it can't
628 * recover from, it will store status information here and shut down
629 */
630 char *errmsg;
631
632 /* head of our list of active server threads */
633 class TadsServerThread *servers;
634
635 /* mutex protecting our shared resources against concurrent access */
636 OS_Mutex *mutex;
637 };
638
639
640 /*
641 * Base class for server threasds.
642 */
643 class TadsServerThread: public OS_Thread
644 {
645 friend class TadsListenerThread;
646
647 public:
648 TadsServerThread(TadsListenerThread *l, OS_Socket *s)
649 {
650 /* we take over the socket reference from the caller */
651 socket = s;
652
653 /* remember the client's IP address */
654 socket->get_peer_addr(client_ip, client_port);
655
656 /* remember the listener thread */
657 listener = l;
658 l->add_ref();
659
660 /* create our resource protection mutex */
661 mutex = new OS_Mutex();
662
663 /* set the initial state string */
664 state = new StringRef("Initializing");
665 }
666
667 ~TadsServerThread()
668 {
669 /* release our resources */
670 socket->release_ref();
671 listener->release_ref();
672 mutex->release_ref();
673 state->release_ref();
674 if (client_ip != 0)
675 t3free(client_ip);
676 }
677
678 /* get the client IP address */
679 const char *get_client_ip() const { return client_ip; }
680 int get_client_port() const { return client_port; }
681
682 /* main thread entrypoint */
683 void thread_main();
684
685 /*
686 * Process a request. The main server loop simply calls this
687 * repeatedly as long as it returns true. This should read a request
688 * from the socket and send the response, then return a success or
689 * failure indication to the caller. Returns true on success, false if
690 * an unrecoverable error occurs. A false return tells the server loop
691 * to close the socket and terminate the thread.
692 */
693 virtual int process_request() = 0;
694
695 /*
696 * Read data from our peer. This blocks until at least one byte is
697 * available, then returns as much data as can be read without
698 * blocking. On success, returns the number of bytes read. On error,
699 * returns -1.
700 *
701 * If 'buf' is null, we'll read and discard data until we've read
702 * 'buflen' bytes.
703 *
704 * 'minlen' gives the minimum number of bytes desired. This can be
705 * less than the buffer length, since we might not know in advance how
706 * many bytes the client will be sending. We'll read up to the buffer
707 * size, but we won't return until we read the minimum size (or
708 * encounter an error or timeout).
709 */
710 long read(char *buf, size_t buflen, long minlen,
711 unsigned long timeout = OS_FOREVER);
712
713 /*
714 * Send data to our peer. This blocks until the request completes, but
715 * we'll abort immediately if the 'quit' event in our listener fires.
716 * Returns true on success, false on error or a 'quit' signal.
717 */
718 int send(const char *buf, size_t len);
719 int send(const char *buf) { return send(buf, strlen(buf)); }
720
721 /* get the last send/receive error from the socket */
722 int last_error() const { return socket->last_error(); }
723
724 /*
725 * Get the state string. The caller must release the reference when
726 * done with it.
727 */
728 StringRef *get_state() const
729 {
730 /* make sure no one changes it under us while we're working */
731 mutex->lock();
732
733 /* make a copy for the caller */
734 StringRef *s = state;
735 s->add_ref();
736
737 /* our copy is safe now */
738 mutex->unlock();
739
740 /* return the caller's copy */
741 return s;
742 }
743
744 /* set the current run state */
745 void set_run_state(const char *s)
746 {
747 /* set up a StringRef for the string */
748 StringRef *r = new StringRef(s);
749
750 /* set it as the new state */
751 set_run_state(r);
752
753 /* done with our reference to the new StringRef */
754 r->release_ref();
755 }
756
757 void set_run_state(StringRef *s)
758 {
759 /* lock against concurrent access while working */
760 mutex->lock();
761
762 /* release the old state string, and save the new one */
763 if (state != 0)
764 state->release_ref();
765 if ((state = s) != 0)
766 s->add_ref();
767
768 /* done with the mutex */
769 mutex->unlock();
770 }
771
772 /* close my socket */
773 void close_socket()
774 {
775 if (socket != 0)
776 socket->close();
777 }
778
779 protected:
780 /*
781 * Thread ID - this is a serial number set by the listener when we
782 * start up, used for human-readable identification. It has no other
783 * significance; in particular, it's NOT an operating system thread
784 * handle or ID.
785 */
786 int thread_id;
787
788 /*
789 * our connection socket - this is the two-way network channel we use
790 * to communicate with our client
791 */
792 OS_Socket *socket;
793
794 /* our listener */
795 TadsListenerThread *listener;
796
797 /* next thread in our listener's list of threads */
798 TadsServerThread *next_server;
799
800 /* resource protection mutex */
801 OS_Mutex *mutex;
802
803 /* current run state message */
804 StringRef *state;
805
806 /* client IP address and port */
807 char *client_ip;
808 int client_port;
809 };
810
811
812 /* ------------------------------------------------------------------------ */
813 /*
814 * HTTP server thread
815 */
816 class TadsHttpServerThread: public TadsServerThread
817 {
818 public:
819 /* construction */
820 TadsHttpServerThread(class TadsHttpListenerThread *l,
821 TadsMessageQueue *q, long ulim, OS_Socket *s);
822
823 /* deletion */
824 ~TadsHttpServerThread();
825
826 /* get my listener thread object */
827 TadsHttpListenerThread *get_listener() const
828 { return (TadsHttpListenerThread *)listener; }
829
830 /* process a request */
831 int process_request();
832
833 /*
834 * Send a simple HTTP response. Returns true on success, false on
835 * error. The status code and mime type strings are required. The
836 * message body is optional; if it's null, we'll simply send the
837 * headers with no body. If there is a message body, we'll send it
838 * with a Content-Length header. The extra headers are optional; if
839 * provided, this must be in standard header format, with each header
840 * (INCLUDING the last one) terminated by a CR-LF (\r\n) sequence. If
841 * this is null we'll only include a set of standard headers describing
842 * the message body (content-type, content-length, cache-control,
843 * connection).
844 */
845 int send_simple(const char *status_code, const char *mime_type,
846 const char *msg_body, size_t msg_len,
847 const char *extra_headers);
848
849 /* send a simple message body */
850 int send_simple(const char *status_code, const char *mime_type,
851 const char *msg_body)
852 {
853 return send_simple(status_code, mime_type,
854 msg_body, strlen(msg_body), 0);
855 }
856
857 /* send the contents of a file as the message body */
858 int send_file(const char *fname, const char *mime_type);
859
860 protected:
861 /*
862 * Read until we reach the desired number of newlines. The states are
863 * 0->base, 1->first CR, 2->first LF, 3->second CR, 4->second LF. To
864 * stop after one contiguous newline, stop at state 2; to stop after
865 * two newlines, stop at state 4.
866 */
867 int read_to_nl(StringRef *dst, long startofs,
868 int init_state, int end_state);
869
870 /* the message queue */
871 TadsMessageQueue *queue;
872
873 /* upload limit */
874 long upload_limit;
875 };
876
877
878 /* ------------------------------------------------------------------------ */
879 /*
880 * HTTP server listener
881 */
882 class TadsHttpListenerThread: public TadsListenerThread
883 {
884 public:
885 TadsHttpListenerThread(vm_obj_id_t srv_obj,
886 class TadsMessageQueue *q, long upload_limit);
887
888 /* our associated server thread class is TadsHttpServer */
889 virtual class TadsServerThread *create_server_thread(OS_Socket *s)
890 { return new TadsHttpServerThread(this, queue, upload_limit, s); }
891
892 /*
893 * Get the HTTPServer object that created the listener.
894 *
895 * For thread safety, this routine should only be called from the main
896 * VM thread. The garbage collector can delete the server object and
897 * thus invalidate the value returned here. The GC runs in the main VM
898 * thread, so it's always safe to interrogate this value from the main
899 * thread.
900 */
901 vm_obj_id_t get_server_obj() const { return srv_obj; }
902
903 /*
904 * Detach from the HTTPServer object. The HTTPServer calls this when
905 * it's about to be deleted by the garbage collector. We have a
906 * reference on the HTTPServer object, but we're not ourselves a
907 * garbage-collected object, so our reference won't keep the HTTPServer
908 * alive. It can thus be collected while we're still pointing to it.
909 * To deal with this, the HTTPServer lets us know when it's about to be
910 * deleted, so that we can clear our reference.
911 *
912 * This routine should only be called from the main VM thread. This is
913 * designed to be called from the HTTPServer object's notify_delete()
914 * method, which is called by the garbage collector, which always runs
915 * in the main VM thread.
916 */
917 void detach_server_obj() { srv_obj = VM_INVALID_OBJ; }
918
919 protected:
920 ~TadsHttpListenerThread();
921
922 /* the message queue we use to handle incoming requests */
923 class TadsMessageQueue *queue;
924
925 /* upload limit for each incoming request */
926 long upload_limit;
927
928 /* the HTTPServer object that owns the listener */
929 vm_obj_id_t srv_obj;
930 };
931
932
933
934 /* ------------------------------------------------------------------------ */
935 /*
936 * XML helper class
937 */
938 class TadsXml
939 {
940 public:
941 /* given an XML buffer, find the end of the <?XML?> prefix */
942 const char *strip_xml_header(const char *buf);
943 };
944
945
946 /* ------------------------------------------------------------------------ */
947 /*
948 * Message queue. Server threads handle requests by sending messages to
949 * the main thread, via the message queue. This approach allows the
950 * network connections to be handled by dedicated threads, while keeping
951 * the byte-code program itself single-threaded. The queue handles the
952 * communications between threads, and also serializes requests so that
953 * they can be serviced by a single thread.
954 */
955
956 /*
957 * Base message object
958 */
959 class TadsMessage: public CVmRefCntObj
960 {
961 public:
962 TadsMessage(const char *typ, OS_Event *quit_evt)
963 {
964 /* remember the message type */
965 this->typ = typ;
966
967 /* we're not in a queue yet */
968 nxt = 0;
969
970 /* set up an event to signal completion of the message */
971 ev = new OS_Event(FALSE);
972 completed = FALSE;
973
974 /* remember the quit event */
975 if ((this->quit_evt = quit_evt) != 0)
976 quit_evt->add_ref();
977 }
978
979 virtual ~TadsMessage()
980 {
981 /* destroy our completion event */
982 ev->release_ref();
983
984 /* forget our quit event */
985 if (quit_evt != 0)
986 quit_evt->release_ref();
987 }
988
989 /*
990 * wait for completion: returns true on success, false if the wait
991 * failed (due to error, timeout, or Quit)
992 */
993 int wait_for_completion(unsigned long timeout)
994 {
995 /* wait on the event, or the quit event */
996 OS_Waitable *w[] = { ev, quit_evt };
997 return OS_Waitable::multi_wait(quit_evt != 0 ? 2 : 1, w, timeout)
998 == OSWAIT_EVENT + 0;
999 }
1000
1001 /* mark the message as completed */
1002 void complete()
1003 {
1004 /* set the completion event */
1005 ev->signal();
1006
1007 /* flag it internally */
1008 completed = TRUE;
1009 }
1010
1011 /* message type - use the name of the class */
1012 const char *typ;
1013
1014 /* next message in queue */
1015 TadsMessage *nxt;
1016
1017 /*
1018 * completion event - this is signaled when the message has been
1019 * processed by the recipient, and if a reply is expected, the reply is
1020 * available
1021 */
1022 OS_Event *ev;
1023
1024 /*
1025 * the 'quit' event - our owner signals this event to tell us to shut
1026 * down the server without doing any more processing
1027 */
1028 OS_Event *quit_evt;
1029
1030 /* flag: has completion been signaled yet? */
1031 int completed;
1032 };
1033
1034 /*
1035 * Safely cast an event message
1036 */
1037 #define cast_tads_message(cls, msg) \
1038 (msg != 0 && strcmp((msg)->typ, #cls) == 0 ? (cls *)msg : 0)
1039
1040 /*
1041 * Network Event message. This is the base class for messages used within
1042 * the TADS 3 getNetEvent() queue for sending messages to the byte-code
1043 * program.
1044 */
1045 class TadsEventMessage: public TadsMessage
1046 {
1047 public:
1048 TadsEventMessage(OS_Event *quit_evt)
1049 : TadsMessage("TadsEventMessage", quit_evt)
1050 { }
1051
1052 /*
1053 * Set up the event object for the byte-code program. This pushes the
1054 * constructor arguments onto the run-time stack, and returns the
1055 * appropriate NetEvent subclass object ID (from G_predef).
1056 *
1057 * '*argc' is to be filled in with the number of constructor arguments
1058 * pushed. Note that the caller will push one additional constructor
1059 * argument giving the request type code (which is common to all
1060 * NetEvent subclass constructors), so this routine doesn't have to
1061 * push that value.
1062 *
1063 * '*evt_code' is to be filled in with the event type code. This is an
1064 * integer giving the type of the event, as defined in the TADS header
1065 * include/tadsnet.h - see the NetEvXxx code list.
1066 *
1067 * Each server type must subclass this to generate the suitable
1068 * information for the request.
1069 */
1070 virtual vm_obj_id_t prep_event_obj(VMG_ int *argc, int *evt_code) = 0;
1071 };
1072
1073 /*
1074 * Message queue.
1075 */
1076 class TadsMessageQueue: public CVmRefCntObj
1077 {
1078 public:
1079 TadsMessageQueue(OS_Event *quit_evt)
1080 {
1081 /* create our mutex object */
1082 mu = new OS_Mutex();
1083
1084 /* create our event - this signals when a message arrives */
1085 ev = new OS_Event(FALSE);
1086
1087 /* no messages in the queue yet */
1088 head = tail = 0;
1089
1090 /* remember my global quit event */
1091 if ((this->quit_evt = quit_evt) != 0)
1092 quit_evt->add_ref();
1093 }
1094
1095 /* are we in the process of shutting down the server? */
1096 int is_quitting()
1097 {
1098 return quit_evt != 0 && quit_evt->test();
1099 }
1100
1101 /*
1102 * Add a message to the queue, without waiting for completion. This is
1103 * a one-way send: posting effectively transfers ownership of the
1104 * reference on the message to the queue, and thence to the recipient.
1105 * The caller thus can't access the message after posting it - for
1106 * their purposes it's effectively gone after they send it. If the
1107 * caller does want to hang onto its own reference to the message after
1108 * sending it, just use add_ref() on the message (BEFORE posting, of
1109 * course, in keeping with the usual ref-count transaction rules).
1110 */
1111 void post(TadsMessage *m)
1112 {
1113 /* synchronize on the mutex */
1114 mu->lock();
1115
1116 /* link the message at the end of the queue */
1117 if (tail != 0)
1118 tail->nxt = m;
1119 else
1120 head = m;
1121 tail = m;
1122 m->nxt = 0;
1123
1124 /*
1125 * if the message doesn't have a 'quit' event, and we do, copy our
1126 * quit event to the message
1127 */
1128 if (m->quit_evt == 0 && quit_evt != 0)
1129 (m->quit_evt = quit_evt)->add_ref();
1130
1131 /* signal that a message is available in the queue */
1132 ev->signal();
1133
1134 /* done with the mutex */
1135 mu->unlock();
1136 }
1137
1138 /*
1139 * Send a message: post it to the queue and wait for completion.
1140 * Returns true on success, false if the wait failed (due to error or
1141 * timeout).
1142 *
1143 * Unlike post(), the caller explicitly keeps its own reference to the
1144 * message with send(), because the message object also provides
1145 * storage for the reply (if any).
1146 */
1147 int send(TadsMessage *m, unsigned long timeout)
1148 {
1149 /*
1150 * Add a reference to the message on behalf of our caller. The
1151 * caller's original reference is about to be transfered to the
1152 * queue (and later to the recipient) via post(), but the caller
1153 * also wants to hang on to the message, so it needs a second
1154 * reference for its own copy.
1155 */
1156 m->add_ref();
1157
1158 /* post the message */
1159 post(m);
1160
1161 /* wait for completion */
1162 return m->wait_for_completion(timeout);
1163 }
1164
1165 /*
1166 * Wait for a message. Blocks until a message is available in the
1167 * queue, or the timeout expires. If there's a message, removes the
1168 * message from the queue and returns OSWAIT_EVENT. Otherwise, returns
1169 * another OSWAIT_xxx code indicating what happened.
1170 *
1171 * The message queue has a 'quit' event object that's used to signal a
1172 * general shutdown. If this event fires, we'll return OSWAIT_EVENT+1
1173 * and fill in *msgp with null.
1174 *
1175 * The message queue also has a 'debug break' event that's used to
1176 * signal that the user wants to pause execution and break into the
1177 * debugger. If this event is signaled, we'll return OSWAIT_EVENT+2
1178 * and fill in *msgp with null.
1179 *
1180 * If we return a message, the caller takes over our reference on it.
1181 * The caller is thus responsible for calling release_ref() when done
1182 * with the message object.
1183 */
1184 int wait(VMG_ unsigned long timeout, TadsMessage **msgp);
1185
1186 /*
1187 * Pull the next message out of the queue without waiting. The caller
1188 * assumes our reference on the message, so they must call Release()
1189 * when done with it.
1190 */
1191 TadsMessage *get()
1192 {
1193 /* synchronize on the mutex */
1194 mu->lock();
1195
1196 /* stash the first message for returning to the caller */
1197 TadsMessage *m = head;
1198
1199 /* pull it off the queue (if there's a message at all) */
1200 if (m != 0)
1201 {
1202 head = head->nxt;
1203 if (head == 0)
1204 tail = 0;
1205 }
1206
1207 /* done with the mutex */
1208 mu->unlock();
1209
1210 /* return the message */
1211 return m;
1212 }
1213
1214 /*
1215 * Abandon a message: release any references the queue has on the given
1216 * message. This can be used if the sender times out waiting for a
1217 * response, to ensure that the queue won't keep the message in memory.
1218 */
1219 void abandon(TadsMessage *msg)
1220 {
1221 /* lock the queue while working */
1222 mu->lock();
1223
1224 /* scan the queue for this message */
1225 TadsMessage *cur, *prv;
1226 for (cur = head, prv = 0 ; cur != 0 ; prv = cur, cur = cur->nxt)
1227 {
1228 /* if this is the message we're looking for, unlink it */
1229 if (cur == msg)
1230 {
1231 /* unlink the message */
1232 if (prv != 0)
1233 prv->nxt = cur->nxt;
1234 else
1235 head = cur->nxt;
1236
1237 /* if it's the tail, move the tail back one */
1238 if (cur == tail)
1239 tail = prv;
1240
1241 /* release our reference on the message */
1242 cur->release_ref();
1243
1244 /* no need to keep looking */
1245 break;
1246 }
1247 }
1248
1249 /* done with the queue lock */
1250 mu->unlock();
1251 }
1252
1253 /*
1254 * Flush the queue: discard any messages in our list.
1255 */
1256 void flush()
1257 {
1258 /* keep going until the queue is empty */
1259 for (;;)
1260 {
1261 /* lock the queue, and pull the first element off the list */
1262 mu->lock();
1263 TadsMessage *m = head;
1264
1265 /* if we got an element, unlink it */
1266 if (m != 0)
1267 {
1268 head = m->nxt;
1269 if (head == 0)
1270 tail = 0;
1271 }
1272
1273 /* unlock the queue */
1274 mu->unlock();
1275
1276 /* if we're out of queue elements, we're done */
1277 if (m == 0)
1278 break;
1279
1280 /* release this message */
1281 m->release_ref();
1282 }
1283 }
1284
1285 /* get my message arrival event */
1286 OS_Event *get_event_obj() { return ev; }
1287
1288 /* get my quit event object */
1289 OS_Event *get_quit_evt() { return quit_evt; }
1290
1291 protected:
1292 /* mutex for access to our statics */
1293 OS_Mutex *mu;
1294
1295 /* event for signaling a message arrival */
1296 OS_Event *ev;
1297
1298 /*
1299 * the server's general 'quit' event - the server signals this event to
1300 * tell message queues to shut down without further processing
1301 */
1302 OS_Event *quit_evt;
1303
1304 /* head/tail of message queue */
1305 TadsMessage *head, *tail;
1306
1307 ~TadsMessageQueue()
1308 {
1309 /* discard any messages still in the queue */
1310 flush();
1311
1312 /* destroy our synchronization resources */
1313 mu->release_ref();
1314 ev->release_ref();
1315 if (quit_evt != 0)
1316 quit_evt->release_ref();
1317 }
1318 };
1319
1320
1321 /* ------------------------------------------------------------------------ */
1322 /*
1323 * HTTP request header.
1324 */
1325 struct TadsHttpRequestHeader
1326 {
1327 /*
1328 * Initialize given the start of a header line; returns a pointer to
1329 * the start of the next header line. This modifies the buffer in
1330 * place: we add a null at the end of the header name, and we add a
1331 * null at the newline at the end of the header.
1332 */
1333 TadsHttpRequestHeader(char *&p, int parse)
1334 {
1335 /* no next item in the list yet */
1336 nxt = 0;
1337
1338 /* the name is always at the start of the line */
1339 name = p;
1340
1341 /* presume we won't find a value - set it to blank */
1342 value = "";
1343
1344 /* parse out the name and value, if desired */
1345 if (parse)
1346 {
1347 /*
1348 * find the end of the header name - it ends at the first
1349 * whitespace or colon character
1350 */
1351 for ( ; *p != '\0' && strchr(":\r\n \t", *p) == 0 ; ++p) ;
1352
1353 /* check what we found */
1354 if (*p == ':')
1355 {
1356 /* found the delimiting colon - null it out and skip spaces */
1357 for (*p++ = '\0' ; isspace(*p) ; ++p) ;
1358
1359 /* the value is the rest of the line */
1360 value = p;
1361 }
1362 else if (isspace(*p))
1363 {
1364 /* stopped at a space - null it out and skip any more spaces */
1365 for (*p++ = '\0' ; isspace(*p) ; ++p) ;
1366
1367 /* make sure we're at the colon */
1368 if (*p == ':')
1369 {
1370 /* skip the colon and any subsequent spaces */
1371 for (++p ; isspace(*p) ; ++p) ;
1372
1373 /* the value starts here */
1374 value = p;
1375 }
1376 }
1377 }
1378
1379 /* find the end of the line */
1380 for ( ; *p != '\0' && (*p != '\r' || *(p+1) != '\n') ; ++p) ;
1381
1382 /* if we found the CR-LF, null-terminate and skip the pair */
1383 if (*p == '\r' && *(p+1) == '\n')
1384 {
1385 *p = '\0';
1386 p += 2;
1387 }
1388 }
1389
1390 ~TadsHttpRequestHeader()
1391 {
1392 /* delete the rest of the list */
1393 if (nxt != 0)
1394 delete nxt;
1395 }
1396
1397 /*
1398 * Simplify multi-line headers into the single-line equivalents
1399 */
1400 static void fix_multiline_headers(StringRef *hdrs, int start_ofs)
1401 {
1402 /*
1403 * Look for CR LF <space>+ <^space> sequences, and delete the line
1404 * breaks in each one.
1405 */
1406 char *p, *dst, *endp = hdrs->getend();
1407 for (dst = p = hdrs->get() + start_ofs ; p < endp ; )
1408 {
1409 /* check for a line break */
1410 if (*p == '\r' && *(p+1) == '\n')
1411 {
1412 /*
1413 * if the next line starts with whitespace, it's a
1414 * continuation line; otherwise it's a new header
1415 */
1416 if (isspace(*(p+2) && *(p+2) != '\r' && *(p+2) != '\n'))
1417 {
1418 /*
1419 * it's a continuation line - replace the CR-LF with a
1420 * single space, then skip all of the whitespace at the
1421 * start of this line
1422 */
1423 *dst++ = ' ';
1424 for (p += 2 ; isspace(*p) && *p != '\r' && *p != '\n' ;
1425 ++p) ;
1426 }
1427 else
1428 {
1429 /* it's not a continuation line, so copy it as-is */
1430 *dst++ = *p++;
1431 *dst++ = *p++;
1432 }
1433 }
1434 else if (*p == '\r' || *p == '\n')
1435 {
1436 /* unpaired CR or LF - convert it to a space */
1437 *dst++ = ' ';
1438 ++p;
1439 }
1440 else
1441 {
1442 /* ordinary character - copy it unchanged */
1443 *dst++ = *p++;
1444 }
1445 }
1446
1447 /* set the new size of the headers */
1448 hdrs->truncate(dst - hdrs->get());
1449 }
1450
1451 /* parse headers from a StringRef starting at the given offset */
1452 static void parse_headers(TadsHttpRequestHeader *&hdr_list,
1453 TadsHttpRequestHeader *&hdr_tail,
1454 int parse_first,
1455 StringRef *str, long ofs)
1456 {
1457 /* fix multiline headers */
1458 fix_multiline_headers(str, ofs);
1459
1460 /* set up at the starting offset */
1461 char *p = str->get() + ofs;
1462
1463 /* if we're already at a blank line, there are no headers */
1464 if (*p == '\0' || *p == '\r' || *p == '\n')
1465 return;
1466
1467 /*
1468 * if there aren't any headers yet, parse the first one; otherwise
1469 * we'll just add to the existing list
1470 */
1471 if (hdr_list == 0)
1472 hdr_list = hdr_tail = new TadsHttpRequestHeader(p, parse_first);
1473
1474 /* now parse until we find a blank line */
1475 while (*p != '\r' && *p != '\n' && *p != '\0')
1476 hdr_tail = hdr_tail->nxt = new TadsHttpRequestHeader(p, TRUE);
1477 }
1478
1479 /* find a header in the list following this item */
1480 const char *find(const char *name)
1481 {
1482 /* scan the list, starting with this element */
1483 for (TadsHttpRequestHeader *h = this ; h != 0 ; h = h->nxt)
1484 {
1485 /* if this name matches, return the value */
1486 if (stricmp(h->name, name) == 0)
1487 return h->value;
1488 }
1489
1490 /* didn't find a match */
1491 return 0;
1492 }
1493
1494 /* name - pointer into a buffer owned by the request object */
1495 const char *name;
1496
1497 /* value - pointer into a buffer owned by the request object */
1498 const char *value;
1499
1500 /* next header in list */
1501 TadsHttpRequestHeader *nxt;
1502 };
1503
1504 /* ------------------------------------------------------------------------ */
1505 /*
1506 * HTTP Request Message.
1507 */
1508 class TadsHttpRequest: public TadsEventMessage
1509 {
1510 public:
1511 TadsHttpRequest(TadsHttpServerThread *t,
1512 const char *verb, size_t verb_len,
1513 StringRef *hdrs, TadsHttpRequestHeader *hdr_list,
1514 StringRef *body, int overflow,
1515 const char *resource_name, size_t res_name_len,
1516 OS_Event *quit_evt)
1517 : TadsEventMessage(quit_evt)
1518 {
1519 /* remember the server thread */
1520 if ((this->thread = t) != 0)
1521 t->add_ref();
1522
1523 /* remember the verb and resource name */
1524 this->verb = new StringRef(verb, verb_len);
1525 this->resource_name = new StringRef(resource_name, res_name_len);
1526
1527 /* keep a copy of the headers */
1528 this->headers = hdrs;
1529 hdrs->add_ref();
1530
1531 /* keep a copy of the body */
1532 this->overflow = overflow;
1533 if ((this->body = body) != 0)
1534 body->add_ref();
1535
1536 /* take ownership of the parsed header list */
1537 this->hdr_list = hdr_list;
1538 }
1539
1540 ~TadsHttpRequest()
1541 {
1542 /* done with our thread and resource name string references */
1543 resource_name->release_ref();
1544 verb->release_ref();
1545 thread->release_ref();
1546 headers->release_ref();
1547 delete hdr_list;
1548 if (body != 0)
1549 body->release_ref();
1550 }
1551
1552 /* mark the request as completed */
1553 void complete();
1554
1555 /*
1556 * Prepare the event object. This creates an HTTPRequest object (the
1557 * intrinsic class representing an incoming HTTP request), and sets up
1558 * a NetRequestEvent (the byte-code object representing a request) to
1559 * wrap it.
1560 */
1561 virtual vm_obj_id_t prep_event_obj(VMG_ int *argc, int *evt_type);
1562
1563 /* server thread */
1564 TadsHttpServerThread *thread;
1565
1566 /* the HTTP verb */
1567 StringRef *verb;
1568
1569 /* the request string */
1570 StringRef *resource_name;
1571
1572 /* buffer containing the headers, parsed into null-delimited strings */
1573 StringRef *headers;
1574
1575 /* list of starts of the headers in the buffer */
1576 TadsHttpRequestHeader *hdr_list;
1577
1578 /* message body, if any */
1579 StringRef *body;
1580
1581 /*
1582 * Flag: the message body exceeded the upload size limit. If this is
1583 * set, body is null, since we discard content that's too large.
1584 */
1585 int overflow;
1586 };
1587
1588 /* ------------------------------------------------------------------------ */
1589 /*
1590 * UI Close Event. In the stand-alone local interpreter configuration,
1591 * where the browser UI is an integrated part of the interpreter, this
1592 * event is sent when the user explicitly closes the UI window. In most
1593 * cases, the game will simply want to terminate when this happens, because
1594 * it indicates that the user has effectively dismissed the application.
1595 */
1596 class TadsUICloseEvent: public TadsEventMessage
1597 {
1598 public:
1599 TadsUICloseEvent(OS_Event *quit_evt) : TadsEventMessage(quit_evt) { }
1600 virtual vm_obj_id_t prep_event_obj(VMG_ int *argc, int *evt_type);
1601 };
1602
1603 #endif /* TADSNET */
1604 #endif /* VMNET_H */
1605