Debian Codegraph @

terps/tads/tads3/osifcnet.h

raw symbols SCIP
1 /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */
2 /*
3 Name
4 osifcnet.h - TADS operating system interfaces for networking and threading
5 Function
6 Virtualizes OS APIs for networking and threading.
7
8 The style of the interface defined here is different from the basic
9 osifc.h function interfaces. Instead, the interfaces are defined via C++
10 classes. This is a more convenient way to represent the facilities in this
11 package, because they all involve resources (network sockets, thread
12 handles, event handles, etc) that have associated sets of operations -
13 which maps very well onto objects and methods.
14
15 We could have used C++'s abstract class mechanism to define a set of
16 public interfaces here that are implemented by system .cpp files. However,
17 that approach isn't very efficient, since it involves run-time virtual
18 method dispatch that truly isn't necessary in this situation (since a given
19 build will be for a single OS, so only that one OS's concrete classes can
20 ever be invoked in that build). Furthermore, as we learned with HTML TADS,
21 that's a somewhat confusing and high-overhead way to set things up for
22 porting.
23
24 So, instead, we define dummy skeletons for the classes, showing the
25 public interfaces that must be implemented. These aren't the real
26 definitions - we #ifdef them out so that they're not actually compiled.
27 The real definitions must be provided by each OS implementation instead.
28 Simply copy the skeleton from this file into your OS file, define the
29 methods listed, and add any additional methods and/or variables that you
30 need for your OS version. You can also add OS-specific base classes as
31 needed. This approach gives you full flexibility in defining the concrete
32 classes, while giving the portable code a predictable set of interfaces.
33 Notes
34 The network API defined here is for the TADS-in-a-browser setup. This
35 includes both the client/server configuration, where the user interface is
36 presented through a web browser on a client machine, but the TADS VM runs
37 on a remote server, and the two talk across an internet connection via
38 HTTP; and the stand-alone browser configuration, where both the browser and
39 the TADS web server are running on the same machine. The latter is really
40 a special case of the former: it's actually just a software bundle that
41 launches the web server and the browser at once, and transparentl to the
42 user, so that the game looks like a simple stand-alone interpreter app to
43 the user.
44
45 For traditional interpreter builds, the network API isn't used, so no
46 implementation is required.
47 Modified
48 04/04/10 MJRoberts - Creation
49 */
50
51 #ifndef OSIFCNET_H
52 #define OSIFCNET_H
53
54 #include "vmglob.h"
55
56
57 /*
58 * Intialize the networking and threading package. This must be called
59 * once at program startup. The OS isn't required to do anything here;
60 * it's just a chance for the OS layer to do any required static/global
61 * initialization. If the OS implementation uses the global thread list
62 * (see TadsThreadList in vmnet.h), it should create the global list object
63 * here.
64 */
65 void os_net_init(class TadsNetConfig *config);
66
67 /*
68 * Clean up the networking and threading package. This must be called once
69 * just before program termination. The OS isn't required to do anything
70 * here; it's just a chance for the OS layer to clean up resources before
71 * quitting.
72 *
73 * If the OS implementation uses the global thread list (see
74 * CTadsThreadList in vmnet.h), it can use this opportunity to do a
75 * wait_all() on the thread list to allow background threads to terminate
76 * gracefully, then it should release its reference on the thread list
77 * object.
78 */
79 void os_net_cleanup();
80
81 /*
82 * Get the local host name, if possible. This should return the EXTERNAL
83 * network name of the local computer (i.e., it shouldn't return
84 * "localhost", but rather the name that other machines on the network can
85 * use to connect to this machine). Copies the host name to the buffer;
86 * returns true if successful, false if not.
87 */
88 int os_get_hostname(char *buf, size_t buflen);
89
90 /*
91 * Get the IP address for the given local host name, if possible. On
92 * success, fills in 'buf' with the IP address in the standard decimal
93 * format ("1.2.3.4") and returns true. On failure, returns false.
94 *
95 * 'host' is a host name for an adapter on the local machine. This
96 * function resolves the external IP address for the host name, which is
97 * the address that other machines on the network use to connect to this
98 * host on the given adapter. Note that this should only be the external
99 * address as far as this machine is concerned. For example, if the
100 * machine is connected to a LAN, and the LAN contains a NAT router that's
101 * connected to the public Internet, this routine does NOT go so far as to
102 * resolve the external address outside the NAT router - it merely returns
103 * the machine's local address on the LAN.
104 *
105 * If 'host' is null, this should return the default adapter's IP address,
106 * if there is such a thing. On a machine with a single adapter, the
107 * default is that single adapter; on a machine with multiple adapters, if
108 * there's a local convention for designating which one is the default, use
109 * the local convention, otherwise the implementation can choose the
110 * default according to its own criteria, or simply pick one arbitrarily.
111 */
112 int os_get_local_ip(char *buf, size_t buflen, const char *host);
113
114
115 /*
116 * Special timeout value for an infinite wait. When this is passed as a
117 * timeout value to the wait() functions, the wait continues indefinitely,
118 * until the desired event occurs.
119 */
120 /* #define OS_FOREVER (define per OS) */
121
122 /*
123 * Event wait results.
124 */
125 #define OSWAIT_TIMEOUT -1 /* timeout expired before the event dired */
126 #define OSWAIT_ERROR -2 /* wait failed with a system error */
127 #define OSWAIT_EVENT 0 /* got the event we were waiting for */
128 /* for a multi-wait, OSWAIT_EVENT+n means the nth event fired */
129 #define OSWAIT_USER 1000 /* user-defined code can use this and above */
130
131 /*
132 * Socket error code. This is the value returned by OS_Socket::send() and
133 * recv() when an error occurs, in lieu of a valid length value. Define
134 * per operating system.
135 */
136 /* #define OS_SOCKET_ERROR (-1) */
137
138 /*
139 * Error values for OS_Socket::last_error(). Define these per OS.
140 *
141 * OS_EWOULDBLOCK - the error code returned from accept(), send(), and
142 * recv() when the socket is in non-blocking mode AND the call can't do any
143 * work without blocking. This tells the caller that they should continue
144 * with asynchronous processing for a while and poll again later.
145 *
146 * OS_ECONNRESET - returned from send(), recv(), and others when the
147 * network peer (on the other side of the socket) has closed its end of the
148 * connection. This means that further communications through the socket
149 * are not possible, since the other side isn't paying attention any more.
150 *
151 * OS_ECONNABORTED - returned from send(), recv(), and others when the
152 * local host has terminated the connection (i.e., some lower-level
153 * software in the network stack - not the application - has decided on its
154 * own to close the socket). This can happen in various situations, such
155 * as when the peer fails to acknowledge a transmission from our side.
156 * From the application's perspective, this is usually equivalent to
157 * OS_ECONNRESET, since in either case we've lost the ability to
158 * communicate with the client due to some kind of interruption outside of
159 * the local machine's control.
160 */
161 /* #define OS_EWOULDBLOCK EWOULDBLOCK */
162 /* #define OS_ECONNRESET ECONNRESET */
163 /* #define OS_ECONNABORTED ECONNABORTED */
164
165 /*
166 * Protected counter. This object maintains an integer count that can be
167 * incremented and decremented. The inc/dec operations are explicitly
168 * atomic, meaning they're thread-safe: it's not necessary to use any
169 * additional access serialization mechanism to perform an increment or
170 * decrement.
171 */
172 #if 0 /* skeleton definition - make a copy for the actual OS definition */
173 class OS_Counter
174 {
175 public:
176 /* initialize with a starting count value */
177 OS_Counter(long c = 1);
178
179 /* get the current counter value */
180 long get() const;
181
182 /*
183 * Increment/decrement. These return the post-update result.
184 *
185 * The entire operation must be atomic. In machine language terms, the
186 * fetch and set must be locked against concurrent access by other
187 * threads or other CPUs.
188 */
189 long inc();
190 long dec();
191 };
192 #endif
193
194 /* ------------------------------------------------------------------------ */
195 /*
196 * IMPORTANT: in your OS-specific header, #include "vmrefcnt.h" here,
197 * immediately after defining class OS_Counter.
198 *
199 * vmrefcnt.h defines generic classes that are used as base classes by OS
200 * interface classes below.
201 */
202 /* ------------------------------------------------------------------------ */
203
204 /*
205 * Waitable object. This is the base class for objects that can be used in
206 * a multi-object wait. A waitable object has two states: ready and not
207 * ready. Waiting for the object blocks the waiting thread as long as the
208 * object is in the not-ready state, and releases the thread (allows it to
209 * continue running) as soon as the object enters the rady state. Waiting
210 * for an object that's already in the ready state simply allows the
211 * calling thread to continue immediately without blocking.
212 */
213 #if 0 /* skeleton definition - make a copy for the actual OS definition */
214 class OS_Waitable
215 {
216 public:
217 OS_Waitable();
218 virtual ~OS_Waitable();
219
220 /*
221 * Wait for the object, with a maximum wait of 'timeout' milliseconds.
222 * Blocks the calling thread until the object is in its ready state, OR
223 * the timeout interval elapses, whichever comes first. At that point
224 * the thread is released and this function returns. If the object is
225 * already in the ready state when this is called, the method returns
226 * immediately.
227 *
228 * If 'timeout' is OS_FOREVER, the wait is indefinite - it continues
229 * until the event occurs, no matter how long that takes.
230 *
231 * Returns an OSWAIT_xxx code to indicate what happened. If the object
232 * is already in the ready state, returns OSWAIT_EVENT immediately. A
233 * timeout value of zero returns OSWAIT_TIMEOUT immediately (without
234 * blocking) if the object isn't ready.
235 */
236 int wait(unsigned long timeout = OS_FOREVER);
237
238 /*
239 * Test to see if the object is ready, without blocking. Returns true
240 * if the object is ready, false if not. If the object is ready,
241 * waiting for the object would immediately release the thread.
242 *
243 * Note that testing some types of objects "consumes" the ready state
244 * and resets the object to not-ready. This is true of auto-reset
245 * event objects.
246 */
247 int test();
248
249 /*
250 * Wait for multiple objects. This blocks until at least one object in
251 * the list is in the ready state, at which point it returns
252 * OSWAIT_OBJECT+N, where N is the array index in 'objs' of an object
253 * that's ready. If the timeout (given in milliseconds) expires before
254 * any objects are ready, we return OSWAIT_TIMEOUT. If the timeout is
255 * omitted, we don't return until an object is ready.
256 *
257 * If multiple objects become ready at the same time, this picks one
258 * and returns its index.
259 *
260 * If any of the objects are auto-reset event objects, the signaled
261 * state of the *returned* object is affected the same way as it would
262 * be for an ordinary wait(). The signaled states of any other objects
263 * involved in the multi_wait are not affected. For example, if you
264 * multi_wait for three auto-reset events, and all three start off in
265 * the signaled state, multi_wait will arbitrarily choose one as the
266 * returned event, and only that one chosen event will be reset by the
267 * multi_wait.
268 */
269 static int multi_wait(int cnt, OS_Waitable **objs,
270 unsigned long timeout = OS_FOREVER);
271 };
272 #endif
273
274 /*
275 * Event. This is a waitable object with two states: signaled and
276 * unsignaled. In the unsignaled state, a thread waiting for the event
277 * blocks until the event becomes signaled, at which point the thread is
278 * released. In the signaled state, a thread waiting for the event simply
279 * continues running without blocking.
280 *
281 * There are two types of event objects: auto-reset and manual-reset.
282 *
283 * An auto-reset event automatically reverts to the unsignaled state as
284 * soon as ONE thread waiting for the event is released. This means that
285 * if multiple threads are waiting for the event, signaling the event will
286 * only release a single thread; the others will continue blocking until
287 * the event is signaled again, at which point one more thread will be
288 * released. An auto-reset event balances signals and waits: one signal
289 * releases one waiting thread. If the event is signaled twice while no
290 * threads are waiting, the next two waits will immediately be released,
291 * and the third wait will block.
292 *
293 * A manual-reset event simply stays signaled once signaled, no matter how
294 * many threads are waiting for it. The event reverts to unsignaled only
295 * when someone manually calls reset().
296 */
297 #if 0 /* skeleton definition - make a copy for the actual OS definition */
298 class OS_Event: public OS_Waitable, public CVmRefCntObj
299 {
300 public:
301 /* construct */
302 OS_Event(int manual_reset);
303
304 /*
305 * Signal the event. In the case of a manual-reset event, this
306 * releases all threads waiting for the event, and leaves the event in
307 * a signaled state until it's explicitly reset. For an auto-reset
308 * event, this releases only one thread waiting for the event and then
309 * automatically resets the event.
310 */
311 void signal();
312
313 /*
314 * Reset the event. For a manual-reset event, this returns the event
315 * to the unsignaled state. This has no effect for an auto-reset
316 * event.
317 */
318 void reset();
319 };
320 #endif
321
322 /*
323 * Mutex - mutual exclusion object. This is used to protect shared
324 * resources from concurrent access by multiple threads.
325 *
326 * You create a mutex to protect a designated set of shared resources; a
327 * typical example is that you create a mutex for each instance of a class,
328 * to protect the member variables of each instance. When a thread is
329 * about to start a series of operation on the shared variables, and that
330 * series of operations is required to be atomic, the thread first locks
331 * the mutex associated with the variables (e.g., if you're about to make
332 * some changes to an object's member variables, you lock the object's
333 * mutex first). Only one thread can hold a mutex lock at a time, so once
334 * you have the mutex lock, you know that any other thread attempting the
335 * same operation would be blocked on its own lock attempt as long as
336 * you're holding the lock, ensuring that no other thread will attempt to
337 * modify the same variables. When you're done with the atomic operation,
338 * you release the mutex to allow other threads to access the variables
339 * again.
340 *
341 * The OS implementation for mutexes should be as lightweight as possible.
342 * It's more efficient in terms of thread concurrency if callers can create
343 * very granular mutexes, to protect specific resources. This means that
344 * callers will want to create many mutexes in a typical system, so the
345 * cost of creating lots of mutexes shouldn't outweigh the efficiency gain
346 * of using lots of them.
347 *
348 * Care should be taken to avoid deadlocks when locking more than one mutex
349 * at a time. The simplest technique for avoiding deadlocks is to use a
350 * fixed order for acquiring any given set of mutexes. For example, if you
351 * have two mutexes A and B, make sure all threads that acquire both will
352 * always acquire A first, then B. This ensures that a thread that
353 * successfully acquires A and then wants to acquire B will not deadlock
354 * with another thread that already locked B and wants to acquire A. Since
355 * the other thread will also always try to lock A before B, the first
356 * thread can be assured that once it has A, no one else who wants both A
357 * and B can already have B, since anyone else wanting both would
358 * necessarily already have A, which the first thread knows can't be the
359 * case because it acquired A.
360 */
361 #if 0 /* skeleton definition - make a copy for the actual OS definition */
362 class OS_Mutex: public CVmRefCntObj
363 {
364 public:
365 OS_Mutex();
366
367 ~OS_Mutex();
368
369 /*
370 * Lock the mutex. Blocks until the mutex is available.
371 */
372 void lock();
373
374 /*
375 * Test the mutex: if the mutex is available, returns true; if not,
376 * returns false. Doesn't block in either case. If the return value
377 * is true, the mutex is acquired as though lock() had been called, so
378 * the caller must use release() when done.
379 */
380 int test();
381
382 /*
383 * Unlock the mutex. This can only be used after a successful lock()
384 * or test(). This releases our lock and makes the mutex available to
385 * other threads.
386 */
387 void unlock();
388 };
389 #endif
390
391 /*
392 * "Core" socket. This is the common base class of data sockets and
393 * listener sockets.
394 *
395 * In the standard Unix socket API, there's really just one kind of socket
396 * object, and its usage as a data or listener socket depends on the way
397 * it's set up. In OO terms, though, the data and listener sockets are
398 * really separate subclasses, with a small part of their interfaces in
399 * common. We've extracted the common parts into this base class.
400 *
401 * Our socket classes in aggregate are just a thin layer implementing the
402 * same model as the Unix socket API. Most modern operating systems have
403 * socket libraries modeled closely on the Unix socket API, so this should
404 * be easily implementable on most systems. We can't use the Unix socket
405 * API directly, because other systems do tend to have idiosyncracies,
406 * despite their overall similarity to the Unix API. Windows is a
407 * particularly good (?) example: a lot of the basic structure of the API
408 * is the same as in Unix, but with a bunch of gratuitous name changes; and
409 * some of the more advanced features, such as non-blocking mode, are
410 * handled rather differently because of deeper differences in the OS.
411 */
412 #if 0 /* skeleton definition - make a copy for the actual OS definition */
413 class OS_CoreSocket: public CVmRefCntObj, public OS_Waitable
414 {
415 public:
416 OS_CoreSocket();
417
418 /* deleting the object closes the underlying system socket */
419 ~OS_CoreSocket() { close(); }
420
421 /*
422 * Close the socket. This releases any system resources associated
423 * with the socket, including any network ports it's using.
424 */
425 void close();
426
427 /*
428 * Set the socket to non-blocking mode.
429 *
430 * In non-blocking mode, any network operation on the socket will
431 * return immediately with OS_SOCKET_ERROR if the operation can't be
432 * completed immediately, and thus would block pending the arrival of
433 * data or completion of a transmission. Specifically:
434 *
435 * - reading a data socket (recv(), in the Unix API) would block if
436 * there are zero bytes available to be read in the inbound buffer
437 *
438 * - writing a data socket (send() in Unix) would block if the outbound
439 * buffer is too full to accommodate all of the bytes being sent
440 *
441 * - listening for a new incoming connection request (accept() in Unix)
442 * would block if there are no pending connection requests
443 *
444 * If one of these functions returns OS_SOCKET_ERROR, the caller should
445 * check the specific error code by calling last_error(). This will
446 * return OS_EWOULDBLOCK when the cause of the error is one of the
447 * above conditions that would normally cause the call to block.
448 *
449 * After an OS_EWOULDBLOCK occurs, the caller can do one of two things.
450 * First, it can simply carry on with other operations; since the
451 * thread isn't blocked waiting for the network operation to complete,
452 * it can do whatever else it wants in the meantime. The thread can
453 * "poll" the socket by attempting the operation again from time to
454 * time to see if it's finally ready. Second, if the thread doesn't
455 * have any other business to transact, it can wait for the socket to
456 * become ready for the desired operation using the socket's
457 * OS_Waitable interface. That blocks the thread the same way that the
458 * same network operation functions would in the default blocking mode,
459 * but provides two extra capabilities that the regular network
460 * functions don't: you can set a timeout so that the thread will only
461 * block for a certain maximum interval, and you can use the multi-wait
462 * interface so that other events of interest will also wake up the
463 * thread if they should occur before the socket is ready.
464 *
465 * Note that the default mode when you create a new socket is blocking
466 * mode. In blocking mode, any of the above blocking conditions do not
467 * cause an error: instead, they simply block the thread until the
468 * network operation completes.
469 */
470 void set_non_blocking();
471
472 /*
473 * In non-blocking mode, the caller must manually reset the socket's
474 * event waiting status after each successful wait.
475 */
476 void reset_event();
477
478 /*
479 * Get the last error for a network operation (for a data socket, send
480 * and receive; for a listener socket, accept). Returns an OS_Exxx
481 * value.
482 */
483 int last_error() const;
484
485 /*
486 * Get my port number. For a listener socket, this is the port on
487 * which we're listening; for a regular data socket, this is the port
488 * number on our side (the local side) of the connection. Returns 0 if
489 * the port hasn't been opened yet.
490 */
491 unsigned short get_port_num();
492
493 /*
494 * Get this socket's local IP address. This returns the IP address of
495 * the network adapter on our side (the local side) of the connection.
496 * For a listening socket, this is the IP address that clients use to
497 * initiate a connection to this server.
498 *
499 * The returned string is allocated. The caller must free the string
500 * when done with it, using lib_free_str().
501 */
502 char *get_ip_addr() const { return lib_copy_str(local_ip); }
503
504 /*
505 * Get the IP address for the given host. The return value is an
506 * allocated buffer that the caller must delete with 'delete[]'. If
507 * the host IP address is unavailable, returns null.
508 *
509 * A null or empty hostname gets the default external IP address for
510 * the local machine. This does NOT return "localhost" or "127.0.0.1",
511 * but rather the external IP that other machines on the same local
512 * area network can use to connect to this machine. Note that this
513 * address is valid on our LAN, but not necessarily on the broader
514 * Internet, since we could be behind a NAT firewall that assigns local
515 * IP addresses within the LAN.
516 */
517 static char *get_host_ip(const char *hostname);
518 };
519 #endif
520
521 /*
522 * Data socket. This is a subclass of the core socket that's used for
523 * basic data transmission. A data socket is a full-duplex communication
524 * channel between this process and another process, which might be running
525 * on the same host or on a remote host connected via a network.
526 *
527 * On the server side, sockets are created by OS_Listener::accept().
528 *
529 * Currently, there is no interface for creating a client-side socket.
530 * Instead, we provide a request-level API for initiating HTTP requests
531 * from the client side (see class OS_HttpRequest).
532 */
533 #if 0 /* skeleton definition - make a copy for the actual OS definition */
534 class OS_Socket: public OS_CoreSocket
535 {
536 public:
537 /*
538 * Construction. Note that callers do not generally create socket
539 * objects directly; instead, these objects are created by other
540 * osifcnet system classes and returned to user code to access. For
541 * example, server sockets are created by OS_Listener::accept().
542 */
543 OS_Socket();
544
545 /*
546 * Send bytes. Returns the number of bytes sent, or OS_SOCKET_ERROR if
547 * an error occurs.
548 *
549 * When the socket is in non-blocking mode, and the buffer is too full
550 * to accept the complete write, this writes nothing and returns
551 * immediately with an error; last_error() will return OS_EWOULDBLOCK.
552 */
553 int send(const char *buf, size_t len);
554
555 /*
556 * Receive bytes. Returns the number of bytes received. If the return
557 * value is 0, it means that the peer has closed its end of the socket
558 * and all buffered data have already been received. If the return
559 * value is negative, it indicates an error; the specific error code
560 * can be obtained from last_error().
561 *
562 * This doesn't necessarily fulfill the complete read request. If
563 * there are fewer bytes immediately available than 'len', this reads
564 * all of the bytes immediately available and returns, indicating the
565 * number of bytes actually transfered. This is the case regardless of
566 * the blocking mode of the socket.
567 *
568 * When the socket is in non-blocking mode, and there are no bytes
569 * available, this returns immediately with an error, and last_error()
570 * will return OS_EWOULDBLOCK.
571 */
572 int recv(char *buf, size_t len);
573
574 /*
575 * Get the IP address and port for our side of the connection. 'ip'
576 * receives an allocated string with the IP address string in decimal
577 * notation ("192.168.115"). We fill in 'port' with our port number.
578 * Returns true on success, false on failure. If we return success,
579 * the caller is responsible for freeing the 'ip' string with
580 * lib_free_str().
581 */
582 int get_local_addr(char *&ip, int &port);
583
584 /*
585 * Get the IP address and port for the network peer to which we're
586 * connected. 'ip' receives an allocated string with the IP address
587 * string in decimal notation ("192.168.1.15"). We fill in 'port' with
588 * the port number on the remote host. Returns true on success, false
589 * on failure. If we return success, the caller is responsible for
590 * freeing the allocated 'ip' string via lib_free_str().
591 */
592 int get_peer_addr(char *&ip, int &port);
593 };
594 #endif
595
596 /*
597 * Listener. This class represents a network listener socket, which is
598 * used to wait for and accept new incoming connections from clients.
599 */
600 #if 0 /* skeleton definition - make a copy for the actual OS definition */
601 class OS_Listener: public OS_CoreSocket
602 {
603 public:
604 /*
605 * Construction. This sets up the object, but doesn't open a listener
606 * port. Call open() to actually open the port.
607 */
608 OS_Listener();
609
610 /*
611 * Open the listener on the given port number. This can be used to
612 * create a server on a well-known port, but it has the drawback that
613 * ports can't be shared, so this will fail if another process is
614 * already using the same port number.
615 *
616 * Returns true on success, false on failure.
617 */
618 int open(const char *hostname, unsigned short port_num);
619
620 /*
621 * Open the listener port, with the port number assigned by the system.
622 * The system will select an available port and assign it to this
623 * listener, so this avoids contention for specific port numbers.
624 * However, it requires some separate means of communicating the port
625 * number to clients, since there's no way for them to know the port
626 * number in advance.
627 *
628 * Returns true on success, false on failure.
629 */
630 int open(const char *hostname);
631
632 /*
633 * Accept the next incoming connection. If the listener is in blocking
634 * mode (the default), and there are no pending requests, this blocks
635 * until the next pending request arrives. In non-blocking mode, this
636 * returns immediately with a null socket if no requests are pending,
637 * and last_error() indicates OS_EWOULDBLOCK.
638 */
639 OS_Socket *accept();
640 };
641 #endif
642
643
644 /*
645 * Thread.
646 *
647 * To define the code to execute for a thread, you subclass this class and
648 * define a concrete implementation for thread_main(). The thread
649 * automatically terminates when thread_main() returns.
650 *
651 * When used as a Waitable object, a thread is in in the "ready" state when
652 * the thread's thread_main() has returned. In other words, waiting for a
653 * thread means that you're waiting for the thread to complete.
654 */
655 #if 0 /* skeleton definition - make a copy for the actual OS definition */
656 class OS_Thread: public CVmWeakRefable, public OS_Waitable
657 {
658 /* the TadsThreadList class must be a friend, if we use it */
659 friend class TadsThreadList;
660
661 public:
662 /*
663 * Construction. This doesn't actually launch the thread; that can't
664 * happen in the base class constructor because the thread entrypoint
665 * might be reached before the construction is completed. Instead,
666 * call launch() to start the system-level thread running.
667 *
668 * If the OS uses the TadsThreadList master list of threads, each new
669 * thread should be registered here through the ThreadList global.
670 * This is optional; it's for the OS layer's benefit, so if the OS
671 * layer doesn't need it, you can omit it.
672 */
673 OS_Thread() { TadsThreadList::add(this); }
674
675 /*
676 * Destruction.
677 *
678 * If the OS uses the ThreadList master list of threads, you should
679 * clean up the master thread list here. The thread list keeps a weak
680 * reference to the thread, and the weak reference is automatically
681 * cleared when we're deleted, so the thread list simply needs to scan
682 * for dead weak refs and clean them up.
683 */
684 ~OS_Thread() { TadsThreadList::clean(); }
685
686 /*
687 * Launch the system thread, and set it up to start running in
688 * thread_main(). Returns true on success, false if the thread
689 * couldn't be started.
690 *
691 * When this returns, the thread may or may not have actually started
692 * executing thread_main(). On most operating systems it's up to the
693 * OS scheduler to decide when to give CPU time to the thread, so the
694 * thread's execution status depends on the OS and on current CPU
695 * conditions in the system. If the caller needs to know that the
696 * thread has started executing, or that the thread has reached some
697 * particular point in its execution, it can easily coordinate this by
698 * creating an event object that it shares with the thread: the thread
699 * signals the event when the desired milestone has been reached, and
700 * the caller waits for the event after creating the thread, ensuring
701 * that the caller won't proceed until the thread has complete the
702 * desired startup steps.
703 */
704 int launch();
705
706 /*
707 * Thread entrypoint routine. Callers must subclass this class and
708 * provide a concrete definition for this method. This method is
709 * called at thread entry.
710 */
711 virtual void thread_main() = 0;
712 };
713 #endif
714
715 /*
716 * HTTP client operations
717 */
718 class OS_HttpClient
719 {
720 public:
721 /*
722 * Perform an HTTP request on a given resource, returning the resource
723 * contents.
724 *
725 * 'opts' is a combination of OptXxx option flags (see below).
726 *
727 * 'verb' is the HTTP verb to perform; this is usually GET, HEAD, POST,
728 * or PUT. 'resource' is the full URL to the resource to be retrieved.
729 * 'portno' is the port number (usually 80). 'ua' is an optional User
730 * Agent string; if this is null, we'll use a default UA string
731 * identifying ourselves as the generic TADS HTTP client.
732 *
733 * 'send_headers' is an optional string of custom headers to send with
734 * the request. The headers are appended to the headers that we
735 * automatically generate. The string must be in the standard "Name:
736 * Value" format, with headers separated by CR-LF sequences. The
737 * overall string can end wtih one or more CR-LF sequences but isn't
738 * required to. Pass null if no custom headers are to be sent.
739 * 'send_headers_len' is the length in bytes of this string.
740 *
741 * If 'payload' is non-null, it contains the payload data to send with
742 * the request. This is for use with POST and PUT to specify the data
743 * to send with the request. For a POST, the payload can be a mix of
744 * form fields and file items. If there are any file items, we'll send
745 * the POST data in the multipart/form-data format; otherwise we'll
746 * send as application/x-www-form-urlencoded. For any verb other than
747 * POST, the payload (if present at all) is limited to a single file
748 * item.
749 *
750 * Special exception: for POST, if the payload consists of a single
751 * payload item with an empty string ("") as the name, we'll assume
752 * that the caller did all of the necessary POST encoding already, and
753 * we'll send that payload item as the entire content body of the
754 * request WITHOUT any further encoding. This allows the caller to
755 * hand-code an x-www-form-urlencoded or multipart/form-data body, or
756 * to use an entirely different encoding for the body. In other words,
757 * we treat a POST payload with a single unnamed payload item exactly
758 * as we treat a payload for PUT or any other non-POST verb.
759 *
760 * Returns the HTTP status code from the server, or an ErrXxx code
761 * defined below if an error occurred on the client side. The ErrXxx
762 * codes are all negative, which distinguishes them from HTTP status
763 * codes.
764 *
765 * If the server sends back a reply body, we'll store the contents of
766 * the reply in the 'reply' object. If provided, this must be a
767 * writable stream object. 'reply' can alternatively be null, in which
768 * case we'll simply discard any reply body. If the request doesn't
769 * return any reply body, but 'reply' is non-null, we'll simply leave
770 * 'reply' unchanged. Note that we don't rewind or truncate the
771 * 'reply' stream object, so the caller has to prepare the object in
772 * the desired initial conditions before calling this method.
773 *
774 * 'headers' is optional. If this is non-null, we'll allocate a buffer
775 * for the headers and store the pointer to the buffer in '*headers'.
776 * This buffer will contain the raw CR-LF delimited header lines from
777 * the reply, with a null terminator. The caller must delete this
778 * memory with delete[]. The header buffer will be returned only if
779 * the request makes it far enough to retrieve headers; if the call
780 * fails at the socket connection level, for example, no headers are
781 * returned.
782 *
783 * 'location' is optional. If this is non-null, AND the request result
784 * is a 301 code ("resource moved"), we'll allocate a copy of the
785 * redirected URL from the HTTP reply and hand it back via *location.
786 * The caller is responsible for freeing this buffer when done with it
787 * via lib_free_str().
788 *
789 * If 'location' is null, and the resource has moved, we'll
790 * automatically follow the redirection link and retrieve the resource
791 * at the redirected location. Any redirection is thus transparent to
792 * the caller when 'location' is null.
793 */
794 static int request(int opts, const char *host, unsigned short portno,
795 const char *verb, const char *resource,
796 const char *send_headers, size_t send_headers_len,
797 class OS_HttpPayload *payload,
798 class CVmDataSource *reply, char **reply_headers,
799 char **location, const char *ua);
800
801 /* option flags for request() */
802 static const int OptHTTPS = 0x0001; /* use https scheme */
803
804 /* non-HTTP status codes for request() */
805 static const int ErrNoMem = -1; /* out of memory */
806 static const int ErrNoConn = -2; /* couldn't connect to host */
807 static const int ErrNet = -3; /* other network/socket error */
808 static const int ErrParams = -4; /* invalid parameters */
809 static const int ErrReadFile = -5; /* can't read payload file contents */
810 static const int ErrWriteFile = -6; /* error writing reply stream */
811 static const int ErrGetHdrs = -7; /* error retrieving reply headers */
812 static const int ErrThread = -8; /* error starting thread */
813 static const int ErrOther = -100; /* other error */
814 };
815
816 /* HTTP request payload item */
817 class OS_HttpPayloadItem
818 {
819 public:
820 /* create as a name/value pair for a form field for a POST */
821 OS_HttpPayloadItem(const char *name, const char *val);
822 OS_HttpPayloadItem(const char *name, size_t name_len,
823 const char *val, size_t val_len);
824
825 /*
826 * Create as a file upload for PUT or POST. 'filename' is the nominal
827 * name for the upload - it doesn't have to correspond to an actual
828 * file system object. The actual payload contents will be taken from
829 * the stream, NOT from a disk file.
830 *
831 * Since 'filename' is only used on the server side to identify the
832 * upload, it's normally a root name only, stripped of any path prefix.
833 * A local path on the client won't mean anything to the server, so
834 * there's no value in sending it, and some people consider doing so a
835 * security risk in that it unnecessarily exposes information about the
836 * local system's directory structure across the network.
837 */
838 OS_HttpPayloadItem(const char *name,
839 const char *filename, const char *mime_type,
840 class CVmDataSource *contents);
841 OS_HttpPayloadItem(const char *name, size_t name_len,
842 const char *filename, size_t filename_len,
843 const char *mime_type, size_t mime_type_len,
844 class CVmDataSource *contents);
845
846 /* delete */
847 ~OS_HttpPayloadItem();
848
849 void init();
850
851 /* field name, for a POST form field or POST form file upload */
852 char *name;
853
854 /*
855 * Field value, for a simple POST form field; for a file, this is the
856 * nominal filename to send to the server.
857 */
858 char *val;
859
860 /* data stream for a PUT file or a POST form file upload */
861 class CVmDataSource *stream;
862
863 /* MIME type, for a PUT file or a POST form file upload */
864 char *mime_type;
865
866 /* next item in the list */
867 OS_HttpPayloadItem *nxt;
868 };
869
870 /*
871 * HTTP request payload data. Use this to package the uploaded data for an
872 * HTTP PUT or POST via OS_HttpClient::request().
873 */
874 class OS_HttpPayload
875 {
876 public:
877 OS_HttpPayload();
878 ~OS_HttpPayload();
879
880 /* add a simple name/value form field */
881 void add(const char *name, const char *val);
882
883 /* add a simple name/value field, in tads-string (VMB_LEN prefix) format */
884 void add_tstr(const char *name, const char *val);
885
886 /* add a simple file upload */
887 void add(const char *name, const char *filename, const char *mime_type,
888 class CVmDataSource *contents);
889 void add(const char *name, size_t name_len,
890 const char *filename, size_t filename_len,
891 const char *mime_type, size_t mime_type_len,
892 class CVmDataSource *contents);
893
894 /* add an item */
895 void add(OS_HttpPayloadItem *item);
896
897 /* get the number of payload items */
898 int count_items() const;
899
900 /*
901 * Is this a multipart payload? This returns true if any of the fields
902 * contain file uploads, false if they're all simple form fields. A
903 * POST consisting entirely of simple form fields is normally sent with
904 * MIME type application/x-www-form-urlencoded, whereas a POST
905 * containing uploaded file data requires multipart/formdata.
906 */
907 int is_multipart() const;
908
909 /*
910 * Create an application/x-www-form-urlencoded buffer from the payload.
911 * This is only applicable when there are no file upload fields. The
912 * returned string is an allocated buffer that the caller is
913 * responsible for freeing when done with it, via t3free().
914 */
915 char *urlencode(size_t &len) const;
916
917 /* get the Nth item */
918 OS_HttpPayloadItem *get(int n) const;
919
920 protected:
921 /* list of payload items */
922 OS_HttpPayloadItem *first_item, *last_item;
923 };
924
925
926 /* ------------------------------------------------------------------------ */
927 /*
928 * Forward declarations
929 */
930 class TadsThreadList;
931
932
933 /* ------------------------------------------------------------------------ */
934 /*
935 * Include the appropriate system-specific header
936 */
937
938 #if defined(GLK)
939 #include "osnetdum.h"
940
941 #elif defined(_WIN32)
942 #include "osnetwin.h"
943
944 #elif defined(UNIX) || defined(FROBTADS)
945 #include "osnetunix.h"
946
947 #else
948 #include "osnetdum.h"
949
950 #endif
951
952
953 /* ------------------------------------------------------------------------ */
954 /*
955 * Connect to the Web UI. The game calls this after it starts its HTTP
956 * server through which it will present its Web UI. This function's job is
957 * to get the client connected to the new HTTP server - in other words, to
958 * navigate the client's browser to the game's HTTP server and load the
959 * game's start page.
960 *
961 * 'message_queue' is an optional message queue to receive notifications
962 * about events in the UI after it's connected. If this is null, no
963 * notifications are sent. If provided, the UI will send the following
964 * event messages to the queue as appropriate:
965 *
966 * - For a stand-alone local configuration (where the browser UI is an
967 * integrated part of the interpreter application - see below), a
968 * TadsUICloseEvent is posted when the user manually closes the UI window.
969 * For the local configuration, the game will usually want to consider this
970 * to be an "end of file" on the input, causing the game to terminate.
971 *
972 * 'addr' is the network address of the server (as a decimal IP string,
973 * e.g. "192.168.1.25", or as a DNS host name), and 'port' is the port
974 * number on which the server is listening. The address will be sent to
975 * the client, and the client will use it to connect to the game, so the
976 * address must be in a form that the client can use to reach our server.
977 * For a client within the same LAN, the local IP address will work. This
978 * won't work in cases where we're behind a NAT firewall and the client is
979 * on the other side of the firewall, though: in those cases, you have to
980 * be sure to use the external Internet IP address. In most cases this
981 * isn't something the game will have to worry about, since the game
982 * generally just takes its listener binding address from the Web server
983 * that launched it - so assuming the Web server is configured correctly,
984 * the game will usually have the right address.
985 *
986 * 'path' is the path to the starting UI page; this is an absolute path on
987 * the server, such as "/webui.htm". 'errmsg' is a pointer to a pointer to
988 * be filled in with an allocated error message string if the operation
989 * fails. 'errmsg' must be set to a string allocated with lib_alloc_str()
990 * or lib_copy_str(); the caller is responsible for freeing this string
991 * with lib_free_str() when done with it. The function must set '*errmsg'
992 * to null if not used. Return true on success, false on failure.
993 *
994 * This function could conceivably be implemented any number of ways, but
995 * we foresee two main implementation strategies, for our two main expected
996 * configurations.
997 *
998 * CONFIGURATION 1: STAND-ALONE PLAY
999 *
1000 * Stand-alone play is where the whole game, client and server, runs on a
1001 * single PC and looks to the user like a single application. The fact
1002 * that there's a network server running is transparent to the user; they
1003 * see what looks like the traditional command-line or HTML TADS setup,
1004 * where there's just a "t3run <game>" command that opens a game window.
1005 *
1006 * In this configuration, connecting to the Web UI is easy. Since both
1007 * client and server are running under one roof, we have control over the
1008 * client UI. We simply need to open a Web browser window and navigate it
1009 * to the game server's start page.
1010 *
1011 * Opening the browser window could consist of actually launching a
1012 * separate Web browser application and passing in the starting URL. This
1013 * is the simplest approach. For a more integrated appearance, the
1014 * application could instead launch its own custom frame window with an
1015 * embedded HTML browser widget filling the interior of the window (the
1016 * "client area" in Windows parlance). In either case, the job is the
1017 * same: launch a browser and point it to the game's HTTP server.
1018 *
1019 * CONFIGURATION 2: CLIENT/SERVER WEB PLAY
1020 *
1021 * Starting a Web-based TADS game presents us with an interesting problem.
1022 * The client initiates the game by connecting to a Web server where the
1023 * game is hosted, and navigating to a "launch" page. The launch page is
1024 * actually a server-side program that starts the TADS 3 Interpreter in a
1025 * child process, passing the .t3 file name to the interpreter. The
1026 * interpreter loads the game and starts executing it. The game then sets
1027 * up an HTTP server which it will use to present its Web UI.
1028 *
1029 * That's where our "interesting problem" comes up. We have a client who
1030 * knows how to talk to the "launch" page, and separately we have the
1031 * game's HTTP server on an ad hoc port assigned by the operating system.
1032 * (For details on why this is an ad hoc port rather than a well-known
1033 * port, see the discussion of Network Service Registration below.) The
1034 * problem is that we now need to connect the client to the server.
1035 *
1036 * The way we solve this is to use that "launch" page as the conduit. When
1037 * the launch page loads, it doesn't immediately send anything back to the
1038 * client. Instead, it stays momentarily silent while it launches the TADS
1039 * Interpreter and lets the game start up. When the launch page starts the
1040 * interpreter, it establishes an interprocess communication channel of
1041 * some kind between itself and the interpreter - for example, a Unix pipe
1042 * would work nicely. When the game calls vmnet_connect_webui(), we use
1043 * this IPC to send our IP address and port number information back to the
1044 * launch page. When the launch page receives this information, it finally
1045 * replies to the client. But rather than sending back just any old HTML,
1046 * it sends back a REDIRECT reply, pointing the client to the game server
1047 * start page. When the client receives the redirect, it turns around and
1048 * loads the start page from the game server.
1049 *
1050 * ---
1051 *
1052 * The implementation of this function is specific to both the
1053 * CONFIGURATION and the SYSTEM. For example, there might be two separate
1054 * Unix implementations: one for stand-alone play that opens an integrated
1055 * frame window containing an embedded browser widget; and the other for
1056 * Web server use that writes the information to stdout for the "launch"
1057 * page script to read.
1058 *
1059 * ---
1060 *
1061 * This routine should reuse the same UI display resources if repeated
1062 * calls are made. For example, in the stand-alone configuration, if we've
1063 * already opened a local browser window in a previous call, and that
1064 * window is still open, we should simply navigate that existing window to
1065 * the new location rather than opening a second window.
1066 *
1067 * The caller should invoke osnet_disconnect_webui() before terminating the
1068 * program. However, calls to osnet_connect_webui() are NOT required to be
1069 * matched by an equal number of calls to the disconnect function. It's
1070 * sufficient to call disconnect once after calling connect several times.
1071 */
1072 int osnet_connect_webui(VMG_ const char *addr, int port, const char *path,
1073 char **errmsg);
1074
1075 /*
1076 * Disconnect from the Web UI. This is used at program termination to
1077 * notify the Web UI that the server program is no longer running, to allow
1078 * it to update or remove its UI, and to release system resources.
1079 *
1080 * If there's no Web UI currently active, this routine should simply return
1081 * without doing anything. It must be harmless to call this routine with
1082 * no previous calls to osnet_connect_webui().
1083 *
1084 * For a stand-alone configuration, this should disconnect from the Web
1085 * UI's window. If the Web UI is running as a separate process, this
1086 * should clean up any IPC channel between the processes, and should update
1087 * the UI to indicate that the game has ended. For example, the UI window
1088 * could show a message to this effect in its title bar or status line, or
1089 * could add a message to the text display.
1090 *
1091 * For a client/server web-play configuration, this usually doesn't do
1092 * anything on the UI side, since the UI is a separate browser (on a
1093 * separate machine) that the user launched and which we're not responsible
1094 * for closing. However, this routine can still take the opportunity to
1095 * free up any local resources allocated is osnet_connect_webui().
1096 *
1097 * If 'close' is true, the web UI should be visually removed. If it's
1098 * running in a separate process, the process can be terminated. If
1099 * 'close' is false, a separate process can be left running for the user to
1100 * close manually. Explicitly closing the UI is appropriate for debuggers
1101 * and other "container" environments where it's reasonable to expect that
1102 * closing the container environment would close the UI window as well.
1103 * Leaving the UI open is appropriate for a stand-alone interpreter in a GUI
1104 * environment; even though the game engine has terminated, we usually want
1105 * to leave the final state of the UI displayed until the user manually
1106 * closes it. This gives the user a chance to read any final messages the
1107 * game displays before terminating.
1108 */
1109 void osnet_disconnect_webui(int close);
1110
1111 /*
1112 * Run the file selector dialog in the *local standalone mode* Web UI.
1113 *
1114 * This is a substitute for the regular os_askfile() routine that the
1115 * interpreter calls when we're running in the local standalone mode. This
1116 * mode is a hybrid of the Web UI and the local interpreter console UI: it
1117 * uses a web browser as the UI, but it uses the local file system for
1118 * storage. The file selection dialog is at the intersection of these two
1119 * axes: the file dialog is a UI element, and our primary UI is the
1120 * browser, but in this configuration the dialog accesses the local file
1121 * system and should present the same UI as it would for the a local
1122 * application. That's why we need a custom function to handle this.
1123 *
1124 * Generally, the implementation should invoke a standard local file
1125 * selector dialog, but show it within the UI context of the Web UI window.
1126 * In the Windows implementation, for example, we run the Web UI in a child
1127 * process that's a customized browser window, so we handle this function
1128 * by sending a message to the child UI process asking it to display a file
1129 * dialog on our behalf. The child process then sends us back a reply
1130 * containing the result of the dialog.
1131 *
1132 * This can be stubbed out with an empty implementation on platforms that
1133 * don't have a standalone Web UI mode.
1134 */
1135 int osnet_askfile(const char *prompt, char *fname_buf, int fname_buf_len,
1136 int prompt_type, int file_type);
1137
1138
1139 #endif /* OSIFCNET_H */