| 1 | /* $Header$ */ |
| 2 | |
| 3 | /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */ |
| 4 | /* |
| 5 | Name |
| 6 | osnetwin.h - TADS networking and threading implementation for Windows |
| 7 | Function |
| 8 | |
| 9 | Notes |
| 10 | |
| 11 | Modified |
| 12 | 04/05/10 MJRoberts - Creation |
| 13 | */ |
| 14 | |
| 15 | #ifndef OSNETWIN_H |
| 16 | #define OSNETWIN_H |
| 17 | |
| 18 | /* include the windows system headers */ |
| 19 | #include <WinSock2.h> |
| 20 | #include <Windows.h> |
| 21 | #include <WinInet.h> |
| 22 | #include <io.h> |
| 23 | |
| 24 | /* include the base header */ |
| 25 | #include "osifcnet.h" |
| 26 | |
| 27 | /* base t3 header */ |
| 28 | #include "t3std.h" |
| 29 | |
| 30 | /* ------------------------------------------------------------------------ */ |
| 31 | /* |
| 32 | * the FOREVER timeout value |
| 33 | */ |
| 34 | #define OS_FOREVER INFINITE |
| 35 | |
| 36 | |
| 37 | /* ------------------------------------------------------------------------ */ |
| 38 | /* |
| 39 | * Host callback functions. These functions must be defined by the host |
| 40 | * application for use by the Windows OS layer. |
| 41 | */ |
| 42 | |
| 43 | /* |
| 44 | * Process a Windows message. The network "wait" functions invoke this |
| 45 | * when messages arrive while waiting for a network event, to ensure that a |
| 46 | * long network wait doesn't freeze the UI. |
| 47 | * |
| 48 | * This should process the message through the same handling that it would |
| 49 | * receive in the application's main event loop. Console-mode |
| 50 | * configurations that don't have event loops can simply provide an empty |
| 51 | * stub for this. |
| 52 | */ |
| 53 | void osnet_host_process_message(MSG *msg); |
| 54 | |
| 55 | |
| 56 | /* ------------------------------------------------------------------------ */ |
| 57 | /* |
| 58 | * Foreground window negotiation. Windows doesn't allow processes to bring |
| 59 | * themselves to the foreground unilaterally, but it does allow a |
| 60 | * foreground application to explicitly yield the foreground. We use our |
| 61 | * pipe control channel to allow Workbench to control whether Workbench or |
| 62 | * the Web UI is in the foreground. |
| 63 | */ |
| 64 | void osnet_webui_yield_foreground(); |
| 65 | void osnet_webui_to_foreground(); |
| 66 | |
| 67 | /* AllowSetForegroundWindow cover (since it's only in Win2k+) */ |
| 68 | BOOL tads_AllowSetForegroundWindow(DWORD pid); |
| 69 | |
| 70 | /* unlink USER32 (for AllowSetForegroundWindow) */ |
| 71 | void tads_unlink_user32(); |
| 72 | |
| 73 | |
| 74 | /* ------------------------------------------------------------------------ */ |
| 75 | /* |
| 76 | * Protected counter. This object maintains an integer count that can be |
| 77 | * incremented and decremented. The inc/dec operations are explicitly |
| 78 | * atomic, meaning they're thread-safe: it's not necessary to use any |
| 79 | * additional access serialization mechanism to perform an increment or |
| 80 | * decrement. |
| 81 | */ |
| 82 | class OS_Counter |
| 83 | { |
| 84 | public: |
| 85 | /* initialize with a starting count value */ |
| 86 | OS_Counter(long c = 1) { cnt = c; } |
| 87 | |
| 88 | /* get the current counter value */ |
| 89 | long get() const { return cnt; } |
| 90 | |
| 91 | /* |
| 92 | * Increment/decrement. These return the post-update result. |
| 93 | * |
| 94 | * The entire operation must be atomic. In machine language terms, the |
| 95 | * fetch and set must be locked against concurrent access by other |
| 96 | * threads or other CPUs. |
| 97 | */ |
| 98 | long inc() { return InterlockedIncrement(&cnt); } |
| 99 | long dec() { return InterlockedDecrement(&cnt); } |
| 100 | |
| 101 | private: |
| 102 | /* reference count */ |
| 103 | LONG cnt; |
| 104 | }; |
| 105 | |
| 106 | /* ------------------------------------------------------------------------ */ |
| 107 | /* |
| 108 | * Include the reference-counted object base classes. |
| 109 | */ |
| 110 | #include "vmrefcnt.h" |
| 111 | |
| 112 | /* ------------------------------------------------------------------------ */ |
| 113 | /* |
| 114 | * Waitable object. This is the base class for objects that can be used in |
| 115 | * a multi-object wait. A waitable object has two states: ready and not |
| 116 | * ready. Waiting for the object blocks the waiting thread as long as the |
| 117 | * object is in the not-ready state, and releases the thread (allows it to |
| 118 | * continue running) as soon as the object enters the rady state. Waiting |
| 119 | * for an object that's already in the ready state simply allows the |
| 120 | * calling thread to continue immediately without blocking. |
| 121 | */ |
| 122 | class OS_Waitable |
| 123 | { |
| 124 | public: |
| 125 | OS_Waitable() |
| 126 | { |
| 127 | /* no handle yet */ |
| 128 | h = 0; |
| 129 | } |
| 130 | |
| 131 | virtual ~OS_Waitable() |
| 132 | { |
| 133 | /* close the handle if we have one */ |
| 134 | if (h != 0) |
| 135 | CloseHandle(h); |
| 136 | } |
| 137 | |
| 138 | /* |
| 139 | * Wait for the object, with a maximum wait of 'timeout' milliseconds. |
| 140 | * Returns an OSWAIT_xxx code to indicate what happened. |
| 141 | */ |
| 142 | virtual int wait(unsigned long timeout = OS_FOREVER) |
| 143 | { |
| 144 | /* if there's no handle, it's an error */ |
| 145 | if (h == 0) |
| 146 | return OSWAIT_ERROR; |
| 147 | |
| 148 | /* do a multi-wait for this one object */ |
| 149 | OS_Waitable *lst[] = { this }; |
| 150 | return multi_wait(1, lst, timeout); |
| 151 | } |
| 152 | |
| 153 | /* |
| 154 | * Test to see if the object is ready, without blocking. Returns true |
| 155 | * if the object is ready, false if not. If the object is ready, |
| 156 | * waiting for the object would immediately release the thread. |
| 157 | * |
| 158 | * Note that testing some types of objects "consumes" the ready state |
| 159 | * and resets the object to not-ready. This is true of auto-reset |
| 160 | * event objects. |
| 161 | */ |
| 162 | virtual int test() |
| 163 | { |
| 164 | /* if there's no object handle, consider it not ready */ |
| 165 | if (h == 0) |
| 166 | return FALSE; |
| 167 | |
| 168 | /* wait for the object with a zero timeout */ |
| 169 | return WaitForSingleObject(h, 0) == WAIT_OBJECT_0; |
| 170 | } |
| 171 | |
| 172 | /* |
| 173 | * Wait for multiple objects. This blocks until at least one event in |
| 174 | * the list is signaled, at which point it returns OSWAIT_OBJECT+N, |
| 175 | * where N is the array index in 'events' of the event that fired. If |
| 176 | * the timeout (given in milliseconds) expires before any events fire, |
| 177 | * we return OSWAIT_TIMEOUT. If the timeout is omitted, we don't |
| 178 | * return until an event fires. |
| 179 | */ |
| 180 | static int multi_wait(int cnt, OS_Waitable **objs, |
| 181 | unsigned long timeout = OS_FOREVER); |
| 182 | |
| 183 | /* get my system object handle */ |
| 184 | HANDLE get_handle() const { return h; } |
| 185 | |
| 186 | protected: |
| 187 | /* |
| 188 | * Process messages. We call this when messages are available in the |
| 189 | * queue for one of our wait functions. |
| 190 | */ |
| 191 | static void process_messages() |
| 192 | { |
| 193 | /* keep going until no more messages are immediately available */ |
| 194 | for (;;) |
| 195 | { |
| 196 | /* if no messages are available, we're done */ |
| 197 | MSG msg; |
| 198 | if (!PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE)) |
| 199 | break; |
| 200 | |
| 201 | /* get the message */ |
| 202 | if (GetMessage(&msg, 0, 0, 0) <= 0) |
| 203 | { |
| 204 | /* Quit message or error - stop now */ |
| 205 | break; |
| 206 | } |
| 207 | |
| 208 | /* send the message to the host app for processing */ |
| 209 | osnet_host_process_message(&msg); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /* |
| 214 | * The waitable handle. All waitable objects on Windows are |
| 215 | * represented by standard Windows handles. |
| 216 | */ |
| 217 | HANDLE h; |
| 218 | }; |
| 219 | |
| 220 | /* ------------------------------------------------------------------------ */ |
| 221 | /* |
| 222 | * Event. This is a waitable object with two states: signaled and |
| 223 | * unsignaled. In the unsignaled state, a thread waiting for the event |
| 224 | * blocks until the event becomes signaled, at which point the thread is |
| 225 | * released. In the signaled state, a thread waiting for the event simply |
| 226 | * continues running without blocking. |
| 227 | * |
| 228 | * There are two types of event objects: auto-reset and manual-reset. |
| 229 | * |
| 230 | * An auto-reset event automatically reverts to the unsignaled state as |
| 231 | * soon as ONE thread waiting for the event is released. This means that |
| 232 | * if multiple threads are waiting for the event, signaling the event will |
| 233 | * only release a single thread; the others will continue blocking until |
| 234 | * the event is signaled again, at which point one more thread will be |
| 235 | * released. An auto-reset event balances signals and waits: one signal |
| 236 | * releases one waiting thread. If the event is signaled twice while no |
| 237 | * threads are waiting, the next two waits will immediately be released, |
| 238 | * and the third wait will block. |
| 239 | * |
| 240 | * A manual-reset event simply stays signaled once signaled, no matter how |
| 241 | * many threads are waiting for it. The event reverts to unsignaled only |
| 242 | * when someone manually calls reset(). |
| 243 | */ |
| 244 | class OS_Event: public OS_Waitable, public CVmRefCntObj |
| 245 | { |
| 246 | public: |
| 247 | /* construct */ |
| 248 | OS_Event(int manual_reset) |
| 249 | { |
| 250 | /* remember the type of object we're creating */ |
| 251 | this->manual_reset = manual_reset; |
| 252 | |
| 253 | /* |
| 254 | * If it's a manual reset event, create an Event object; otherwise |
| 255 | * create a Semaphore object. |
| 256 | */ |
| 257 | this->h = (manual_reset |
| 258 | ? CreateEvent(0, TRUE, FALSE, 0) |
| 259 | : CreateSemaphore(0, 0, 0x7FFFFFFF, 0)); |
| 260 | } |
| 261 | |
| 262 | /* |
| 263 | * Signal the event. In the case of a manual-reset event, this |
| 264 | * releases all threads waiting for the event, and leaves the event in |
| 265 | * a signaled state until it's explicitly reset. For an auto-reset |
| 266 | * event, this releases only one thread waiting for the event and then |
| 267 | * automatically resets the event. |
| 268 | */ |
| 269 | void signal() |
| 270 | { |
| 271 | if (manual_reset) |
| 272 | SetEvent(h); |
| 273 | else |
| 274 | ReleaseSemaphore(h, 1, 0); |
| 275 | } |
| 276 | |
| 277 | /* |
| 278 | * Reset the event. For a manual-reset event, this returns the event |
| 279 | * to the unsignaled state. This has no effect for an auto-reset |
| 280 | * event. |
| 281 | */ |
| 282 | void reset() |
| 283 | { |
| 284 | if (manual_reset) |
| 285 | ResetEvent(h); |
| 286 | } |
| 287 | |
| 288 | private: |
| 289 | /* |
| 290 | * Is this a manual-reset event? True means that this is a manual |
| 291 | * event: signaling the event will release all threads waiting for the |
| 292 | * event, and the event will remain signaled until it's explicitly |
| 293 | * cleared. False means that this is an auto-reset event: signaling |
| 294 | * the event releases only ONE thread waiting for the event, and as |
| 295 | * soon as the thread is released, the system automatically clears the |
| 296 | * event, so no more threads will be released until the next signal. |
| 297 | */ |
| 298 | int manual_reset; |
| 299 | }; |
| 300 | |
| 301 | /* ------------------------------------------------------------------------ */ |
| 302 | /* |
| 303 | * Mutex. |
| 304 | */ |
| 305 | class OS_Mutex: public CVmRefCntObj |
| 306 | { |
| 307 | public: |
| 308 | OS_Mutex() |
| 309 | { |
| 310 | /* create the system mutex object */ |
| 311 | h = CreateMutex(0, FALSE, 0); |
| 312 | } |
| 313 | |
| 314 | ~OS_Mutex() |
| 315 | { |
| 316 | /* destroy the mutex */ |
| 317 | if (h != 0) |
| 318 | CloseHandle(h); |
| 319 | } |
| 320 | |
| 321 | /* |
| 322 | * Lock the mutex. Blocks until the mutex is available. |
| 323 | */ |
| 324 | void lock() { WaitForSingleObject(h, INFINITE); } |
| 325 | |
| 326 | /* |
| 327 | * Test the mutex: if the mutex is available, returns true; if not, |
| 328 | * returns false. Doesn't block in either case. If the return value |
| 329 | * is true, the mutex is acquired as though lock() had been called, so |
| 330 | * the caller must use release() when done. |
| 331 | */ |
| 332 | int test() { return WaitForSingleObject(h, 0) == WAIT_OBJECT_0; } |
| 333 | |
| 334 | /* |
| 335 | * Unlock the mutex. This can only be used after a successful lock() |
| 336 | * or test(). This releases our lock and makes the mutex available to |
| 337 | * other threads. |
| 338 | */ |
| 339 | void unlock() { ReleaseMutex(h); } |
| 340 | |
| 341 | private: |
| 342 | /* the underlying system mutex handle */ |
| 343 | HANDLE h; |
| 344 | }; |
| 345 | |
| 346 | /* ------------------------------------------------------------------------ */ |
| 347 | /* |
| 348 | * Socket error indicator - returned from OS_Socket::send() and recv() if |
| 349 | * an error occurs, in lieu of a valid length value. |
| 350 | */ |
| 351 | #define OS_SOCKET_ERROR SOCKET_ERROR |
| 352 | |
| 353 | /* |
| 354 | * Error values for OS_Socket::last_error(). |
| 355 | */ |
| 356 | #define OS_EWOULDBLOCK WSAEWOULDBLOCK /* send/recv would block */ |
| 357 | #define OS_ECONNRESET WSAECONNRESET /* connection reset by peer */ |
| 358 | #define OS_ECONNABORTED WSAECONNABORTED /* connection aborted on this end */ |
| 359 | |
| 360 | /* ------------------------------------------------------------------------ */ |
| 361 | /* |
| 362 | * Core Socket. This is the common subclass of data sockets and listener |
| 363 | * sockets. |
| 364 | */ |
| 365 | class OS_CoreSocket: public CVmRefCntObj, public OS_Waitable |
| 366 | { |
| 367 | public: |
| 368 | OS_CoreSocket() |
| 369 | { |
| 370 | /* no socket, event, or error yet */ |
| 371 | s = INVALID_SOCKET; |
| 372 | evt = 0; |
| 373 | err = 0; |
| 374 | } |
| 375 | |
| 376 | virtual ~OS_CoreSocket() |
| 377 | { |
| 378 | /* close our socket */ |
| 379 | close(); |
| 380 | } |
| 381 | |
| 382 | /* |
| 383 | * Set the socket to non-blocking mode. In this mode, a send/recv on |
| 384 | * the socket will return immediately with OS_SOCKET_ERROR if the |
| 385 | * socket's data buffer is empty on read or full on write. By default, |
| 386 | * these calls "block": they don't return until at least one byte is |
| 387 | * available to read or there's buffer space for all of the data being |
| 388 | * written. |
| 389 | */ |
| 390 | void set_non_blocking() |
| 391 | { |
| 392 | /* create the event object */ |
| 393 | h = evt = WSACreateEvent(); |
| 394 | |
| 395 | /* |
| 396 | * Windows automatically sets the socket to non-blocking mode when |
| 397 | * it has an associated event object for the relevant operations. |
| 398 | * So, to activate the non-blocking mode, associate our event with |
| 399 | * Read, Write, and Close events on the socket. |
| 400 | */ |
| 401 | WSAEventSelect(s, evt, non_blocking_event_bits()); |
| 402 | } |
| 403 | |
| 404 | /* |
| 405 | * In non-blocking mode, the caller must manually reset the socket's |
| 406 | * event waiting status after each successful wait. |
| 407 | */ |
| 408 | void reset_event() |
| 409 | { |
| 410 | if (evt != 0) |
| 411 | WSAResetEvent(evt); |
| 412 | } |
| 413 | |
| 414 | /* |
| 415 | * Get the last error for a send/receive operation. Returns an OS_Exxx |
| 416 | * value. |
| 417 | */ |
| 418 | int last_error() const { return err; } |
| 419 | |
| 420 | /* close the socket */ |
| 421 | void close() |
| 422 | { |
| 423 | /* close the socket, if it's still open */ |
| 424 | if (s != INVALID_SOCKET) |
| 425 | { |
| 426 | closesocket(s); |
| 427 | s = INVALID_SOCKET; |
| 428 | } |
| 429 | |
| 430 | /* destroy the socket event, if applicable */ |
| 431 | if (evt != 0) |
| 432 | { |
| 433 | WSACloseEvent(evt); |
| 434 | evt = 0; |
| 435 | h = 0; |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /* |
| 440 | * Get the IP address and port for our side of the connection. 'ip' |
| 441 | * receives an allocated string with the IP address string in decimal |
| 442 | * notation ("192.168.115"). We fill in 'port' with our port number. |
| 443 | * Returns true on success, false on failure. If we return success, |
| 444 | * the caller is responsible for freeing the 'ip' string with |
| 445 | * lib_free_str(). |
| 446 | */ |
| 447 | int get_local_addr(char *&ip, int &port) |
| 448 | { |
| 449 | /* set up the address structure */ |
| 450 | sockaddr_storage addr; |
| 451 | int len = sizeof(addr); |
| 452 | |
| 453 | /* get the peer address - return null if this fails */ |
| 454 | if (getsockname(s, (sockaddr *)&addr, &len)) |
| 455 | return FALSE; |
| 456 | |
| 457 | /* parse the address information */ |
| 458 | return parse_addr(addr, len, ip, port); |
| 459 | } |
| 460 | |
| 461 | /* |
| 462 | * Get the IP address and port for the network peer to which we're |
| 463 | * connected. 'ip' receives an allocated string with the IP address |
| 464 | * string in decimal notation ("192.168.1.15"). We fill in 'port' with |
| 465 | * the port number on the remote host. Returns true on success, false |
| 466 | * on failure. If we return success, the caller is responsible for |
| 467 | * freeing the allocated 'ip' string via lib_free_str(). |
| 468 | */ |
| 469 | int get_peer_addr(char *&ip, int &port) |
| 470 | { |
| 471 | /* set up the address structure */ |
| 472 | sockaddr_storage addr; |
| 473 | int len = sizeof(addr); |
| 474 | |
| 475 | /* get the peer address - return null if this fails */ |
| 476 | if (getpeername(s, (sockaddr *)&addr, &len)) |
| 477 | return FALSE; |
| 478 | |
| 479 | /* parse the address */ |
| 480 | return parse_addr(addr, len, ip, port); |
| 481 | } |
| 482 | |
| 483 | /* |
| 484 | * Get the IP address for the local host. The return value is an |
| 485 | * allocated buffer that the caller must delete with 'delete[]'. If |
| 486 | * the host IP address is unavailable, returns null. |
| 487 | */ |
| 488 | static char *get_host_ip(const char *hostname) |
| 489 | { |
| 490 | /* |
| 491 | * Get the local host information. On Windows, we can provide an |
| 492 | * empty string as the host name to tell the system to look the |
| 493 | * name up for us. |
| 494 | */ |
| 495 | struct hostent *local_host = gethostbyname(hostname); |
| 496 | const char *a = |
| 497 | local_host != 0 |
| 498 | ? inet_ntoa(*(struct in_addr *)*local_host->h_addr_list) : 0; |
| 499 | |
| 500 | /* if it's null, return null */ |
| 501 | if (a == 0) |
| 502 | return 0; |
| 503 | |
| 504 | /* make an allocated copy of the string */ |
| 505 | char *buf = new char[strlen(a) + 1]; |
| 506 | strcpy(buf, a); |
| 507 | |
| 508 | /* return the allocated copy */ |
| 509 | return buf; |
| 510 | } |
| 511 | |
| 512 | protected: |
| 513 | /* create a socket object wrapping an existing OS socket handle */ |
| 514 | OS_CoreSocket(SOCKET s) |
| 515 | { |
| 516 | /* remember the socket */ |
| 517 | this->s = s; |
| 518 | |
| 519 | /* no error or non-blocking-mode event object yet */ |
| 520 | err = 0; |
| 521 | evt = 0; |
| 522 | } |
| 523 | |
| 524 | /* parse an address */ |
| 525 | int parse_addr(sockaddr_storage &addr, int len, char *&ip, int &port) |
| 526 | { |
| 527 | /* presume failure */ |
| 528 | ip = 0; |
| 529 | port = 0; |
| 530 | |
| 531 | /* check which family we have */ |
| 532 | if (addr.ss_family == AF_INET) |
| 533 | { |
| 534 | /* get the ip address structure */ |
| 535 | struct sockaddr_in *s = (struct sockaddr_in *)&addr; |
| 536 | |
| 537 | /* get the port and the IP name string */ |
| 538 | port = ntohs(s->sin_port); |
| 539 | char *ipp = inet_ntoa(s->sin_addr); |
| 540 | |
| 541 | /* if we didn't get a name string, abort */ |
| 542 | if (ipp == 0) |
| 543 | return FALSE; |
| 544 | |
| 545 | /* make the caller's copy of the return string */ |
| 546 | ip = lib_copy_str(ipp); |
| 547 | |
| 548 | /* success */ |
| 549 | return TRUE; |
| 550 | } |
| 551 | else |
| 552 | { |
| 553 | /* we don't handle other protocol families */ |
| 554 | return FALSE; |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | /* |
| 559 | * The non-blocking events bits for this socket type. This is a |
| 560 | * combination of FD_xxs bits for WSAEventSelect(). |
| 561 | */ |
| 562 | virtual DWORD non_blocking_event_bits() const = 0; |
| 563 | |
| 564 | /* our underlying system socket handle */ |
| 565 | SOCKET s; |
| 566 | |
| 567 | /* last read/write socket error code */ |
| 568 | int err; |
| 569 | |
| 570 | /* for a non-blocking socket, the socket event object */ |
| 571 | WSAEVENT evt; |
| 572 | }; |
| 573 | |
| 574 | /* ------------------------------------------------------------------------ */ |
| 575 | /* |
| 576 | * Data socket. |
| 577 | */ |
| 578 | class OS_Socket: public OS_CoreSocket |
| 579 | { |
| 580 | friend class OS_Listener; |
| 581 | |
| 582 | public: |
| 583 | /* |
| 584 | * Send bytes. Returns the number of bytes sent, or OS_SOCKET_ERROR if |
| 585 | * an error occurs. |
| 586 | */ |
| 587 | int send(const char *buf, size_t len) |
| 588 | { |
| 589 | /* send the bytes and note the result */ |
| 590 | int ret = ::send(s, buf, len, 0); |
| 591 | |
| 592 | /* if an error occurred, note it */ |
| 593 | err = (ret == SOCKET_ERROR ? WSAGetLastError() : 0); |
| 594 | |
| 595 | /* return the result */ |
| 596 | return ret; |
| 597 | } |
| 598 | |
| 599 | /* |
| 600 | * Receive bytes. If the return value is >0, it's the number of bytes |
| 601 | * received. If 0, it means that the peer has closed its end of the |
| 602 | * socket. If <0, it indicates an error; the specific error code can |
| 603 | * be obtained from last_error(). |
| 604 | */ |
| 605 | int recv(char *buf, size_t len) |
| 606 | { |
| 607 | /* read the bytes and note the result */ |
| 608 | int ret = ::recv(s, buf, len, 0); |
| 609 | |
| 610 | /* if an error occurred, note it */ |
| 611 | err = (ret == SOCKET_ERROR ? WSAGetLastError() : 0); |
| 612 | |
| 613 | /* return the result */ |
| 614 | return ret; |
| 615 | } |
| 616 | |
| 617 | protected: |
| 618 | /* wrap an existing system socket in an OS_Socket object */ |
| 619 | OS_Socket(SOCKET s, struct sockaddr_in *addr, size_t addrlen) |
| 620 | : OS_CoreSocket(s) |
| 621 | { |
| 622 | /* save the socket address, if present */ |
| 623 | if (addr != 0) |
| 624 | { |
| 625 | this->addr = (struct sockaddr_in *)osmalloc(addrlen); |
| 626 | this->addrlen = addrlen; |
| 627 | memcpy(this->addr, addr, addrlen); |
| 628 | } |
| 629 | else |
| 630 | { |
| 631 | this->addr = 0; |
| 632 | this->addrlen = 0; |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | /* |
| 637 | * get the non-blocking event bits - for a data socket, set events for |
| 638 | * read, write, and closing the socket |
| 639 | */ |
| 640 | virtual DWORD non_blocking_event_bits() const |
| 641 | { return FD_READ | FD_WRITE | FD_CLOSE; } |
| 642 | |
| 643 | /* network address of peer */ |
| 644 | struct sockaddr_in *addr; |
| 645 | size_t addrlen; |
| 646 | }; |
| 647 | |
| 648 | /* ------------------------------------------------------------------------ */ |
| 649 | /* |
| 650 | * Listener. This class represents a network listener socket, which is |
| 651 | * used to wait for and accept new incoming connections from clients. |
| 652 | */ |
| 653 | class OS_Listener: public OS_CoreSocket |
| 654 | { |
| 655 | public: |
| 656 | /* |
| 657 | * Construction. This sets up the object, but doesn't open a listener |
| 658 | * port. Call open() to actually open the port. |
| 659 | */ |
| 660 | OS_Listener() { } |
| 661 | |
| 662 | ~OS_Listener() { } |
| 663 | |
| 664 | /* |
| 665 | * Open the listener on the given port number. This can be used to |
| 666 | * create a server on a well-known port, but it has the drawback that |
| 667 | * ports can't be shared, so this will fail if another process is |
| 668 | * already using the same port number. |
| 669 | * |
| 670 | * Returns true on success, false on failure. |
| 671 | */ |
| 672 | int open(const char *hostname, unsigned short port_num) |
| 673 | { |
| 674 | /* create our socket */ |
| 675 | if ((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) |
| 676 | return FALSE; |
| 677 | |
| 678 | /* bind to the given host address */ |
| 679 | char *ip = get_host_ip(hostname); |
| 680 | if (ip == 0) |
| 681 | return FALSE; |
| 682 | |
| 683 | /* |
| 684 | * set up the address request structure to bind to the requested |
| 685 | * port on the local address we just figured |
| 686 | */ |
| 687 | struct sockaddr_in saddr; |
| 688 | saddr.sin_family = AF_INET; |
| 689 | saddr.sin_addr.s_addr = inet_addr(ip); |
| 690 | saddr.sin_port = htons(port_num); |
| 691 | |
| 692 | /* done with the IP address */ |
| 693 | delete [] ip; |
| 694 | |
| 695 | /* try binding */ |
| 696 | if (bind(s, (SOCKADDR *)&saddr, sizeof(saddr))) |
| 697 | return FALSE; |
| 698 | |
| 699 | /* put the socket into the 'listening' state */ |
| 700 | if (listen(s, SOMAXCONN)) |
| 701 | return FALSE; |
| 702 | |
| 703 | /* success */ |
| 704 | return TRUE; |
| 705 | } |
| 706 | |
| 707 | /* |
| 708 | * Open the listener port, with the port number assigned by the system. |
| 709 | * The system will select an available port and assign it to this |
| 710 | * listener, so this avoids contention for specific port numbers. |
| 711 | * However, it requires some separate means of communicating the port |
| 712 | * number to clients, since there's no way for them to know the port |
| 713 | * number in advance. |
| 714 | * |
| 715 | * Returns true on success, false on failure. |
| 716 | */ |
| 717 | int open(const char *hostname) { return open(hostname, 0); } |
| 718 | |
| 719 | /* |
| 720 | * Accept the next incoming connection. If the listener is in blocking |
| 721 | * mode (the default), and there are no pending requests, this blocks |
| 722 | * until the next pending request arrives. In non-blocking mode, this |
| 723 | * returns immediately with a null socket if no requests are pending, |
| 724 | * and last_error() indicates OS_EWOULDBLOCK. |
| 725 | */ |
| 726 | OS_Socket *accept() |
| 727 | { |
| 728 | /* accept a connection on the underlying system socket */ |
| 729 | struct sockaddr_in addr; |
| 730 | int addrlen = sizeof(addr); |
| 731 | SOCKET snew = ::accept(s, (SOCKADDR *)&addr, &addrlen); |
| 732 | |
| 733 | /* check to see if we got a socket */ |
| 734 | if (snew != INVALID_SOCKET) |
| 735 | { |
| 736 | /* success - clear the error memory */ |
| 737 | err = 0; |
| 738 | |
| 739 | /* |
| 740 | * remove the parent event association from the socket - |
| 741 | * winsock sockets essentially inherit the parent event |
| 742 | * settings, but we'll want different event handling for this |
| 743 | * new http socket |
| 744 | */ |
| 745 | WSAEventSelect(snew, 0, 0); |
| 746 | |
| 747 | /* |
| 748 | * Set the "linger" option on close. This helps ensure that we |
| 749 | * transmit any error response to a request that causes the |
| 750 | * server thread to abort. Without this option, winsock will |
| 751 | * sometimes terminate the connection before transmitting the |
| 752 | * final response. |
| 753 | * |
| 754 | * NB - on second thought, I removed this; the winsock |
| 755 | * documentation advises against using this for non-blocking |
| 756 | * sockets, because it can prevent them from ever closing. It |
| 757 | * seems better to set the "graceful close" option (linger |
| 758 | * off). |
| 759 | */ |
| 760 | //struct linger ls = { 1, 1 }; // linger for up to one second |
| 761 | struct linger ls = { 0, 0 }; // graceful close, no wait |
| 762 | setsockopt(snew, SOL_SOCKET, SO_LINGER, |
| 763 | (const char *)&ls, sizeof(ls)); |
| 764 | |
| 765 | /* wrap the socket in an OS_Socket and return the object */ |
| 766 | return new OS_Socket(snew, &addr, addrlen); |
| 767 | } |
| 768 | else |
| 769 | { |
| 770 | /* failed - remember the system error code */ |
| 771 | err = WSAGetLastError(); |
| 772 | |
| 773 | /* return failure */ |
| 774 | return 0; |
| 775 | } |
| 776 | } |
| 777 | |
| 778 | protected: |
| 779 | /* |
| 780 | * get the non-blocking event bits - for a listener socket, set events |
| 781 | * for accept and close |
| 782 | */ |
| 783 | virtual DWORD non_blocking_event_bits() const |
| 784 | { return FD_ACCEPT | FD_CLOSE; } |
| 785 | }; |
| 786 | |
| 787 | |
| 788 | /* ------------------------------------------------------------------------ */ |
| 789 | /* |
| 790 | * Thread. Callers subclass this to define the thread entrypoint routine. |
| 791 | */ |
| 792 | class OS_Thread: public CVmWeakRefable, public OS_Waitable |
| 793 | { |
| 794 | friend class TadsThreadList; |
| 795 | |
| 796 | public: |
| 797 | OS_Thread(); |
| 798 | ~OS_Thread(); |
| 799 | |
| 800 | /* launch the system thread */ |
| 801 | int launch() |
| 802 | { |
| 803 | /* add a reference on behalf of the system thread */ |
| 804 | add_ref(); |
| 805 | |
| 806 | /* create the system thread */ |
| 807 | DWORD tid; |
| 808 | h = CreateThread(0, 0, &sys_thread_main, this, 0, &tid); |
| 809 | |
| 810 | /* if we failed to launch the thread, clean up */ |
| 811 | if (h == 0) |
| 812 | { |
| 813 | /* |
| 814 | * release the extra reference for the system thread, since the |
| 815 | * thread won't be around to claim it |
| 816 | */ |
| 817 | release_ref(); |
| 818 | |
| 819 | /* mark ourselves as done for 'wait' and 'test' */ |
| 820 | failed = TRUE; |
| 821 | } |
| 822 | |
| 823 | /* if we got a handle, we launched the thread successfully */ |
| 824 | return h != 0; |
| 825 | } |
| 826 | |
| 827 | /* |
| 828 | * Thread entrypoint routine. Callers must subclass this class and |
| 829 | * provide a concrete definition for this method. This method is |
| 830 | * called at thread entry. |
| 831 | */ |
| 832 | virtual void thread_main() = 0; |
| 833 | |
| 834 | /* |
| 835 | * Wait and test return true if the thread has exited, or we failed to |
| 836 | * launch the thread. |
| 837 | */ |
| 838 | int wait(unsigned long timeout = OS_FOREVER) |
| 839 | { |
| 840 | /* if the thread failed to launch, consider it done */ |
| 841 | if (failed) |
| 842 | return OSWAIT_EVENT; |
| 843 | |
| 844 | /* otherwise, wait for the thread */ |
| 845 | return OS_Waitable::wait(timeout); |
| 846 | } |
| 847 | int test() |
| 848 | { |
| 849 | /* if the thread failed to launch, consider it done */ |
| 850 | if (failed) |
| 851 | return TRUE; |
| 852 | |
| 853 | /* otherwise do the normal test */ |
| 854 | return OS_Waitable::test(); |
| 855 | } |
| 856 | |
| 857 | private: |
| 858 | /* |
| 859 | * Static entrypoint. This is the routine the system calls directly; |
| 860 | * we then invoke the virtual method with the subclassed thread main. |
| 861 | */ |
| 862 | static DWORD WINAPI sys_thread_main(void *ctx) |
| 863 | { |
| 864 | /* cast the context to the 'this' pointer */ |
| 865 | OS_Thread *thread = (OS_Thread *)ctx; |
| 866 | |
| 867 | /* invoke the subclasses entrypoint */ |
| 868 | thread->thread_main(); |
| 869 | |
| 870 | /* release the system thread's reference on the thread object */ |
| 871 | thread->release_ref(); |
| 872 | |
| 873 | /* return a generic result code */ |
| 874 | return 0; |
| 875 | } |
| 876 | |
| 877 | /* the thread failed to launch */ |
| 878 | int failed; |
| 879 | }; |
| 880 | |
| 881 | /* master thread list global */ |
| 882 | extern class TadsThreadList *G_thread_list; |
| 883 | |
| 884 | |
| 885 | #endif /* OSNETWIN_H */ |