1 /** 2 * Asynchronous socket abstraction. 3 * 4 * License: 5 * This Source Code Form is subject to the terms of 6 * the Mozilla Public License, v. 2.0. If a copy of 7 * the MPL was not distributed with this file, You 8 * can obtain one at http://mozilla.org/MPL/2.0/. 9 * 10 * Authors: 11 * Stéphan Kochen <stephan@kochen.nl> 12 * Vladimir Panteleev <vladimir@thecybershadow.net> 13 * Vincent Povirk <madewokherd@gmail.com> 14 * Simon Arlott 15 */ 16 17 module ae.net.asockets; 18 19 import ae.sys.timing; 20 import ae.utils.math; 21 public import ae.sys.data; 22 23 import std.exception; 24 import std.socket; 25 import std.string : format; 26 public import std.socket : Address, Socket; 27 28 debug(ASOCKETS) import std.stdio; 29 debug(PRINTDATA) static import std.stdio; 30 debug(PRINTDATA) import ae.utils.text : hexDump; 31 private import std.conv : to; 32 33 34 // http://d.puremagic.com/issues/show_bug.cgi?id=7016 35 static import ae.utils.array; 36 37 version(LIBEV) 38 { 39 import deimos.ev; 40 pragma(lib, "ev"); 41 } 42 43 version(Windows) 44 { 45 import core.sys.windows.windows : Sleep; 46 enum USE_SLEEP = true; // avoid convoluted mix of static and runtime conditions 47 } 48 else 49 enum USE_SLEEP = false; 50 51 /// Flags that determine socket wake-up events. 52 int eventCounter; 53 54 version(LIBEV) 55 { 56 // Watchers are a GenericSocket field (as declared in SocketMixin). 57 // Use one watcher per read and write event. 58 // Start/stop those as higher-level code declares interest in those events. 59 // Use the "data" ev_io field to store the parent GenericSocket address. 60 // Also use the "data" field as a flag to indicate whether the watcher is active 61 // (data is null when the watcher is stopped). 62 63 struct SocketManager 64 { 65 private: 66 size_t count; 67 68 extern(C) 69 static void ioCallback(ev_loop_t* l, ev_io* w, int revents) 70 { 71 eventCounter++; 72 auto socket = cast(GenericSocket)w.data; 73 assert(socket, "libev event fired on stopped watcher"); 74 debug (ASOCKETS) writefln("ioCallback(%s, 0x%X)", socket, revents); 75 76 if (revents & EV_READ) 77 socket.onReadable(); 78 else 79 if (revents & EV_WRITE) 80 socket.onWritable(); 81 else 82 assert(false, "Unknown event fired from libev"); 83 84 // TODO? Need to get proper SocketManager instance to call updateTimer on 85 socketManager.updateTimer(false); 86 } 87 88 ev_timer evTimer; 89 MonoTime lastNextEvent = MonoTime.max; 90 91 extern(C) 92 static void timerCallback(ev_loop_t* l, ev_timer* w, int revents) 93 { 94 eventCounter++; 95 debug (ASOCKETS) writefln("Timer callback called."); 96 mainTimer.prod(); 97 98 socketManager.updateTimer(true); 99 debug (ASOCKETS) writefln("Timer callback exiting."); 100 } 101 102 void updateTimer(bool force) 103 { 104 auto nextEvent = mainTimer.getNextEvent(); 105 if (force || lastNextEvent != nextEvent) 106 { 107 debug (ASOCKETS) writefln("Rescheduling timer. Was at %s, now at %s", lastNextEvent, nextEvent); 108 if (nextEvent == MonoTime.max) // Stopping 109 { 110 if (lastNextEvent != MonoTime.max) 111 ev_timer_stop(ev_default_loop(0), &evTimer); 112 } 113 else 114 { 115 auto remaining = mainTimer.getRemainingTime(); 116 while (remaining <= Duration.zero) 117 { 118 debug (ASOCKETS) writefln("remaining=%s, prodding timer.", remaining); 119 mainTimer.prod(); 120 remaining = mainTimer.getRemainingTime(); 121 } 122 ev_tstamp tstamp = remaining.total!"hnsecs" * 1.0 / convert!("seconds", "hnsecs")(1); 123 debug (ASOCKETS) writefln("remaining=%s, ev_tstamp=%s", remaining, tstamp); 124 if (lastNextEvent == MonoTime.max) // Starting 125 { 126 ev_timer_init(&evTimer, &timerCallback, 0., tstamp); 127 ev_timer_start(ev_default_loop(0), &evTimer); 128 } 129 else // Adjusting 130 { 131 evTimer.repeat = tstamp; 132 ev_timer_again(ev_default_loop(0), &evTimer); 133 } 134 } 135 lastNextEvent = nextEvent; 136 } 137 } 138 139 /// Register a socket with the manager. 140 void register(GenericSocket socket) 141 { 142 debug (ASOCKETS) writefln("Registering %s", socket); 143 debug assert(socket.evRead.data is null && socket.evWrite.data is null, "Re-registering a started socket"); 144 auto fd = socket.conn.handle; 145 assert(fd, "Must have fd before socket registration"); 146 ev_io_init(&socket.evRead , &ioCallback, fd, EV_READ ); 147 ev_io_init(&socket.evWrite, &ioCallback, fd, EV_WRITE); 148 count++; 149 } 150 151 /// Unregister a socket with the manager. 152 void unregister(GenericSocket socket) 153 { 154 debug (ASOCKETS) writefln("Unregistering %s", socket); 155 socket.notifyRead = false; 156 socket.notifyWrite = false; 157 count--; 158 } 159 160 public: 161 size_t size() 162 { 163 return count; 164 } 165 166 /// Loop continuously until no sockets are left. 167 void loop() 168 { 169 auto evLoop = ev_default_loop(0); 170 enforce(evLoop, "libev initialization failure"); 171 172 updateTimer(true); 173 debug (ASOCKETS) writeln("ev_run"); 174 ev_run(ev_default_loop(0), 0); 175 } 176 } 177 178 private mixin template SocketMixin() 179 { 180 private ev_io evRead, evWrite; 181 182 private void setWatcherState(ref ev_io ev, bool newValue, int event) 183 { 184 if (!conn) 185 { 186 // Can happen when setting delegates before connecting. 187 return; 188 } 189 190 if (newValue && !ev.data) 191 { 192 // Start 193 ev.data = cast(void*)this; 194 ev_io_start(ev_default_loop(0), &ev); 195 } 196 else 197 if (!newValue && ev.data) 198 { 199 // Stop 200 assert(ev.data is cast(void*)this); 201 ev.data = null; 202 ev_io_stop(ev_default_loop(0), &ev); 203 } 204 } 205 206 /// Interested in read notifications (onReadable)? 207 @property final void notifyRead (bool value) { setWatcherState(evRead , value, EV_READ ); } 208 /// Interested in write notifications (onWritable)? 209 @property final void notifyWrite(bool value) { setWatcherState(evWrite, value, EV_WRITE); } 210 211 debug ~this() 212 { 213 // The LIBEV SocketManager holds no references to registered sockets. 214 // TODO: Add a doubly-linked list? 215 assert(evRead.data is null && evWrite.data is null, "Destroying a registered socket"); 216 } 217 } 218 } 219 else // Use select 220 { 221 struct SocketManager 222 { 223 private: 224 enum FD_SETSIZE = 1024; 225 226 /// List of all sockets to poll. 227 GenericSocket[] sockets; 228 229 /// Debug AA to check for dangling socket references. 230 debug GenericSocket[socket_t] socketHandles; 231 232 /// Register a socket with the manager. 233 void register(GenericSocket conn) 234 { 235 debug (ASOCKETS) writefln("Registering %s (%d total)", conn, sockets.length + 1); 236 assert(!conn.socket.blocking, "Trying to register a blocking socket"); 237 sockets ~= conn; 238 239 debug 240 { 241 auto handle = conn.socket.handle; 242 assert(handle != socket_t.init, "Can't register a closed socket"); 243 assert(handle !in socketHandles, "This socket handle is already registered"); 244 socketHandles[handle] = conn; 245 } 246 } 247 248 /// Unregister a socket with the manager. 249 void unregister(GenericSocket conn) 250 { 251 debug (ASOCKETS) writefln("Unregistering %s (%d total)", conn, sockets.length - 1); 252 253 debug 254 { 255 auto handle = conn.socket.handle; 256 assert(handle != socket_t.init, "Can't unregister a closed socket"); 257 auto pconn = handle in socketHandles; 258 assert(pconn, "This socket handle is not registered"); 259 assert(*pconn is conn, "This socket handle is registered but belongs to another GenericSocket"); 260 socketHandles.remove(handle); 261 } 262 263 foreach (size_t i, GenericSocket j; sockets) 264 if (j is conn) 265 { 266 sockets = sockets[0 .. i] ~ sockets[i + 1 .. sockets.length]; 267 return; 268 } 269 assert(false, "Socket not registered"); 270 } 271 272 void delegate()[] idleHandlers; 273 274 public: 275 size_t size() 276 { 277 return sockets.length; 278 } 279 280 /// Loop continuously until no sockets are left. 281 void loop() 282 { 283 debug (ASOCKETS) writeln("Starting event loop."); 284 285 SocketSet readset, writeset, errorset; 286 size_t sockcount; 287 uint setSize = FD_SETSIZE; // Can't trust SocketSet.max due to Issue 14012 288 readset = new SocketSet(setSize); 289 writeset = new SocketSet(setSize); 290 errorset = new SocketSet(setSize); 291 while (true) 292 { 293 uint minSize = 0; 294 version(Windows) 295 minSize = cast(uint)sockets.length; 296 else 297 { 298 foreach (s; sockets) 299 if (s.socket && s.socket.handle != socket_t.init && s.socket.handle > minSize) 300 minSize = s.socket.handle; 301 } 302 minSize++; 303 304 if (setSize < minSize) 305 { 306 debug (ASOCKETS) writefln("Resizing SocketSets: %d => %d", setSize, minSize*2); 307 setSize = minSize * 2; 308 readset = new SocketSet(setSize); 309 writeset = new SocketSet(setSize); 310 errorset = new SocketSet(setSize); 311 } 312 else 313 { 314 readset.reset(); 315 writeset.reset(); 316 errorset.reset(); 317 } 318 319 sockcount = 0; 320 bool haveActive; 321 debug (ASOCKETS) writeln("Populating sets"); 322 foreach (GenericSocket conn; sockets) 323 { 324 if (!conn.socket) 325 continue; 326 sockcount++; 327 if (!conn.daemon) 328 haveActive = true; 329 330 debug (ASOCKETS) writef("\t%s:", conn); 331 if (conn.notifyRead) 332 { 333 readset.add(conn.socket); 334 debug (ASOCKETS) write(" READ"); 335 } 336 if (conn.notifyWrite) 337 { 338 writeset.add(conn.socket); 339 debug (ASOCKETS) write(" WRITE"); 340 } 341 errorset.add(conn.socket); 342 debug (ASOCKETS) writeln(); 343 } 344 debug (ASOCKETS) 345 { 346 writefln("Sets populated as follows:"); 347 printSets(readset, writeset, errorset); 348 } 349 350 debug (ASOCKETS) writefln("Waiting (%d sockets, %s timer events, %d idle handlers)...", 351 sockcount, 352 mainTimer.isWaiting() ? "with" : "no", 353 idleHandlers.length, 354 ); 355 if (!haveActive && !mainTimer.isWaiting()) 356 { 357 debug (ASOCKETS) writeln("No more sockets or timer events, exiting loop."); 358 break; 359 } 360 361 debug (ASOCKETS) { stdout.flush(); stderr.flush(); } 362 363 int events; 364 if (idleHandlers.length) 365 { 366 if (sockcount==0) 367 events = 0; 368 else 369 events = Socket.select(readset, writeset, errorset, 0.seconds); 370 } 371 else 372 if (USE_SLEEP && sockcount==0) 373 { 374 version(Windows) 375 { 376 auto duration = mainTimer.getRemainingTime().total!"msecs"(); 377 debug (ASOCKETS) writeln("Wait duration: ", duration, " msecs"); 378 if (duration <= 0) 379 duration = 1; // Avoid busywait 380 else 381 if (duration > int.max) 382 duration = int.max; 383 Sleep(cast(int)duration); 384 events = 0; 385 } 386 else 387 assert(0); 388 } 389 else 390 if (mainTimer.isWaiting()) 391 events = Socket.select(readset, writeset, errorset, mainTimer.getRemainingTime()); 392 else 393 events = Socket.select(readset, writeset, errorset); 394 395 debug (ASOCKETS) writefln("%d events fired.", events); 396 397 if (events > 0) 398 { 399 // Handle just one event at a time, as the first 400 // handler might invalidate select()'s results. 401 handleEvent(readset, writeset, errorset); 402 } 403 else 404 if (idleHandlers.length) 405 { 406 import ae.utils.array; 407 auto handler = idleHandlers.shift(); 408 409 // Rotate the idle handler queue before running it, 410 // in case the handler unregisters itself. 411 idleHandlers ~= handler; 412 413 handler(); 414 } 415 416 // Timers may invalidate our select results, so fire them after processing the latter 417 mainTimer.prod(); 418 419 eventCounter++; 420 } 421 } 422 423 debug (ASOCKETS) 424 void printSets(SocketSet readset, SocketSet writeset, SocketSet errorset) 425 { 426 foreach (GenericSocket conn; sockets) 427 { 428 if (!conn.socket) 429 writefln("\t\t%s is unset", conn); 430 else 431 if (readset.isSet(conn.socket)) 432 writefln("\t\t%s is readable", conn); 433 else 434 if (writeset.isSet(conn.socket)) 435 writefln("\t\t%s is writable", conn); 436 else 437 if (errorset.isSet(conn.socket)) 438 writefln("\t\t%s is errored", conn); 439 } 440 } 441 442 void handleEvent(SocketSet readset, SocketSet writeset, SocketSet errorset) 443 { 444 debug (ASOCKETS) 445 { 446 writefln("\tSelect results:"); 447 printSets(readset, writeset, errorset); 448 } 449 450 foreach (GenericSocket conn; sockets) 451 { 452 if (!conn.socket) 453 continue; 454 455 if (readset.isSet(conn.socket)) 456 { 457 debug (ASOCKETS) writefln("\t%s - calling onReadable", conn); 458 return conn.onReadable(); 459 } 460 else 461 if (writeset.isSet(conn.socket)) 462 { 463 debug (ASOCKETS) writefln("\t%s - calling onWritable", conn); 464 return conn.onWritable(); 465 } 466 else 467 if (errorset.isSet(conn.socket)) 468 { 469 debug (ASOCKETS) writefln("\t%s - calling onError", conn); 470 return conn.onError("select() error: " ~ conn.socket.getErrorText()); 471 } 472 } 473 474 assert(false, "select() reported events available, but no registered sockets are set"); 475 } 476 } 477 478 // Use UFCS to allow removeIdleHandler to have a predicate with context 479 void addIdleHandler(ref SocketManager socketManager, void delegate() handler) 480 { 481 foreach (i, idleHandler; socketManager.idleHandlers) 482 assert(handler !is idleHandler); 483 484 socketManager.idleHandlers ~= handler; 485 } 486 487 static bool isFun(T)(T a, T b) { return a is b; } 488 void removeIdleHandler(alias pred=isFun, Args...)(ref SocketManager socketManager, Args args) 489 { 490 foreach (i, idleHandler; socketManager.idleHandlers) 491 if (pred(idleHandler, args)) 492 { 493 import std.algorithm; 494 socketManager.idleHandlers = socketManager.idleHandlers.remove(i); 495 return; 496 } 497 assert(false, "No such idle handler"); 498 } 499 500 private mixin template SocketMixin() 501 { 502 /// Interested in read notifications (onReadable)? 503 bool notifyRead; 504 /// Interested in write notifications (onWritable)? 505 bool notifyWrite; 506 } 507 } 508 509 /// The default socket manager. 510 SocketManager socketManager; 511 512 // *************************************************************************** 513 514 /// General methods for an asynchronous socket. 515 private abstract class GenericSocket 516 { 517 /// Declares notifyRead and notifyWrite. 518 mixin SocketMixin; 519 520 protected: 521 /// The socket this class wraps. 522 Socket conn; 523 524 protected: 525 /// Retrieve the socket class this class wraps. 526 @property final Socket socket() 527 { 528 return conn; 529 } 530 531 void onReadable() 532 { 533 } 534 535 void onWritable() 536 { 537 } 538 539 void onError(string reason) 540 { 541 } 542 543 public: 544 /// allow getting the address of connections that are already disconnected 545 private Address cachedLocalAddress, cachedRemoteAddress; 546 547 /// Don't block the process from exiting. 548 /// TODO: Not implemented with libev 549 bool daemon; 550 551 final @property Address localAddress() 552 { 553 if (cachedLocalAddress !is null) 554 return cachedLocalAddress; 555 else 556 if (conn is null) 557 return null; 558 else 559 return cachedLocalAddress = conn.localAddress(); 560 } 561 562 final @property string localAddressStr() nothrow 563 { 564 try 565 { 566 auto a = localAddress; 567 return a is null ? "[null address]" : a.toString(); 568 } 569 catch (Exception e) 570 return "[error: " ~ e.msg ~ "]"; 571 } 572 573 final @property Address remoteAddress() 574 { 575 if (cachedRemoteAddress !is null) 576 return cachedRemoteAddress; 577 else 578 if (conn is null) 579 return null; 580 else 581 return cachedRemoteAddress = conn.remoteAddress(); 582 } 583 584 final @property string remoteAddressStr() nothrow 585 { 586 try 587 { 588 auto a = remoteAddress; 589 return a is null ? "[null address]" : a.toString(); 590 } 591 catch (Exception e) 592 return "[error: " ~ e.msg ~ "]"; 593 } 594 595 final void setKeepAlive(bool enabled=true, int time=10, int interval=5) 596 { 597 assert(conn, "Attempting to set keep-alive on an uninitialized socket"); 598 if (enabled) 599 { 600 try 601 conn.setKeepAlive(time, interval); 602 catch (SocketFeatureException) 603 conn.setOption(SocketOptionLevel.SOCKET, SocketOption.KEEPALIVE, true); 604 } 605 else 606 conn.setOption(SocketOptionLevel.SOCKET, SocketOption.KEEPALIVE, false); 607 } 608 609 override string toString() const 610 { 611 import std.string; 612 return "%s {this=%s, fd=%s}".format(this.classinfo.name.split(".")[$-1], cast(void*)this, conn ? conn.handle : -1); 613 } 614 } 615 616 // *************************************************************************** 617 618 enum DisconnectType 619 { 620 requested, // initiated by the application 621 graceful, // peer gracefully closed the connection 622 error // abnormal network condition 623 } 624 625 enum ConnectionState 626 { 627 /// The initial state, or the state after a disconnect was fully processed. 628 disconnected, 629 630 /// Name resolution. Currently done synchronously. 631 resolving, 632 633 /// A connection attempt is in progress. 634 connecting, 635 636 /// A connection is established. 637 connected, 638 639 /// Disconnecting in progress. No data can be sent or received at this point. 640 /// We are waiting for queued data to be actually sent before disconnecting. 641 disconnecting, 642 } 643 644 /// Common interface for connections and adapters. 645 interface IConnection 646 { 647 enum MAX_PRIORITY = 4; 648 enum DEFAULT_PRIORITY = 2; 649 650 static const defaultDisconnectReason = "Software closed the connection"; 651 652 /// Get connection state. 653 @property ConnectionState state(); 654 655 /// Has a connection been established? 656 deprecated final @property bool connected() { return state == ConnectionState.connected; } 657 658 /// Are we in the process of disconnecting? (Waiting for data to be flushed) 659 deprecated final @property bool disconnecting() { return state == ConnectionState.disconnecting; } 660 661 /// Queue Data for sending. 662 void send(Data[] data, int priority = DEFAULT_PRIORITY); 663 664 /// ditto 665 final void send(Data datum, int priority = DEFAULT_PRIORITY) 666 { 667 Data[1] data; 668 data[0] = datum; 669 this.send(data); 670 data[] = Data.init; 671 } 672 673 /// Terminate the connection. 674 void disconnect(string reason = defaultDisconnectReason, DisconnectType type = DisconnectType.requested); 675 676 /// Callback setter for when a connection has been established 677 /// (if applicable). 678 alias void delegate() ConnectHandler; 679 @property void handleConnect(ConnectHandler value); /// ditto 680 681 /// Callback setter for when new data is read. 682 alias void delegate(Data data) ReadDataHandler; 683 @property void handleReadData(ReadDataHandler value); /// ditto 684 685 /// Callback setter for when a connection was closed. 686 alias void delegate(string reason, DisconnectType type) DisconnectHandler; 687 @property void handleDisconnect(DisconnectHandler value); /// ditto 688 689 /// Callback setter for when all queued data has been sent. 690 alias void delegate() BufferFlushedHandler; 691 @property void handleBufferFlushed(BufferFlushedHandler value); /// ditto 692 } 693 694 // *************************************************************************** 695 696 class StreamConnection : GenericSocket, IConnection 697 { 698 private: 699 /// Blocks of data larger than this value are passed as unmanaged memory 700 /// (in Data objects). Blocks smaller than this value will be reallocated 701 /// on the managed heap. The disadvantage of placing large objects on the 702 /// managed heap is false pointers; the disadvantage of using Data for 703 /// small objects is wasted slack space due to the page size alignment 704 /// requirement. 705 enum UNMANAGED_THRESHOLD = 256; 706 707 /// Queue of addresses to try connecting to. 708 Address[] addressQueue; 709 710 ConnectionState _state; 711 final @property ConnectionState state(ConnectionState value) { return _state = value; } 712 713 public: 714 /// Get connection state. 715 override @property ConnectionState state() { return _state; } 716 717 protected: 718 abstract sizediff_t doSend(in void[] buffer); 719 abstract sizediff_t doReceive(void[] buffer); 720 721 /// The send buffers. 722 Data[][MAX_PRIORITY+1] outQueue; 723 /// Whether the first item from each queue has been partially sent (and thus can't be cancelled). 724 bool[MAX_PRIORITY+1] partiallySent; 725 726 /// Constructor used by a ServerSocket for new connections 727 this(Socket conn) 728 { 729 this(); 730 this.conn = conn; 731 state = conn is null ? ConnectionState.disconnected : ConnectionState.connected; 732 if (conn) 733 socketManager.register(this); 734 updateFlags(); 735 } 736 737 final void updateFlags() 738 { 739 if (state == ConnectionState.connecting) 740 notifyWrite = true; 741 else 742 notifyWrite = writePending; 743 744 notifyRead = state == ConnectionState.connected && readDataHandler; 745 } 746 747 /// Called when a socket is readable. 748 override void onReadable() 749 { 750 // TODO: use FIONREAD when Phobos gets ioctl support (issue 6649) 751 static ubyte[0x10000] inBuffer; 752 auto received = doReceive(inBuffer); 753 754 if (received == 0) 755 return disconnect("Connection closed", DisconnectType.graceful); 756 757 if (received == Socket.ERROR) 758 { 759 // if (wouldHaveBlocked) 760 // { 761 // debug (ASOCKETS) writefln("\t\t%s: wouldHaveBlocked or recv()", this); 762 // return; 763 // } 764 // else 765 onError("recv() error: " ~ lastSocketError); 766 } 767 else 768 { 769 debug (PRINTDATA) 770 { 771 std.stdio.writefln("== %s <- %s ==", localAddress, remoteAddress); 772 std.stdio.write(hexDump(inBuffer[0 .. received])); 773 std.stdio.stdout.flush(); 774 } 775 776 if (state == ConnectionState.disconnecting) 777 { 778 debug (ASOCKETS) writefln("\t\t%s: Discarding received data because we are disconnecting", this); 779 } 780 else 781 if (!readDataHandler) 782 { 783 debug (ASOCKETS) writefln("\t\t%s: Discarding received data because there is no data handler", this); 784 } 785 else 786 { 787 // Currently, unlike the D1 version of this module, 788 // we will always reallocate read network data. 789 // This disfavours code which doesn't need to store 790 // read data after processing it, but otherwise 791 // makes things simpler and safer all around. 792 793 if (received < UNMANAGED_THRESHOLD) 794 { 795 // Copy to the managed heap 796 readDataHandler(Data(inBuffer[0 .. received].dup)); 797 } 798 else 799 { 800 // Copy to unmanaged memory 801 readDataHandler(Data(inBuffer[0 .. received], true)); 802 } 803 } 804 } 805 } 806 807 /// Called when a socket is writable. 808 override void onWritable() 809 { 810 //scope(success) updateFlags(); 811 onWritableImpl(); 812 updateFlags(); 813 } 814 815 // Work around scope(success) breaking debugger stack traces 816 final private void onWritableImpl() 817 { 818 if (state == ConnectionState.connecting) 819 { 820 state = ConnectionState.connected; 821 822 //debug writefln("[%s] Connected", remoteAddress); 823 try 824 setKeepAlive(); 825 catch (Exception e) 826 return disconnect(e.msg, DisconnectType.error); 827 if (connectHandler) 828 connectHandler(); 829 return; 830 } 831 //debug writefln(remoteAddress(), ": Writable - handler ", handleBufferFlushed?"OK":"not set", ", outBuffer.length=", outBuffer.length); 832 833 foreach (priority, ref queue; outQueue) 834 while (queue.length) 835 { 836 auto pdata = queue.ptr; // pointer to first data 837 838 ptrdiff_t sent = 0; 839 if (pdata.length) 840 { 841 sent = doSend(pdata.contents); 842 debug (ASOCKETS) writefln("\t\t%s: sent %d/%d bytes", this, sent, pdata.length); 843 } 844 else 845 { 846 debug (ASOCKETS) writefln("\t\t%s: empty Data object", this); 847 } 848 849 if (sent == Socket.ERROR) 850 { 851 if (wouldHaveBlocked()) 852 return; 853 else 854 return onError("send() error: " ~ lastSocketError); 855 } 856 else 857 if (sent < pdata.length) 858 { 859 if (sent > 0) 860 { 861 *pdata = (*pdata)[sent..pdata.length]; 862 partiallySent[priority] = true; 863 } 864 return; 865 } 866 else 867 { 868 assert(sent == pdata.length); 869 //debug writefln("[%s] Sent data:", remoteAddress); 870 //debug writefln("%s", hexDump(pdata.contents[0..sent])); 871 pdata.clear(); 872 queue = queue[1..$]; 873 partiallySent[priority] = false; 874 if (queue.length == 0) 875 queue = null; 876 } 877 } 878 879 // outQueue is now empty 880 if (bufferFlushedHandler) 881 bufferFlushedHandler(); 882 if (state == ConnectionState.disconnecting) 883 { 884 debug (ASOCKETS) writefln("Closing @ %s (Delayed disconnect - buffer flushed)", cast(void*)this); 885 close(); 886 } 887 } 888 889 /// Called when an error occurs on the socket. 890 override void onError(string reason) 891 { 892 if (state == ConnectionState.disconnecting) 893 { 894 debug (ASOCKETS) writefln("Socket error while disconnecting @ %s: %s".format(cast(void*)this, reason)); 895 return close(); 896 } 897 898 assert(state == ConnectionState.resolving || state == ConnectionState.connecting || state == ConnectionState.connected); 899 disconnect("Socket error: " ~ reason, DisconnectType.error); 900 } 901 902 this() 903 { 904 } 905 906 public: 907 /// Close a connection. If there is queued data waiting to be sent, wait until it is sent before disconnecting. 908 /// The disconnect handler will be called immediately, even when not all data has been flushed yet. 909 void disconnect(string reason = defaultDisconnectReason, DisconnectType type = DisconnectType.requested) 910 { 911 //scope(success) updateFlags(); // Work around scope(success) breaking debugger stack traces 912 assert(state == ConnectionState.resolving || state == ConnectionState.connecting || state == ConnectionState.connected, "Attempting to disconnect on a %s socket".format(state)); 913 914 if (writePending) 915 { 916 if (type==DisconnectType.requested) 917 { 918 assert(conn, "Attempting to disconnect on an uninitialized socket"); 919 // queue disconnect after all data is sent 920 debug (ASOCKETS) writefln("[%s] Queueing disconnect: %s", remoteAddressStr, reason); 921 state = ConnectionState.disconnecting; 922 //setIdleTimeout(30.seconds); 923 if (disconnectHandler) 924 disconnectHandler(reason, type); 925 updateFlags(); 926 return; 927 } 928 else 929 discardQueues(); 930 } 931 932 debug (ASOCKETS) writefln("Disconnecting @ %s: %s", cast(void*)this, reason); 933 934 if (state == ConnectionState.connecting || state == ConnectionState.connected) 935 close(); 936 else 937 { 938 assert(conn is null, "Registered but %s socket".format(state)); 939 if (state == ConnectionState.resolving) 940 state = ConnectionState.disconnected; 941 } 942 943 if (disconnectHandler) 944 disconnectHandler(reason, type); 945 updateFlags(); 946 } 947 948 private final void close() 949 { 950 assert(conn, "Attempting to close an unregistered socket"); 951 socketManager.unregister(this); 952 conn.close(); 953 conn = null; 954 outQueue[] = null; 955 state = ConnectionState.disconnected; 956 } 957 958 /// Append data to the send buffer. 959 void send(Data[] data, int priority = DEFAULT_PRIORITY) 960 { 961 assert(state == ConnectionState.connected, "Attempting to send on a %s socket".format(state)); 962 outQueue[priority] ~= data; 963 notifyWrite = true; // Fast updateFlags() 964 965 debug (PRINTDATA) 966 { 967 std.stdio.writefln("== %s -> %s ==", localAddress, remoteAddress); 968 foreach (datum; data) 969 if (datum.length) 970 std.stdio.write(hexDump(datum.contents)); 971 else 972 std.stdio.writeln("(empty Data)"); 973 std.stdio.stdout.flush(); 974 } 975 } 976 977 /// ditto 978 alias send = IConnection.send; 979 980 final void clearQueue(int priority) 981 { 982 if (partiallySent[priority]) 983 { 984 assert(outQueue[priority].length > 0); 985 outQueue[priority] = outQueue[priority][0..1]; 986 } 987 else 988 outQueue[priority] = null; 989 updateFlags(); 990 } 991 992 /// Clears all queues, even partially sent content. 993 private final void discardQueues() 994 { 995 foreach (priority; 0..MAX_PRIORITY+1) 996 { 997 outQueue[priority] = null; 998 partiallySent[priority] = false; 999 } 1000 updateFlags(); 1001 } 1002 1003 @property 1004 final bool writePending() 1005 { 1006 foreach (queue; outQueue) 1007 if (queue.length) 1008 return true; 1009 return false; 1010 } 1011 1012 final bool queuePresent(int priority) 1013 { 1014 if (partiallySent[priority]) 1015 { 1016 assert(outQueue[priority].length > 0); 1017 return outQueue[priority].length > 1; 1018 } 1019 else 1020 return outQueue[priority].length > 0; 1021 } 1022 1023 public: 1024 private ConnectHandler connectHandler; 1025 /// Callback for when a connection has been established. 1026 @property final void handleConnect(ConnectHandler value) { connectHandler = value; updateFlags(); } 1027 1028 private ReadDataHandler readDataHandler; 1029 /// Callback for incoming data. 1030 /// Data will not be received unless this handler is set. 1031 @property final void handleReadData(ReadDataHandler value) { readDataHandler = value; updateFlags(); } 1032 1033 private DisconnectHandler disconnectHandler; 1034 /// Callback for when a connection was closed. 1035 @property final void handleDisconnect(DisconnectHandler value) { disconnectHandler = value; updateFlags(); } 1036 1037 /// Callback setter for when all queued data has been sent. 1038 private BufferFlushedHandler bufferFlushedHandler; 1039 @property final void handleBufferFlushed(BufferFlushedHandler value) { bufferFlushedHandler = value; updateFlags(); } 1040 } 1041 1042 // *************************************************************************** 1043 1044 /// A POSIX file stream. 1045 /// Allows adding a file (e.g. stdin/stdout) to the socket manager. 1046 /// Does not dup the given file descriptor, so "disconnecting" this connection 1047 /// will close it. 1048 version (Posix) 1049 class FileConnection : StreamConnection 1050 { 1051 this(int fileno) 1052 { 1053 auto conn = new Socket(cast(socket_t)fileno, AddressFamily.UNSPEC); 1054 conn.blocking = false; 1055 super(conn); 1056 } 1057 1058 protected: 1059 import core.sys.posix.unistd : read, write; 1060 1061 override sizediff_t doSend(in void[] buffer) 1062 { 1063 return write(socket.handle, buffer.ptr, buffer.length); 1064 } 1065 1066 override sizediff_t doReceive(void[] buffer) 1067 { 1068 return read(socket.handle, buffer.ptr, buffer.length); 1069 } 1070 } 1071 1072 // *************************************************************************** 1073 1074 /// An asynchronous TCP connection. 1075 class TcpConnection : StreamConnection 1076 { 1077 protected: 1078 this(Socket conn) 1079 { 1080 super(conn); 1081 } 1082 1083 override sizediff_t doSend(in void[] buffer) 1084 { 1085 return conn.send(buffer); 1086 } 1087 1088 override sizediff_t doReceive(void[] buffer) 1089 { 1090 return conn.receive(buffer); 1091 } 1092 1093 final void tryNextAddress() 1094 { 1095 assert(state == ConnectionState.connecting); 1096 auto address = addressQueue[0]; 1097 addressQueue = addressQueue[1..$]; 1098 1099 try 1100 { 1101 conn = new Socket(address.addressFamily(), SocketType.STREAM, ProtocolType.TCP); 1102 conn.blocking = false; 1103 1104 socketManager.register(this); 1105 updateFlags(); 1106 debug (ASOCKETS) writefln("Attempting connection to %s", address.toString()); 1107 conn.connect(address); 1108 } 1109 catch (SocketException e) 1110 return onError("Connect error: " ~ e.msg); 1111 } 1112 1113 /// Called when an error occurs on the socket. 1114 override void onError(string reason) 1115 { 1116 if (state == ConnectionState.connecting && addressQueue.length) 1117 { 1118 socketManager.unregister(this); 1119 conn.close(); 1120 conn = null; 1121 1122 return tryNextAddress(); 1123 } 1124 1125 super.onError(reason); 1126 } 1127 1128 public: 1129 /// Default constructor 1130 this() 1131 { 1132 debug (ASOCKETS) writefln("New TcpConnection @ %s", cast(void*)this); 1133 } 1134 1135 /// Start establishing a connection. 1136 final void connect(string host, ushort port) 1137 { 1138 assert(host.length, "Empty host"); 1139 assert(port, "No port specified"); 1140 1141 debug (ASOCKETS) writefln("Connecting to %s:%s", host, port); 1142 assert(state == ConnectionState.disconnected, "Attempting to connect on a %s socket".format(state)); 1143 assert(!conn); 1144 1145 state = ConnectionState.resolving; 1146 1147 try 1148 { 1149 addressQueue = getAddress(host, port); 1150 enforce(addressQueue.length, "No addresses found"); 1151 debug (ASOCKETS) 1152 { 1153 writefln("Resolved to %s addresses:", addressQueue.length); 1154 foreach (address; addressQueue) 1155 writefln("- %s", address.toString()); 1156 } 1157 1158 state = ConnectionState.connecting; 1159 if (addressQueue.length > 1) 1160 { 1161 import std.random : randomShuffle; 1162 randomShuffle(addressQueue); 1163 } 1164 } 1165 catch (SocketException e) 1166 return onError("Lookup error: " ~ e.msg); 1167 1168 tryNextAddress(); 1169 } 1170 1171 } 1172 1173 // *************************************************************************** 1174 1175 /// An asynchronous TCP connection server. 1176 final class TcpServer 1177 { 1178 private: 1179 /// Class that actually performs listening on a certain address family 1180 final class Listener : GenericSocket 1181 { 1182 this(Socket conn) 1183 { 1184 debug (ASOCKETS) writefln("New Listener @ %s", cast(void*)this); 1185 this.conn = conn; 1186 socketManager.register(this); 1187 } 1188 1189 /// Called when a socket is readable. 1190 override void onReadable() 1191 { 1192 debug (ASOCKETS) writefln("Accepting connection from listener @ %s", cast(void*)this); 1193 Socket acceptSocket = conn.accept(); 1194 acceptSocket.blocking = false; 1195 if (handleAccept) 1196 { 1197 TcpConnection connection = new TcpConnection(acceptSocket); 1198 debug (ASOCKETS) writefln("\tAccepted connection %s from %s", connection, connection.remoteAddress); 1199 connection.setKeepAlive(); 1200 //assert(connection.connected); 1201 //connection.connected = true; 1202 acceptHandler(connection); 1203 } 1204 else 1205 acceptSocket.close(); 1206 } 1207 1208 /// Called when a socket is writable. 1209 override void onWritable() 1210 { 1211 } 1212 1213 /// Called when an error occurs on the socket. 1214 override void onError(string reason) 1215 { 1216 close(); // call parent 1217 } 1218 1219 void closeListener() 1220 { 1221 assert(conn); 1222 socketManager.unregister(this); 1223 conn.close(); 1224 conn = null; 1225 } 1226 } 1227 1228 /// Whether the socket is listening. 1229 bool listening; 1230 /// Listener instances 1231 Listener[] listeners; 1232 1233 final void updateFlags() 1234 { 1235 foreach (listener; listeners) 1236 listener.notifyRead = handleAccept !is null; 1237 } 1238 1239 public: 1240 /// Start listening on this socket. 1241 ushort listen(ushort port, string addr = null) 1242 { 1243 debug(ASOCKETS) writefln("Attempting to listen on %s:%d", addr, port); 1244 //assert(!listening, "Attempting to listen on a listening socket"); 1245 1246 auto addressInfos = getAddressInfo(addr, to!string(port), AddressInfoFlags.PASSIVE, SocketType.STREAM, ProtocolType.TCP); 1247 1248 foreach (ref addressInfo; addressInfos) 1249 { 1250 if (addressInfo.family != AddressFamily.INET && port == 0) 1251 continue; // listen on random ports only on IPv4 for now 1252 1253 try 1254 { 1255 Socket conn = new Socket(addressInfo); 1256 conn.blocking = false; 1257 if (addressInfo.family == AddressFamily.INET6) 1258 conn.setOption(SocketOptionLevel.IPV6, SocketOption.IPV6_V6ONLY, true); 1259 conn.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true); 1260 1261 conn.bind(addressInfo.address); 1262 conn.listen(8); 1263 1264 if (addressInfo.family == AddressFamily.INET) 1265 port = to!ushort(conn.localAddress().toPortString()); 1266 1267 listeners ~= new Listener(conn); 1268 } 1269 catch (SocketException e) 1270 { 1271 debug(ASOCKETS) writefln("Unable to listen node \"%s\" service \"%s\"", addressInfo.address.toAddrString(), addressInfo.address.toPortString()); 1272 debug(ASOCKETS) writeln(e.msg); 1273 } 1274 } 1275 1276 if (listeners.length==0) 1277 throw new Exception("Unable to bind service"); 1278 1279 listening = true; 1280 1281 updateFlags(); 1282 1283 return port; 1284 } 1285 1286 @property Address[] localAddresses() 1287 { 1288 Address[] result; 1289 foreach (listener; listeners) 1290 result ~= listener.localAddress; 1291 return result; 1292 } 1293 1294 @property bool isListening() 1295 { 1296 return listening; 1297 } 1298 1299 /// Stop listening on this socket. 1300 void close() 1301 { 1302 foreach (listener;listeners) 1303 listener.closeListener(); 1304 listeners = null; 1305 listening = false; 1306 if (handleClose) 1307 handleClose(); 1308 } 1309 1310 public: 1311 /// Callback for when the socket was closed. 1312 void delegate() handleClose; 1313 1314 private void delegate(TcpConnection incoming) acceptHandler; 1315 /// Callback for an incoming connection. 1316 /// Connections will not be accepted unless this handler is set. 1317 @property final void delegate(TcpConnection incoming) handleAccept() { return acceptHandler; } 1318 /// ditto 1319 @property final void handleAccept(void delegate(TcpConnection incoming) value) { acceptHandler = value; updateFlags(); } 1320 } 1321 1322 // *************************************************************************** 1323 1324 /// Base class for a connection adapter. 1325 /// By itself, does nothing. 1326 class ConnectionAdapter : IConnection 1327 { 1328 IConnection next; 1329 1330 this(IConnection next) 1331 { 1332 this.next = next; 1333 next.handleConnect = &onConnect; 1334 next.handleDisconnect = &onDisconnect; 1335 } 1336 1337 @property ConnectionState state() { return next.state; } 1338 1339 /// Queue Data for sending. 1340 void send(Data[] data, int priority) 1341 { 1342 next.send(data, priority); 1343 } 1344 1345 alias send = IConnection.send; /// ditto 1346 1347 /// Terminate the connection. 1348 void disconnect(string reason = defaultDisconnectReason, DisconnectType type = DisconnectType.requested) 1349 { 1350 next.disconnect(reason, type); 1351 } 1352 1353 protected void onConnect() 1354 { 1355 if (connectHandler) 1356 connectHandler(); 1357 } 1358 1359 protected void onReadData(Data data) 1360 { 1361 // onReadData should be fired only if readDataHandler is set 1362 readDataHandler(data); 1363 } 1364 1365 protected void onDisconnect(string reason, DisconnectType type) 1366 { 1367 if (disconnectHandler) 1368 disconnectHandler(reason, type); 1369 } 1370 1371 protected void onBufferFlushed() 1372 { 1373 if (bufferFlushedHandler) 1374 bufferFlushedHandler(); 1375 } 1376 1377 /// Callback for when a connection has been established. 1378 @property void handleConnect(ConnectHandler value) { connectHandler = value; } 1379 private ConnectHandler connectHandler; 1380 1381 /// Callback setter for when new data is read. 1382 @property void handleReadData(ReadDataHandler value) 1383 { 1384 readDataHandler = value; 1385 next.handleReadData = value ? &onReadData : null ; 1386 } 1387 private ReadDataHandler readDataHandler; 1388 1389 /// Callback setter for when a connection was closed. 1390 @property void handleDisconnect(DisconnectHandler value) { disconnectHandler = value; } 1391 private DisconnectHandler disconnectHandler; 1392 1393 /// Callback setter for when all queued data has been written. 1394 @property void handleBufferFlushed(BufferFlushedHandler value) { bufferFlushedHandler = value; } 1395 private BufferFlushedHandler bufferFlushedHandler; 1396 } 1397 1398 // *************************************************************************** 1399 1400 /// Adapter for connections with a line-based protocol. 1401 /// Splits data stream into delimiter-separated lines. 1402 class LineBufferedAdapter : ConnectionAdapter 1403 { 1404 /// The protocol's line delimiter. 1405 string delimiter = "\r\n"; 1406 1407 this(IConnection next) 1408 { 1409 super(next); 1410 } 1411 1412 /// Append a line to the send buffer. 1413 void send(string line) 1414 { 1415 //super.send(Data(line ~ delimiter)); 1416 // https://issues.dlang.org/show_bug.cgi?id=13985 1417 ConnectionAdapter ca = this; 1418 ca.send(Data(line ~ delimiter)); 1419 } 1420 1421 protected: 1422 /// The receive buffer. 1423 Data inBuffer; 1424 1425 /// Called when data has been received. 1426 final override void onReadData(Data data) 1427 { 1428 import std.string; 1429 auto oldBufferLength = inBuffer.length; 1430 if (oldBufferLength) 1431 inBuffer ~= data; 1432 else 1433 inBuffer = data; 1434 1435 if (delimiter.length == 1) 1436 { 1437 import core.stdc.string; // memchr 1438 1439 char c = delimiter[0]; 1440 auto p = memchr(inBuffer.ptr + oldBufferLength, c, data.length); 1441 while (p) 1442 { 1443 sizediff_t index = p - inBuffer.ptr; 1444 processLine(index); 1445 1446 p = memchr(inBuffer.ptr, c, inBuffer.length); 1447 } 1448 } 1449 else 1450 { 1451 sizediff_t index; 1452 // TODO: we can start the search at oldBufferLength-delimiter.length+1 1453 while ((index=indexOf(cast(string)inBuffer.contents, delimiter)) >= 0) 1454 processLine(index); 1455 } 1456 } 1457 1458 final void processLine(size_t index) 1459 { 1460 auto line = inBuffer[0..index]; 1461 inBuffer = inBuffer[index+delimiter.length..inBuffer.length]; 1462 super.onReadData(line); 1463 } 1464 1465 override void onDisconnect(string reason, DisconnectType type) 1466 { 1467 super.onDisconnect(reason, type); 1468 inBuffer.clear(); 1469 } 1470 } 1471 1472 // *************************************************************************** 1473 1474 /// Fires an event handler or disconnects connections 1475 /// after a period of inactivity. 1476 class TimeoutAdapter : ConnectionAdapter 1477 { 1478 this(IConnection next) 1479 { 1480 debug (ASOCKETS) writefln("New TimeoutAdapter @ %s", cast(void*)this); 1481 super(next); 1482 } 1483 1484 void cancelIdleTimeout() 1485 { 1486 debug (ASOCKETS) writefln("TimeoutAdapter.cancelIdleTimeout @ %s", cast(void*)this); 1487 assert(idleTask !is null); 1488 assert(idleTask.isWaiting()); 1489 idleTask.cancel(); 1490 } 1491 1492 void resumeIdleTimeout() 1493 { 1494 debug (ASOCKETS) writefln("TimeoutAdapter.resumeIdleTimeout @ %s", cast(void*)this); 1495 assert(state == ConnectionState.connected); 1496 assert(idleTask !is null); 1497 assert(!idleTask.isWaiting()); 1498 mainTimer.add(idleTask); 1499 } 1500 1501 final void setIdleTimeout(Duration duration) 1502 { 1503 debug (ASOCKETS) writefln("TimeoutAdapter.setIdleTimeout @ %s", cast(void*)this); 1504 assert(duration > Duration.zero); 1505 if (idleTask is null) 1506 { 1507 idleTask = new TimerTask(duration); 1508 idleTask.handleTask = &onTask_Idle; 1509 } 1510 else 1511 { 1512 if (idleTask.isWaiting()) 1513 idleTask.cancel(); 1514 idleTask.delay = duration; 1515 } 1516 if (state == ConnectionState.connected) 1517 mainTimer.add(idleTask); 1518 } 1519 1520 void markNonIdle() 1521 { 1522 debug (ASOCKETS) writefln("TimeoutAdapter.markNonIdle @ %s", cast(void*)this); 1523 assert(idleTask !is null); 1524 if (handleNonIdle) 1525 handleNonIdle(); 1526 if (idleTask.isWaiting()) 1527 idleTask.restart(); 1528 } 1529 1530 /// Callback for when a connection has stopped responding. 1531 /// If unset, the connection will be disconnected. 1532 void delegate() handleIdleTimeout; 1533 1534 /// Callback for when a connection is marked as non-idle 1535 /// (when data is received). 1536 void delegate() handleNonIdle; 1537 1538 protected: 1539 override void onConnect() 1540 { 1541 debug (ASOCKETS) writefln("TimeoutAdapter.onConnect @ %s", cast(void*)this); 1542 super.onConnect(); 1543 if (idleTask) 1544 resumeIdleTimeout(); 1545 } 1546 1547 override void onReadData(Data data) 1548 { 1549 debug (ASOCKETS) writefln("TimeoutAdapter.onReadData @ %s", cast(void*)this); 1550 markNonIdle(); 1551 super.onReadData(data); 1552 } 1553 1554 override void onDisconnect(string reason, DisconnectType type) 1555 { 1556 debug (ASOCKETS) writefln("TimeoutAdapter.onDisconnect @ %s", cast(void*)this); 1557 super.onDisconnect(reason, type); 1558 if (idleTask && idleTask.isWaiting()) 1559 idleTask.cancel(); 1560 } 1561 1562 private: 1563 TimerTask idleTask; 1564 1565 final void onTask_Idle(Timer timer, TimerTask task) 1566 { 1567 if (state == ConnectionState.disconnecting) 1568 return disconnect("Delayed disconnect - time-out", DisconnectType.error); 1569 1570 if (state != ConnectionState.connected) 1571 return; 1572 1573 if (handleIdleTimeout) 1574 { 1575 handleIdleTimeout(); 1576 if (state == ConnectionState.connected) 1577 { 1578 assert(!idleTask.isWaiting()); 1579 mainTimer.add(idleTask); 1580 } 1581 } 1582 else 1583 disconnect("Time-out", DisconnectType.error); 1584 } 1585 } 1586 1587 // *************************************************************************** 1588 1589 unittest 1590 { 1591 void testTimer() 1592 { 1593 bool fired; 1594 setTimeout({fired = true;}, 10.msecs); 1595 socketManager.loop(); 1596 assert(fired); 1597 } 1598 1599 testTimer(); 1600 }