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 assert(conn is null, "Registered but %s socket".format(state)); 938 939 if (disconnectHandler) 940 disconnectHandler(reason, type); 941 updateFlags(); 942 } 943 944 private final void close() 945 { 946 assert(conn, "Attempting to close an unregistered socket"); 947 socketManager.unregister(this); 948 conn.close(); 949 conn = null; 950 outQueue[] = null; 951 state = ConnectionState.disconnected; 952 } 953 954 /// Append data to the send buffer. 955 void send(Data[] data, int priority = DEFAULT_PRIORITY) 956 { 957 assert(state == ConnectionState.connected, "Attempting to send on a %s socket".format(state)); 958 outQueue[priority] ~= data; 959 notifyWrite = true; // Fast updateFlags() 960 961 debug (PRINTDATA) 962 { 963 std.stdio.writefln("== %s -> %s ==", localAddress, remoteAddress); 964 foreach (datum; data) 965 if (datum.length) 966 std.stdio.write(hexDump(datum.contents)); 967 else 968 std.stdio.writeln("(empty Data)"); 969 std.stdio.stdout.flush(); 970 } 971 } 972 973 /// ditto 974 alias send = IConnection.send; 975 976 final void clearQueue(int priority) 977 { 978 if (partiallySent[priority]) 979 { 980 assert(outQueue[priority].length > 0); 981 outQueue[priority] = outQueue[priority][0..1]; 982 } 983 else 984 outQueue[priority] = null; 985 updateFlags(); 986 } 987 988 /// Clears all queues, even partially sent content. 989 private final void discardQueues() 990 { 991 foreach (priority; 0..MAX_PRIORITY+1) 992 { 993 outQueue[priority] = null; 994 partiallySent[priority] = false; 995 } 996 updateFlags(); 997 } 998 999 @property 1000 final bool writePending() 1001 { 1002 foreach (queue; outQueue) 1003 if (queue.length) 1004 return true; 1005 return false; 1006 } 1007 1008 final bool queuePresent(int priority) 1009 { 1010 if (partiallySent[priority]) 1011 { 1012 assert(outQueue[priority].length > 0); 1013 return outQueue[priority].length > 1; 1014 } 1015 else 1016 return outQueue[priority].length > 0; 1017 } 1018 1019 public: 1020 private ConnectHandler connectHandler; 1021 /// Callback for when a connection has been established. 1022 @property final void handleConnect(ConnectHandler value) { connectHandler = value; updateFlags(); } 1023 1024 private ReadDataHandler readDataHandler; 1025 /// Callback for incoming data. 1026 /// Data will not be received unless this handler is set. 1027 @property final void handleReadData(ReadDataHandler value) { readDataHandler = value; updateFlags(); } 1028 1029 private DisconnectHandler disconnectHandler; 1030 /// Callback for when a connection was closed. 1031 @property final void handleDisconnect(DisconnectHandler value) { disconnectHandler = value; updateFlags(); } 1032 1033 /// Callback setter for when all queued data has been sent. 1034 private BufferFlushedHandler bufferFlushedHandler; 1035 @property final void handleBufferFlushed(BufferFlushedHandler value) { bufferFlushedHandler = value; updateFlags(); } 1036 } 1037 1038 // *************************************************************************** 1039 1040 /// A POSIX file stream. 1041 /// Allows adding a file (e.g. stdin/stdout) to the socket manager. 1042 /// Does not dup the given file descriptor, so "disconnecting" this connection 1043 /// will close it. 1044 version (Posix) 1045 class FileConnection : StreamConnection 1046 { 1047 this(int fileno) 1048 { 1049 auto conn = new Socket(cast(socket_t)fileno, AddressFamily.UNSPEC); 1050 conn.blocking = false; 1051 super(conn); 1052 } 1053 1054 protected: 1055 import core.sys.posix.unistd : read, write; 1056 1057 override sizediff_t doSend(in void[] buffer) 1058 { 1059 return write(socket.handle, buffer.ptr, buffer.length); 1060 } 1061 1062 override sizediff_t doReceive(void[] buffer) 1063 { 1064 return read(socket.handle, buffer.ptr, buffer.length); 1065 } 1066 } 1067 1068 // *************************************************************************** 1069 1070 /// An asynchronous TCP connection. 1071 class TcpConnection : StreamConnection 1072 { 1073 protected: 1074 this(Socket conn) 1075 { 1076 super(conn); 1077 } 1078 1079 override sizediff_t doSend(in void[] buffer) 1080 { 1081 return conn.send(buffer); 1082 } 1083 1084 override sizediff_t doReceive(void[] buffer) 1085 { 1086 return conn.receive(buffer); 1087 } 1088 1089 final void tryNextAddress() 1090 { 1091 assert(state == ConnectionState.connecting); 1092 auto address = addressQueue[0]; 1093 addressQueue = addressQueue[1..$]; 1094 1095 try 1096 { 1097 conn = new Socket(address.addressFamily(), SocketType.STREAM, ProtocolType.TCP); 1098 conn.blocking = false; 1099 1100 socketManager.register(this); 1101 updateFlags(); 1102 debug (ASOCKETS) writefln("Attempting connection to %s", address.toString()); 1103 conn.connect(address); 1104 } 1105 catch (SocketException e) 1106 return onError("Connect error: " ~ e.msg); 1107 } 1108 1109 /// Called when an error occurs on the socket. 1110 override void onError(string reason) 1111 { 1112 if (state == ConnectionState.connecting && addressQueue.length) 1113 { 1114 socketManager.unregister(this); 1115 conn.close(); 1116 conn = null; 1117 1118 return tryNextAddress(); 1119 } 1120 1121 super.onError(reason); 1122 } 1123 1124 public: 1125 /// Default constructor 1126 this() 1127 { 1128 debug (ASOCKETS) writefln("New TcpConnection @ %s", cast(void*)this); 1129 } 1130 1131 /// Start establishing a connection. 1132 final void connect(string host, ushort port) 1133 { 1134 assert(host.length, "Empty host"); 1135 assert(port, "No port specified"); 1136 1137 debug (ASOCKETS) writefln("Connecting to %s:%s", host, port); 1138 assert(state == ConnectionState.disconnected, "Attempting to connect on a %s socket".format(state)); 1139 assert(!conn); 1140 1141 state = ConnectionState.resolving; 1142 1143 try 1144 { 1145 addressQueue = getAddress(host, port); 1146 enforce(addressQueue.length, "No addresses found"); 1147 debug (ASOCKETS) 1148 { 1149 writefln("Resolved to %s addresses:", addressQueue.length); 1150 foreach (address; addressQueue) 1151 writefln("- %s", address.toString()); 1152 } 1153 1154 state = ConnectionState.connecting; 1155 if (addressQueue.length > 1) 1156 { 1157 import std.random : randomShuffle; 1158 randomShuffle(addressQueue); 1159 } 1160 } 1161 catch (SocketException e) 1162 return onError("Lookup error: " ~ e.msg); 1163 1164 tryNextAddress(); 1165 } 1166 1167 } 1168 1169 // *************************************************************************** 1170 1171 /// An asynchronous TCP connection server. 1172 final class TcpServer 1173 { 1174 private: 1175 /// Class that actually performs listening on a certain address family 1176 final class Listener : GenericSocket 1177 { 1178 this(Socket conn) 1179 { 1180 debug (ASOCKETS) writefln("New Listener @ %s", cast(void*)this); 1181 this.conn = conn; 1182 socketManager.register(this); 1183 } 1184 1185 /// Called when a socket is readable. 1186 override void onReadable() 1187 { 1188 debug (ASOCKETS) writefln("Accepting connection from listener @ %s", cast(void*)this); 1189 Socket acceptSocket = conn.accept(); 1190 acceptSocket.blocking = false; 1191 if (handleAccept) 1192 { 1193 TcpConnection connection = new TcpConnection(acceptSocket); 1194 debug (ASOCKETS) writefln("\tAccepted connection %s from %s", connection, connection.remoteAddress); 1195 connection.setKeepAlive(); 1196 //assert(connection.connected); 1197 //connection.connected = true; 1198 acceptHandler(connection); 1199 } 1200 else 1201 acceptSocket.close(); 1202 } 1203 1204 /// Called when a socket is writable. 1205 override void onWritable() 1206 { 1207 } 1208 1209 /// Called when an error occurs on the socket. 1210 override void onError(string reason) 1211 { 1212 close(); // call parent 1213 } 1214 1215 void closeListener() 1216 { 1217 assert(conn); 1218 socketManager.unregister(this); 1219 conn.close(); 1220 conn = null; 1221 } 1222 } 1223 1224 /// Whether the socket is listening. 1225 bool listening; 1226 /// Listener instances 1227 Listener[] listeners; 1228 1229 final void updateFlags() 1230 { 1231 foreach (listener; listeners) 1232 listener.notifyRead = handleAccept !is null; 1233 } 1234 1235 public: 1236 /// Start listening on this socket. 1237 ushort listen(ushort port, string addr = null) 1238 { 1239 debug(ASOCKETS) writefln("Attempting to listen on %s:%d", addr, port); 1240 //assert(!listening, "Attempting to listen on a listening socket"); 1241 1242 auto addressInfos = getAddressInfo(addr, to!string(port), AddressInfoFlags.PASSIVE, SocketType.STREAM, ProtocolType.TCP); 1243 1244 foreach (ref addressInfo; addressInfos) 1245 { 1246 if (addressInfo.family != AddressFamily.INET && port == 0) 1247 continue; // listen on random ports only on IPv4 for now 1248 1249 try 1250 { 1251 Socket conn = new Socket(addressInfo); 1252 conn.blocking = false; 1253 if (addressInfo.family == AddressFamily.INET6) 1254 conn.setOption(SocketOptionLevel.IPV6, SocketOption.IPV6_V6ONLY, true); 1255 conn.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true); 1256 1257 conn.bind(addressInfo.address); 1258 conn.listen(8); 1259 1260 if (addressInfo.family == AddressFamily.INET) 1261 port = to!ushort(conn.localAddress().toPortString()); 1262 1263 listeners ~= new Listener(conn); 1264 } 1265 catch (SocketException e) 1266 { 1267 debug(ASOCKETS) writefln("Unable to listen node \"%s\" service \"%s\"", addressInfo.address.toAddrString(), addressInfo.address.toPortString()); 1268 debug(ASOCKETS) writeln(e.msg); 1269 } 1270 } 1271 1272 if (listeners.length==0) 1273 throw new Exception("Unable to bind service"); 1274 1275 listening = true; 1276 1277 updateFlags(); 1278 1279 return port; 1280 } 1281 1282 @property Address[] localAddresses() 1283 { 1284 Address[] result; 1285 foreach (listener; listeners) 1286 result ~= listener.localAddress; 1287 return result; 1288 } 1289 1290 @property bool isListening() 1291 { 1292 return listening; 1293 } 1294 1295 /// Stop listening on this socket. 1296 void close() 1297 { 1298 foreach (listener;listeners) 1299 listener.closeListener(); 1300 listeners = null; 1301 listening = false; 1302 if (handleClose) 1303 handleClose(); 1304 } 1305 1306 public: 1307 /// Callback for when the socket was closed. 1308 void delegate() handleClose; 1309 1310 private void delegate(TcpConnection incoming) acceptHandler; 1311 /// Callback for an incoming connection. 1312 /// Connections will not be accepted unless this handler is set. 1313 @property final void delegate(TcpConnection incoming) handleAccept() { return acceptHandler; } 1314 /// ditto 1315 @property final void handleAccept(void delegate(TcpConnection incoming) value) { acceptHandler = value; updateFlags(); } 1316 } 1317 1318 // *************************************************************************** 1319 1320 /// Base class for a connection adapter. 1321 /// By itself, does nothing. 1322 class ConnectionAdapter : IConnection 1323 { 1324 IConnection next; 1325 1326 this(IConnection next) 1327 { 1328 this.next = next; 1329 next.handleConnect = &onConnect; 1330 next.handleDisconnect = &onDisconnect; 1331 } 1332 1333 @property ConnectionState state() { return next.state; } 1334 1335 /// Queue Data for sending. 1336 void send(Data[] data, int priority) 1337 { 1338 next.send(data, priority); 1339 } 1340 1341 alias send = IConnection.send; /// ditto 1342 1343 /// Terminate the connection. 1344 void disconnect(string reason = defaultDisconnectReason, DisconnectType type = DisconnectType.requested) 1345 { 1346 next.disconnect(reason, type); 1347 } 1348 1349 protected void onConnect() 1350 { 1351 if (connectHandler) 1352 connectHandler(); 1353 } 1354 1355 protected void onReadData(Data data) 1356 { 1357 // onReadData should be fired only if readDataHandler is set 1358 readDataHandler(data); 1359 } 1360 1361 protected void onDisconnect(string reason, DisconnectType type) 1362 { 1363 if (disconnectHandler) 1364 disconnectHandler(reason, type); 1365 } 1366 1367 protected void onBufferFlushed() 1368 { 1369 if (bufferFlushedHandler) 1370 bufferFlushedHandler(); 1371 } 1372 1373 /// Callback for when a connection has been established. 1374 @property void handleConnect(ConnectHandler value) { connectHandler = value; } 1375 private ConnectHandler connectHandler; 1376 1377 /// Callback setter for when new data is read. 1378 @property void handleReadData(ReadDataHandler value) 1379 { 1380 readDataHandler = value; 1381 next.handleReadData = value ? &onReadData : null ; 1382 } 1383 private ReadDataHandler readDataHandler; 1384 1385 /// Callback setter for when a connection was closed. 1386 @property void handleDisconnect(DisconnectHandler value) { disconnectHandler = value; } 1387 private DisconnectHandler disconnectHandler; 1388 1389 /// Callback setter for when all queued data has been written. 1390 @property void handleBufferFlushed(BufferFlushedHandler value) { bufferFlushedHandler = value; } 1391 private BufferFlushedHandler bufferFlushedHandler; 1392 } 1393 1394 // *************************************************************************** 1395 1396 /// Adapter for connections with a line-based protocol. 1397 /// Splits data stream into delimiter-separated lines. 1398 class LineBufferedAdapter : ConnectionAdapter 1399 { 1400 /// The protocol's line delimiter. 1401 string delimiter = "\r\n"; 1402 1403 this(IConnection next) 1404 { 1405 super(next); 1406 } 1407 1408 /// Append a line to the send buffer. 1409 void send(string line) 1410 { 1411 //super.send(Data(line ~ delimiter)); 1412 // https://issues.dlang.org/show_bug.cgi?id=13985 1413 ConnectionAdapter ca = this; 1414 ca.send(Data(line ~ delimiter)); 1415 } 1416 1417 protected: 1418 /// The receive buffer. 1419 Data inBuffer; 1420 1421 /// Called when data has been received. 1422 final override void onReadData(Data data) 1423 { 1424 import std.string; 1425 auto oldBufferLength = inBuffer.length; 1426 if (oldBufferLength) 1427 inBuffer ~= data; 1428 else 1429 inBuffer = data; 1430 1431 if (delimiter.length == 1) 1432 { 1433 import core.stdc.string; // memchr 1434 1435 char c = delimiter[0]; 1436 auto p = memchr(inBuffer.ptr + oldBufferLength, c, data.length); 1437 while (p) 1438 { 1439 sizediff_t index = p - inBuffer.ptr; 1440 processLine(index); 1441 1442 p = memchr(inBuffer.ptr, c, inBuffer.length); 1443 } 1444 } 1445 else 1446 { 1447 sizediff_t index; 1448 // TODO: we can start the search at oldBufferLength-delimiter.length+1 1449 while ((index=indexOf(cast(string)inBuffer.contents, delimiter)) >= 0) 1450 processLine(index); 1451 } 1452 } 1453 1454 final void processLine(size_t index) 1455 { 1456 auto line = inBuffer[0..index]; 1457 inBuffer = inBuffer[index+delimiter.length..inBuffer.length]; 1458 super.onReadData(line); 1459 } 1460 1461 override void onDisconnect(string reason, DisconnectType type) 1462 { 1463 super.onDisconnect(reason, type); 1464 inBuffer.clear(); 1465 } 1466 } 1467 1468 // *************************************************************************** 1469 1470 /// Fires an event handler or disconnects connections 1471 /// after a period of inactivity. 1472 class TimeoutAdapter : ConnectionAdapter 1473 { 1474 this(IConnection next) 1475 { 1476 debug (ASOCKETS) writefln("New TimeoutAdapter @ %s", cast(void*)this); 1477 super(next); 1478 } 1479 1480 void cancelIdleTimeout() 1481 { 1482 debug (ASOCKETS) writefln("TimeoutAdapter.cancelIdleTimeout @ %s", cast(void*)this); 1483 assert(idleTask !is null); 1484 assert(idleTask.isWaiting()); 1485 idleTask.cancel(); 1486 } 1487 1488 void resumeIdleTimeout() 1489 { 1490 debug (ASOCKETS) writefln("TimeoutAdapter.resumeIdleTimeout @ %s", cast(void*)this); 1491 assert(state == ConnectionState.connected); 1492 assert(idleTask !is null); 1493 assert(!idleTask.isWaiting()); 1494 mainTimer.add(idleTask); 1495 } 1496 1497 final void setIdleTimeout(Duration duration) 1498 { 1499 debug (ASOCKETS) writefln("TimeoutAdapter.setIdleTimeout @ %s", cast(void*)this); 1500 assert(duration > Duration.zero); 1501 if (idleTask is null) 1502 { 1503 idleTask = new TimerTask(duration); 1504 idleTask.handleTask = &onTask_Idle; 1505 } 1506 else 1507 { 1508 if (idleTask.isWaiting()) 1509 idleTask.cancel(); 1510 idleTask.delay = duration; 1511 } 1512 if (state == ConnectionState.connected) 1513 mainTimer.add(idleTask); 1514 } 1515 1516 void markNonIdle() 1517 { 1518 debug (ASOCKETS) writefln("TimeoutAdapter.markNonIdle @ %s", cast(void*)this); 1519 assert(idleTask !is null); 1520 if (handleNonIdle) 1521 handleNonIdle(); 1522 if (idleTask.isWaiting()) 1523 idleTask.restart(); 1524 } 1525 1526 /// Callback for when a connection has stopped responding. 1527 /// If unset, the connection will be disconnected. 1528 void delegate() handleIdleTimeout; 1529 1530 /// Callback for when a connection is marked as non-idle 1531 /// (when data is received). 1532 void delegate() handleNonIdle; 1533 1534 protected: 1535 override void onConnect() 1536 { 1537 debug (ASOCKETS) writefln("TimeoutAdapter.onConnect @ %s", cast(void*)this); 1538 super.onConnect(); 1539 if (idleTask) 1540 resumeIdleTimeout(); 1541 } 1542 1543 override void onReadData(Data data) 1544 { 1545 debug (ASOCKETS) writefln("TimeoutAdapter.onReadData @ %s", cast(void*)this); 1546 markNonIdle(); 1547 super.onReadData(data); 1548 } 1549 1550 override void onDisconnect(string reason, DisconnectType type) 1551 { 1552 debug (ASOCKETS) writefln("TimeoutAdapter.onDisconnect @ %s", cast(void*)this); 1553 super.onDisconnect(reason, type); 1554 if (idleTask && idleTask.isWaiting()) 1555 idleTask.cancel(); 1556 } 1557 1558 private: 1559 TimerTask idleTask; 1560 1561 final void onTask_Idle(Timer timer, TimerTask task) 1562 { 1563 if (state == ConnectionState.disconnecting) 1564 return disconnect("Delayed disconnect - time-out", DisconnectType.error); 1565 1566 if (state != ConnectionState.connected) 1567 return; 1568 1569 if (handleIdleTimeout) 1570 { 1571 handleIdleTimeout(); 1572 if (state == ConnectionState.connected) 1573 { 1574 assert(!idleTask.isWaiting()); 1575 mainTimer.add(idleTask); 1576 } 1577 } 1578 else 1579 disconnect("Time-out", DisconnectType.error); 1580 } 1581 } 1582 1583 // *************************************************************************** 1584 1585 unittest 1586 { 1587 void testTimer() 1588 { 1589 bool fired; 1590 setTimeout({fired = true;}, 10.msecs); 1591 socketManager.loop(); 1592 assert(fired); 1593 } 1594 1595 testTimer(); 1596 }