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, AddressInfo, 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 (SocketException)
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 	AddressInfo[] 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 && conn) || 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 addressInfo = addressQueue[0];
1097 		addressQueue = addressQueue[1..$];
1098 
1099 		try
1100 		{
1101 			conn = new Socket(addressInfo.family, addressInfo.type, addressInfo.protocol);
1102 			conn.blocking = false;
1103 
1104 			socketManager.register(this);
1105 			updateFlags();
1106 			debug (ASOCKETS) writefln("Attempting connection to %s", addressInfo.address.toString());
1107 			conn.connect(addressInfo.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 
1144 		state = ConnectionState.resolving;
1145 
1146 		AddressInfo[] addressInfos;
1147 		try
1148 		{
1149 			auto addresses = getAddress(host, port);
1150 			enforce(addresses.length, "No addresses found");
1151 			debug (ASOCKETS)
1152 			{
1153 				writefln("Resolved to %s addresses:", addresses.length);
1154 				foreach (address; addresses)
1155 					writefln("- %s", address.toString());
1156 			}
1157 
1158 			if (addresses.length > 1)
1159 			{
1160 				import std.random : randomShuffle;
1161 				randomShuffle(addresses);
1162 			}
1163 
1164 			foreach (address; addresses)
1165 				addressInfos ~= AddressInfo(address.addressFamily, SocketType.STREAM, ProtocolType.TCP, address, host);
1166 		}
1167 		catch (SocketException e)
1168 			return onError("Lookup error: " ~ e.msg);
1169 
1170 		state = ConnectionState.disconnected;
1171 		connect(addressInfos);
1172 	}
1173 
1174 	/// ditto
1175 	final void connect(AddressInfo[] addresses)
1176 	{
1177 		assert(addresses.length, "No addresses specified");
1178 
1179 		assert(state == ConnectionState.disconnected, "Attempting to connect on a %s socket".format(state));
1180 		assert(!conn);
1181 
1182 		addressQueue = addresses;
1183 		state = ConnectionState.connecting;
1184 		tryNextAddress();
1185 	}
1186 }
1187 
1188 // ***************************************************************************
1189 
1190 /// An asynchronous TCP connection server.
1191 final class TcpServer
1192 {
1193 private:
1194 	/// Class that actually performs listening on a certain address family
1195 	final class Listener : GenericSocket
1196 	{
1197 		this(Socket conn)
1198 		{
1199 			debug (ASOCKETS) writefln("New Listener @ %s", cast(void*)this);
1200 			this.conn = conn;
1201 			socketManager.register(this);
1202 		}
1203 
1204 		/// Called when a socket is readable.
1205 		override void onReadable()
1206 		{
1207 			debug (ASOCKETS) writefln("Accepting connection from listener @ %s", cast(void*)this);
1208 			Socket acceptSocket = conn.accept();
1209 			acceptSocket.blocking = false;
1210 			if (handleAccept)
1211 			{
1212 				TcpConnection connection = new TcpConnection(acceptSocket);
1213 				debug (ASOCKETS) writefln("\tAccepted connection %s from %s", connection, connection.remoteAddress);
1214 				connection.setKeepAlive();
1215 				//assert(connection.connected);
1216 				//connection.connected = true;
1217 				acceptHandler(connection);
1218 			}
1219 			else
1220 				acceptSocket.close();
1221 		}
1222 
1223 		/// Called when a socket is writable.
1224 		override void onWritable()
1225 		{
1226 		}
1227 
1228 		/// Called when an error occurs on the socket.
1229 		override void onError(string reason)
1230 		{
1231 			close(); // call parent
1232 		}
1233 
1234 		void closeListener()
1235 		{
1236 			assert(conn);
1237 			socketManager.unregister(this);
1238 			conn.close();
1239 			conn = null;
1240 		}
1241 	}
1242 
1243 	/// Whether the socket is listening.
1244 	bool listening;
1245 	/// Listener instances
1246 	Listener[] listeners;
1247 
1248 	final void updateFlags()
1249 	{
1250 		foreach (listener; listeners)
1251 			listener.notifyRead = handleAccept !is null;
1252 	}
1253 
1254 public:
1255 	/// Start listening on this socket.
1256 	ushort listen(ushort port, string addr = null)
1257 	{
1258 		debug(ASOCKETS) writefln("Attempting to listen on %s:%d", addr, port);
1259 		//assert(!listening, "Attempting to listen on a listening socket");
1260 
1261 		auto addressInfos = getAddressInfo(addr, to!string(port), AddressInfoFlags.PASSIVE, SocketType.STREAM, ProtocolType.TCP);
1262 
1263 		// listen on random ports only on IPv4 for now
1264 		if (port == 0)
1265 		{
1266 			foreach_reverse (i, ref addressInfo; addressInfos)
1267 				if (addressInfo.family != AddressFamily.INET)
1268 					addressInfos = addressInfos[0..i] ~ addressInfos[i+1..$];
1269 		}
1270 
1271 		listen(addressInfos);
1272 
1273 		foreach (listener; listeners)
1274 		{
1275 			auto address = listener.conn.localAddress();
1276 			if (address.addressFamily == AddressFamily.INET)
1277 				port = to!ushort(address.toPortString());
1278 		}
1279 
1280 		return port;
1281 	}
1282 
1283 	/// ditto
1284 	void listen(AddressInfo[] addressInfos)
1285 	{
1286 		foreach (ref addressInfo; addressInfos)
1287 		{
1288 			try
1289 			{
1290 				Socket conn = new Socket(addressInfo);
1291 				conn.blocking = false;
1292 				if (addressInfo.family == AddressFamily.INET6)
1293 					conn.setOption(SocketOptionLevel.IPV6, SocketOption.IPV6_V6ONLY, true);
1294 				conn.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true);
1295 
1296 				conn.bind(addressInfo.address);
1297 				conn.listen(8);
1298 
1299 				listeners ~= new Listener(conn);
1300 			}
1301 			catch (SocketException e)
1302 			{
1303 				debug(ASOCKETS) writefln("Unable to listen node \"%s\" service \"%s\"", addressInfo.address.toAddrString(), addressInfo.address.toPortString());
1304 				debug(ASOCKETS) writeln(e.msg);
1305 			}
1306 		}
1307 
1308 		if (listeners.length==0)
1309 			throw new Exception("Unable to bind service");
1310 
1311 		listening = true;
1312 
1313 		updateFlags();
1314 	}
1315 
1316 	@property Address[] localAddresses()
1317 	{
1318 		Address[] result;
1319 		foreach (listener; listeners)
1320 			result ~= listener.localAddress;
1321 		return result;
1322 	}
1323 
1324 	@property bool isListening()
1325 	{
1326 		return listening;
1327 	}
1328 
1329 	/// Stop listening on this socket.
1330 	void close()
1331 	{
1332 		foreach (listener;listeners)
1333 			listener.closeListener();
1334 		listeners = null;
1335 		listening = false;
1336 		if (handleClose)
1337 			handleClose();
1338 	}
1339 
1340 public:
1341 	/// Callback for when the socket was closed.
1342 	void delegate() handleClose;
1343 
1344 	private void delegate(TcpConnection incoming) acceptHandler;
1345 	/// Callback for an incoming connection.
1346 	/// Connections will not be accepted unless this handler is set.
1347 	@property final void delegate(TcpConnection incoming) handleAccept() { return acceptHandler; }
1348 	/// ditto
1349 	@property final void handleAccept(void delegate(TcpConnection incoming) value) { acceptHandler = value; updateFlags(); }
1350 }
1351 
1352 // ***************************************************************************
1353 
1354 /// Base class for a connection adapter.
1355 /// By itself, does nothing.
1356 class ConnectionAdapter : IConnection
1357 {
1358 	IConnection next;
1359 
1360 	this(IConnection next)
1361 	{
1362 		this.next = next;
1363 		next.handleConnect = &onConnect;
1364 		next.handleDisconnect = &onDisconnect;
1365 	}
1366 
1367 	@property ConnectionState state() { return next.state; }
1368 
1369 	/// Queue Data for sending.
1370 	void send(Data[] data, int priority)
1371 	{
1372 		next.send(data, priority);
1373 	}
1374 
1375 	alias send = IConnection.send; /// ditto
1376 
1377 	/// Terminate the connection.
1378 	void disconnect(string reason = defaultDisconnectReason, DisconnectType type = DisconnectType.requested)
1379 	{
1380 		next.disconnect(reason, type);
1381 	}
1382 
1383 	protected void onConnect()
1384 	{
1385 		if (connectHandler)
1386 			connectHandler();
1387 	}
1388 
1389 	protected void onReadData(Data data)
1390 	{
1391 		// onReadData should be fired only if readDataHandler is set
1392 		readDataHandler(data);
1393 	}
1394 
1395 	protected void onDisconnect(string reason, DisconnectType type)
1396 	{
1397 		if (disconnectHandler)
1398 			disconnectHandler(reason, type);
1399 	}
1400 
1401 	protected void onBufferFlushed()
1402 	{
1403 		if (bufferFlushedHandler)
1404 			bufferFlushedHandler();
1405 	}
1406 
1407 	/// Callback for when a connection has been established.
1408 	@property void handleConnect(ConnectHandler value) { connectHandler = value; }
1409 	private ConnectHandler connectHandler;
1410 
1411 	/// Callback setter for when new data is read.
1412 	@property void handleReadData(ReadDataHandler value)
1413 	{
1414 		readDataHandler = value;
1415 		next.handleReadData = value ? &onReadData : null ;
1416 	}
1417 	private ReadDataHandler readDataHandler;
1418 
1419 	/// Callback setter for when a connection was closed.
1420 	@property void handleDisconnect(DisconnectHandler value) { disconnectHandler = value; }
1421 	private DisconnectHandler disconnectHandler;
1422 
1423 	/// Callback setter for when all queued data has been written.
1424 	@property void handleBufferFlushed(BufferFlushedHandler value) { bufferFlushedHandler = value; }
1425 	private BufferFlushedHandler bufferFlushedHandler;
1426 }
1427 
1428 // ***************************************************************************
1429 
1430 /// Adapter for connections with a line-based protocol.
1431 /// Splits data stream into delimiter-separated lines.
1432 class LineBufferedAdapter : ConnectionAdapter
1433 {
1434 	/// The protocol's line delimiter.
1435 	string delimiter = "\r\n";
1436 
1437 	this(IConnection next)
1438 	{
1439 		super(next);
1440 	}
1441 
1442 	/// Append a line to the send buffer.
1443 	void send(string line)
1444 	{
1445 		//super.send(Data(line ~ delimiter));
1446 		// https://issues.dlang.org/show_bug.cgi?id=13985
1447 		ConnectionAdapter ca = this;
1448 		ca.send(Data(line ~ delimiter));
1449 	}
1450 
1451 protected:
1452 	/// The receive buffer.
1453 	Data inBuffer;
1454 
1455 	/// Called when data has been received.
1456 	final override void onReadData(Data data)
1457 	{
1458 		import std.string;
1459 		auto oldBufferLength = inBuffer.length;
1460 		if (oldBufferLength)
1461 			inBuffer ~= data;
1462 		else
1463 			inBuffer = data;
1464 
1465 		if (delimiter.length == 1)
1466 		{
1467 			import core.stdc.string; // memchr
1468 
1469 			char c = delimiter[0];
1470 			auto p = memchr(inBuffer.ptr + oldBufferLength, c, data.length);
1471 			while (p)
1472 			{
1473 				sizediff_t index = p - inBuffer.ptr;
1474 				processLine(index);
1475 
1476 				p = memchr(inBuffer.ptr, c, inBuffer.length);
1477 			}
1478 		}
1479 		else
1480 		{
1481 			sizediff_t index;
1482 			// TODO: we can start the search at oldBufferLength-delimiter.length+1
1483 			while ((index=indexOf(cast(string)inBuffer.contents, delimiter)) >= 0)
1484 				processLine(index);
1485 		}
1486 	}
1487 
1488 	final void processLine(size_t index)
1489 	{
1490 		auto line = inBuffer[0..index];
1491 		inBuffer = inBuffer[index+delimiter.length..inBuffer.length];
1492 		super.onReadData(line);
1493 	}
1494 
1495 	override void onDisconnect(string reason, DisconnectType type)
1496 	{
1497 		super.onDisconnect(reason, type);
1498 		inBuffer.clear();
1499 	}
1500 }
1501 
1502 // ***************************************************************************
1503 
1504 /// Fires an event handler or disconnects connections
1505 /// after a period of inactivity.
1506 class TimeoutAdapter : ConnectionAdapter
1507 {
1508 	this(IConnection next)
1509 	{
1510 		debug (ASOCKETS) writefln("New TimeoutAdapter @ %s", cast(void*)this);
1511 		super(next);
1512 	}
1513 
1514 	void cancelIdleTimeout()
1515 	{
1516 		debug (ASOCKETS) writefln("TimeoutAdapter.cancelIdleTimeout @ %s", cast(void*)this);
1517 		assert(idleTask !is null);
1518 		assert(idleTask.isWaiting());
1519 		idleTask.cancel();
1520 	}
1521 
1522 	void resumeIdleTimeout()
1523 	{
1524 		debug (ASOCKETS) writefln("TimeoutAdapter.resumeIdleTimeout @ %s", cast(void*)this);
1525 		assert(state == ConnectionState.connected);
1526 		assert(idleTask !is null);
1527 		assert(!idleTask.isWaiting());
1528 		mainTimer.add(idleTask);
1529 	}
1530 
1531 	final void setIdleTimeout(Duration duration)
1532 	{
1533 		debug (ASOCKETS) writefln("TimeoutAdapter.setIdleTimeout @ %s", cast(void*)this);
1534 		assert(duration > Duration.zero);
1535 		if (idleTask is null)
1536 		{
1537 			idleTask = new TimerTask(duration);
1538 			idleTask.handleTask = &onTask_Idle;
1539 		}
1540 		else
1541 		{
1542 			if (idleTask.isWaiting())
1543 				idleTask.cancel();
1544 			idleTask.delay = duration;
1545 		}
1546 		if (state == ConnectionState.connected)
1547 			mainTimer.add(idleTask);
1548 	}
1549 
1550 	void markNonIdle()
1551 	{
1552 		debug (ASOCKETS) writefln("TimeoutAdapter.markNonIdle @ %s", cast(void*)this);
1553 		assert(idleTask !is null);
1554 		if (handleNonIdle)
1555 			handleNonIdle();
1556 		if (idleTask.isWaiting())
1557 			idleTask.restart();
1558 	}
1559 
1560 	/// Callback for when a connection has stopped responding.
1561 	/// If unset, the connection will be disconnected.
1562 	void delegate() handleIdleTimeout;
1563 
1564 	/// Callback for when a connection is marked as non-idle
1565 	/// (when data is received).
1566 	void delegate() handleNonIdle;
1567 
1568 protected:
1569 	override void onConnect()
1570 	{
1571 		debug (ASOCKETS) writefln("TimeoutAdapter.onConnect @ %s", cast(void*)this);
1572 		super.onConnect();
1573 		if (idleTask)
1574 			resumeIdleTimeout();
1575 	}
1576 
1577 	override void onReadData(Data data)
1578 	{
1579 		debug (ASOCKETS) writefln("TimeoutAdapter.onReadData @ %s", cast(void*)this);
1580 		markNonIdle();
1581 		super.onReadData(data);
1582 	}
1583 
1584 	override void onDisconnect(string reason, DisconnectType type)
1585 	{
1586 		debug (ASOCKETS) writefln("TimeoutAdapter.onDisconnect @ %s", cast(void*)this);
1587 		if (idleTask && idleTask.isWaiting())
1588 			idleTask.cancel();
1589 		super.onDisconnect(reason, type);
1590 	}
1591 
1592 private:
1593 	TimerTask idleTask;
1594 
1595 	final void onTask_Idle(Timer timer, TimerTask task)
1596 	{
1597 		if (state == ConnectionState.disconnecting)
1598 			return disconnect("Delayed disconnect - time-out", DisconnectType.error);
1599 
1600 		if (state != ConnectionState.connected)
1601 			return;
1602 
1603 		if (handleIdleTimeout)
1604 		{
1605 			handleIdleTimeout();
1606 			if (state == ConnectionState.connected)
1607 			{
1608 				assert(!idleTask.isWaiting());
1609 				mainTimer.add(idleTask);
1610 			}
1611 		}
1612 		else
1613 			disconnect("Time-out", DisconnectType.error);
1614 	}
1615 }
1616 
1617 // ***************************************************************************
1618 
1619 unittest
1620 {
1621 	void testTimer()
1622 	{
1623 		bool fired;
1624 		setTimeout({fired = true;}, 10.msecs);
1625 		socketManager.loop();
1626 		assert(fired);
1627 	}
1628 
1629 	testTimer();
1630 }