-
Notifications
You must be signed in to change notification settings - Fork 39
/
asockets.d
2263 lines (1932 loc) · 60 KB
/
asockets.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Asynchronous socket abstraction.
*
* License:
* This Source Code Form is subject to the terms of
* the Mozilla Public License, v. 2.0. If a copy of
* the MPL was not distributed with this file, You
* can obtain one at http://mozilla.org/MPL/2.0/.
*
* Authors:
* Stéphan Kochen <stephan@kochen.nl>
* Vladimir Panteleev <ae@cy.md>
* Vincent Povirk <madewokherd@gmail.com>
* Simon Arlott
*/
module ae.net.asockets;
import ae.sys.dataset : DataVec;
import ae.sys.timing;
import ae.utils.array : asSlice, asBytes, queuePush, queuePop;
import ae.utils.math;
public import ae.sys.data;
import core.stdc.stdint : int32_t;
import std.exception;
import std.parallelism : totalCPUs;
import std.socket;
import std.string : format;
public import std.socket : Address, AddressInfo, Socket;
version (Windows)
private import c_socks = core.sys.windows.winsock2;
else version (Posix)
private import c_socks = core.sys.posix.sys.socket;
debug(ASOCKETS) import std.stdio : stderr;
debug(PRINTDATA) import std.stdio : stderr;
debug(PRINTDATA) import ae.utils.text : hexDump;
private import std.conv : to;
// https://issues.dlang.org/show_bug.cgi?id=7016
static import ae.utils.array;
version(LIBEV)
{
import deimos.ev;
pragma(lib, "ev");
}
version(Windows)
{
import core.sys.windows.windows : Sleep;
private enum USE_SLEEP = true; // avoid convoluted mix of static and runtime conditions
}
else
private enum USE_SLEEP = false;
int eventCounter;
version (LIBEV)
{
// Watchers are a GenericSocket field (as declared in SocketMixin).
// Use one watcher per read and write event.
// Start/stop those as higher-level code declares interest in those events.
// Use the "data" ev_io field to store the parent GenericSocket address.
// Also use the "data" field as a flag to indicate whether the watcher is active
// (data is null when the watcher is stopped).
/// `libev`-based event loop implementation.
struct SocketManager
{
private:
size_t count;
void delegate()[] nextTickHandlers;
extern(C)
static void ioCallback(ev_loop_t* l, ev_io* w, int revents)
{
auto socket = cast(GenericSocket)w.data;
assert(socket, "libev event fired on stopped watcher");
debug (ASOCKETS) stderr.writefln("ioCallback(%s, 0x%X)", socket, revents);
// TODO? Need to get proper SocketManager instance to call updateTimer on
socketManager.preEvent();
if (revents & EV_READ)
socket.onReadable();
else
if (revents & EV_WRITE)
socket.onWritable();
else
assert(false, "Unknown event fired from libev");
socketManager.postEvent(false);
}
ev_timer evTimer;
MonoTime lastNextEvent = MonoTime.max;
extern(C)
static void timerCallback(ev_loop_t* l, ev_timer* w, int /*revents*/)
{
debug (ASOCKETS) stderr.writefln("Timer callback called.");
socketManager.preEvent(); // This also updates socketManager.now
mainTimer.prod(socketManager.now);
socketManager.postEvent(true);
debug (ASOCKETS) stderr.writefln("Timer callback exiting.");
}
/// Called upon waking up, before calling any users' event handlers.
void preEvent()
{
eventCounter++;
socketManager.now = MonoTime.currTime();
}
/// Called before going back to sleep, after calling any users' event handlers.
void postEvent(bool wokeDueToTimeout)
{
while (nextTickHandlers.length)
{
auto thisTickHandlers = nextTickHandlers;
nextTickHandlers = null;
foreach (handler; thisTickHandlers)
handler();
}
socketManager.updateTimer(wokeDueToTimeout);
}
void updateTimer(bool force)
{
auto nextEvent = mainTimer.getNextEvent();
if (force || lastNextEvent != nextEvent)
{
debug (ASOCKETS) stderr.writefln("Rescheduling timer. Was at %s, now at %s", lastNextEvent, nextEvent);
if (nextEvent == MonoTime.max) // Stopping
{
if (lastNextEvent != MonoTime.max)
ev_timer_stop(ev_default_loop(0), &evTimer);
}
else
{
auto remaining = mainTimer.getRemainingTime(socketManager.now);
while (remaining <= Duration.zero)
{
debug (ASOCKETS) stderr.writefln("remaining=%s, prodding timer.", remaining);
mainTimer.prod(socketManager.now);
remaining = mainTimer.getRemainingTime(socketManager.now);
}
ev_tstamp tstamp = remaining.total!"hnsecs" * 1.0 / convert!("seconds", "hnsecs")(1);
debug (ASOCKETS) stderr.writefln("remaining=%s, ev_tstamp=%s", remaining, tstamp);
if (lastNextEvent == MonoTime.max) // Starting
{
ev_timer_init(&evTimer, &timerCallback, 0., tstamp);
ev_timer_start(ev_default_loop(0), &evTimer);
}
else // Adjusting
{
evTimer.repeat = tstamp;
ev_timer_again(ev_default_loop(0), &evTimer);
}
}
lastNextEvent = nextEvent;
}
}
public:
MonoTime now;
/// Register a socket with the manager.
void register(GenericSocket socket)
{
debug (ASOCKETS) stderr.writefln("Registering %s", socket);
debug assert(socket.evRead.data is null && socket.evWrite.data is null, "Re-registering a started socket");
auto fd = socket.conn.handle;
assert(fd, "Must have fd before socket registration");
ev_io_init(&socket.evRead , &ioCallback, fd, EV_READ );
ev_io_init(&socket.evWrite, &ioCallback, fd, EV_WRITE);
count++;
}
/// Unregister a socket with the manager.
void unregister(GenericSocket socket)
{
debug (ASOCKETS) stderr.writefln("Unregistering %s", socket);
socket.notifyRead = false;
socket.notifyWrite = false;
count--;
}
/// Returns the number of registered sockets.
size_t size()
{
return count;
}
/// Loop continuously until no sockets are left.
void loop()
{
auto evLoop = ev_default_loop(0);
enforce(evLoop, "libev initialization failure");
updateTimer(true);
debug (ASOCKETS) stderr.writeln("ev_run");
ev_run(ev_default_loop(0), 0);
}
}
private mixin template SocketMixin()
{
private ev_io evRead, evWrite;
private final void setWatcherState(ref ev_io ev, bool newValue, int /*event*/)
{
if (!conn)
{
// Can happen when setting delegates before connecting.
return;
}
if (newValue && !ev.data)
{
// Start
ev.data = cast(void*)this;
ev_io_start(ev_default_loop(0), &ev);
}
else
if (!newValue && ev.data)
{
// Stop
assert(ev.data is cast(void*)this);
ev.data = null;
ev_io_stop(ev_default_loop(0), &ev);
}
}
private final bool getWatcherState(ref ev_io ev) { return !!ev.data; }
// Flags that determine socket wake-up events.
/// Interested in read notifications (onReadable)?
@property final void notifyRead (bool value) { setWatcherState(evRead , value, EV_READ ); }
@property final bool notifyRead () { return getWatcherState(evRead); } /// ditto
/// Interested in write notifications (onWritable)?
@property final void notifyWrite(bool value) { setWatcherState(evWrite, value, EV_WRITE); }
@property final bool notifyWrite() { return getWatcherState(evWrite); } /// ditto
debug ~this() @nogc
{
// The LIBEV SocketManager holds no references to registered sockets.
// TODO: Add a doubly-linked list?
assert(evRead.data is null && evWrite.data is null, "Destroying a registered socket");
}
}
}
else // Use select
{
/// `select`-based event loop implementation.
struct SocketManager
{
private:
enum FD_SETSIZE = 1024;
/// List of all sockets to poll.
GenericSocket[] sockets;
/// Debug AA to check for dangling socket references.
debug GenericSocket[socket_t] socketHandles;
void delegate()[] nextTickHandlers, idleHandlers;
public:
MonoTime now;
/// Register a socket with the manager.
void register(GenericSocket conn)
{
debug (ASOCKETS) stderr.writefln("Registering %s (%d total)", conn, sockets.length + 1);
assert(!conn.socket.blocking, "Trying to register a blocking socket");
sockets ~= conn;
debug
{
auto handle = conn.socket.handle;
assert(handle != socket_t.init, "Can't register a closed socket");
assert(handle !in socketHandles, "This socket handle is already registered");
socketHandles[handle] = conn;
}
}
/// Unregister a socket with the manager.
void unregister(GenericSocket conn)
{
debug (ASOCKETS) stderr.writefln("Unregistering %s (%d total)", conn, sockets.length - 1);
debug
{
auto handle = conn.socket.handle;
assert(handle != socket_t.init, "Can't unregister a closed socket");
auto pconn = handle in socketHandles;
assert(pconn, "This socket handle is not registered");
assert(*pconn is conn, "This socket handle is registered but belongs to another GenericSocket");
socketHandles.remove(handle);
}
foreach (size_t i, GenericSocket j; sockets)
if (j is conn)
{
sockets = sockets[0 .. i] ~ sockets[i + 1 .. sockets.length];
return;
}
assert(false, "Socket not registered");
}
/// Returns the number of registered sockets.
size_t size()
{
return sockets.length;
}
/// Loop continuously until no sockets are left.
void loop()
{
debug (ASOCKETS) stderr.writeln("Starting event loop.");
SocketSet readset, writeset;
size_t sockcount;
uint setSize = FD_SETSIZE; // Can't trust SocketSet.max due to Issue 14012
readset = new SocketSet(setSize);
writeset = new SocketSet(setSize);
while (true)
{
if (nextTickHandlers.length)
{
auto thisTickHandlers = nextTickHandlers;
nextTickHandlers = null;
foreach (handler; thisTickHandlers)
handler();
continue;
}
uint minSize = 0;
version(Windows)
minSize = cast(uint)sockets.length;
else
{
foreach (s; sockets)
if (s.socket && s.socket.handle != socket_t.init && s.socket.handle > minSize)
minSize = s.socket.handle;
}
minSize++;
if (setSize < minSize)
{
debug (ASOCKETS) stderr.writefln("Resizing SocketSets: %d => %d", setSize, minSize*2);
setSize = minSize * 2;
readset = new SocketSet(setSize);
writeset = new SocketSet(setSize);
}
else
{
readset.reset();
writeset.reset();
}
sockcount = 0;
bool haveActive;
debug (ASOCKETS) stderr.writeln("Populating sets");
foreach (GenericSocket conn; sockets)
{
if (!conn.socket)
continue;
sockcount++;
debug (ASOCKETS) stderr.writef("\t%s:", conn);
if (conn.notifyRead)
{
readset.add(conn.socket);
if (!conn.daemonRead)
haveActive = true;
debug (ASOCKETS) stderr.write(" READ", conn.daemonRead ? "[daemon]" : "");
}
if (conn.notifyWrite)
{
writeset.add(conn.socket);
if (!conn.daemonWrite)
haveActive = true;
debug (ASOCKETS) stderr.write(" WRITE", conn.daemonWrite ? "[daemon]" : "");
}
debug (ASOCKETS) stderr.writeln();
}
debug (ASOCKETS)
{
stderr.writefln("Sets populated as follows:");
printSets(readset, writeset);
}
debug (ASOCKETS) stderr.writefln("Waiting (%sactive with %d sockets, %s timer events, %d idle handlers)...",
haveActive ? "" : "not ",
sockcount,
mainTimer.isWaiting() ? "with" : "no",
idleHandlers.length,
);
if (!haveActive && !mainTimer.isWaiting() && !nextTickHandlers.length)
{
debug (ASOCKETS) stderr.writeln("No more sockets or timer events, exiting loop.");
break;
}
debug (ASOCKETS) stderr.flush();
int events;
if (idleHandlers.length)
{
if (sockcount==0)
events = 0;
else
events = Socket.select(readset, writeset, null, 0.seconds);
}
else
if (USE_SLEEP && sockcount==0)
{
version (Windows)
{
now = MonoTime.currTime();
auto duration = mainTimer.getRemainingTime(now).total!"msecs"();
debug (ASOCKETS) writeln("Wait duration: ", duration, " msecs");
if (duration <= 0)
duration = 1; // Avoid busywait
else
if (duration > int.max)
duration = int.max;
Sleep(cast(int)duration);
events = 0;
}
else
assert(0);
}
else
if (mainTimer.isWaiting())
{
// Refresh time before sleeping, to ensure that a
// slow event handler does not skew everything else
now = MonoTime.currTime();
events = Socket.select(readset, writeset, null, mainTimer.getRemainingTime(now));
}
else
events = Socket.select(readset, writeset, null);
debug (ASOCKETS) stderr.writefln("%d events fired.", events);
// Update time after sleeping
now = MonoTime.currTime();
if (events > 0)
{
// Handle just one event at a time, as the first
// handler might invalidate select()'s results.
handleEvent(readset, writeset);
}
else
if (idleHandlers.length)
{
import ae.utils.array : shift;
auto handler = idleHandlers.shift();
// Rotate the idle handler queue before running it,
// in case the handler unregisters itself.
idleHandlers ~= handler;
handler();
}
// Timers may invalidate our select results, so fire them after processing the latter
mainTimer.prod(now);
eventCounter++;
}
}
debug (ASOCKETS)
private void printSets(SocketSet readset, SocketSet writeset)
{
foreach (GenericSocket conn; sockets)
{
if (!conn.socket)
stderr.writefln("\t\t%s is unset", conn);
else
{
if (readset.isSet(conn.socket))
stderr.writefln("\t\t%s is readable", conn);
if (writeset.isSet(conn.socket))
stderr.writefln("\t\t%s is writable", conn);
}
}
}
private void handleEvent(SocketSet readset, SocketSet writeset)
{
debug (ASOCKETS)
{
stderr.writefln("\tSelect results:");
printSets(readset, writeset);
}
foreach (GenericSocket conn; sockets)
{
if (!conn.socket)
continue;
if (writeset.isSet(conn.socket))
{
debug (ASOCKETS) stderr.writefln("\t%s - calling onWritable", conn);
return conn.onWritable();
}
if (readset.isSet(conn.socket))
{
debug (ASOCKETS) stderr.writefln("\t%s - calling onReadable", conn);
return conn.onReadable();
}
}
assert(false, "select() reported events available, but no registered sockets are set");
}
}
// Use UFCS to allow removeIdleHandler to have a predicate with context
/// Register a function to be called when the event loop is idle,
/// and would otherwise sleep.
void addIdleHandler(ref SocketManager socketManager, void delegate() handler)
{
foreach (i, idleHandler; socketManager.idleHandlers)
assert(handler !is idleHandler);
socketManager.idleHandlers ~= handler;
}
/// Unregister a function previously registered with `addIdleHandler`.
void removeIdleHandler(alias pred=(a, b) => a is b, Args...)(ref SocketManager socketManager, Args args)
{
foreach (i, idleHandler; socketManager.idleHandlers)
if (pred(idleHandler, args))
{
import std.algorithm : remove;
socketManager.idleHandlers = socketManager.idleHandlers.remove(i);
return;
}
assert(false, "No such idle handler");
}
private mixin template SocketMixin()
{
// Flags that determine socket wake-up events.
/// Interested in read notifications (onReadable)?
bool notifyRead;
/// Interested in write notifications (onWritable)?
bool notifyWrite;
}
}
/// The default socket manager.
SocketManager socketManager;
/// Schedule a function to run on the next event loop iteration.
/// Can be used to queue logic to run once all current execution frames exit.
/// Similar to e.g. process.nextTick in Node.
void onNextTick(ref SocketManager socketManager, void delegate() dg) pure @safe nothrow
{
socketManager.nextTickHandlers ~= dg;
}
/// The current monotonic time.
/// Updated by the event loop whenever it is awoken.
@property MonoTime now()
{
if (socketManager.now == MonoTime.init)
{
// Event loop not yet started.
socketManager.now = MonoTime.currTime();
}
return socketManager.now;
}
// ***************************************************************************
/// General methods for an asynchronous socket.
abstract class GenericSocket
{
/// Declares notifyRead and notifyWrite.
mixin SocketMixin;
protected:
/// The socket this class wraps.
Socket conn;
// protected:
void onReadable()
{
}
void onWritable()
{
}
void onError(string /*reason*/)
{
}
public:
/// Retrieve the socket class this class wraps.
@property final Socket socket()
{
return conn;
}
/// allow getting the address of connections that are already disconnected
private Address[2] cachedAddress;
/*private*/ final @property Address _address(bool local)()
{
if (cachedAddress[local] !is null)
return cachedAddress[local];
else
if (conn is null)
return null;
else
{
Address a;
if (conn.addressFamily == AddressFamily.UNSPEC)
{
// Socket will attempt to construct an UnknownAddress,
// which will almost certainly not match the real address length.
static if (local)
alias getname = c_socks.getsockname;
else
alias getname = c_socks.getpeername;
c_socks.socklen_t nameLen = 0;
if (getname(conn.handle, null, &nameLen) < 0)
throw new SocketOSException("Unable to obtain socket address");
auto buf = new ubyte[nameLen];
auto sa = cast(c_socks.sockaddr*)buf.ptr;
if (getname(conn.handle, sa, &nameLen) < 0)
throw new SocketOSException("Unable to obtain socket address");
a = new UnknownAddressReference(sa, nameLen);
}
else
a = local ? conn.localAddress() : conn.remoteAddress();
return cachedAddress[local] = a;
}
}
alias localAddress = _address!true; /// Retrieve this socket's local address.
alias remoteAddress = _address!false; /// Retrieve this socket's remote address.
/*private*/ final @property string _addressStr(bool local)() nothrow
{
try
{
auto a = _address!local;
if (a is null)
return "[null address]";
string host = a.toAddrString();
import std.string : indexOf;
if (host.indexOf(':') >= 0)
host = "[" ~ host ~ "]";
try
{
string port = a.toPortString();
return host ~ ":" ~ port;
}
catch (Exception e)
return host;
}
catch (Exception e)
return "[error: " ~ e.msg ~ "]";
}
alias localAddressStr = _addressStr!true; /// Retrieve this socket's local address, as a string.
alias remoteAddressStr = _addressStr!false; /// Retrieve this socket's remote address, as a string.
/// Don't block the process from exiting, even if the socket is ready to receive data.
/// TODO: Not implemented with libev
bool daemonRead;
/// Don't block the process from exiting, even if the socket is ready to send data.
/// TODO: Not implemented with libev
bool daemonWrite;
deprecated alias daemon = daemonRead;
/// Enable TCP keep-alive on the socket with the given settings.
final void setKeepAlive(bool enabled=true, int time=10, int interval=5)
{
assert(conn, "Attempting to set keep-alive on an uninitialized socket");
if (enabled)
{
try
conn.setKeepAlive(time, interval);
catch (SocketException)
conn.setOption(SocketOptionLevel.SOCKET, SocketOption.KEEPALIVE, true);
}
else
conn.setOption(SocketOptionLevel.SOCKET, SocketOption.KEEPALIVE, false);
}
/// Returns a string containing the class name, address, and file descriptor.
override string toString() const
{
import std.string : format, split;
return "%s {this=%s, fd=%s}".format(this.classinfo.name.split(".")[$-1], cast(void*)this, conn ? conn.handle : -1);
}
}
// ***************************************************************************
/// Classifies the cause of the disconnect.
/// Can be used to decide e.g. when it makes sense to reconnect.
enum DisconnectType
{
requested, /// Initiated by the application.
graceful, /// The peer gracefully closed the connection.
error /// Some abnormal network condition.
}
/// Used to indicate the state of a connection throughout its lifecycle.
enum ConnectionState
{
/// The initial state, or the state after a disconnect was fully processed.
disconnected,
/// Name resolution. Currently done synchronously.
resolving,
/// A connection attempt is in progress.
connecting,
/// A connection is established.
connected,
/// Disconnecting in progress. No data can be sent or received at this point.
/// We are waiting for queued data to be actually sent before disconnecting.
disconnecting,
}
/// Returns true if this is a connection state for which disconnecting is valid.
/// Generally, applications should be aware of the life cycle of their sockets,
/// so checking the state of a connection is unnecessary (and a code smell).
/// However, unconditionally disconnecting some connected sockets can be useful
/// when it needs to occur "out-of-bound" (not tied to the application normal life cycle),
/// such as in response to a signal.
bool disconnectable(ConnectionState state) { return state >= ConnectionState.resolving && state <= ConnectionState.connected; }
/// Common interface for connections and adapters.
interface IConnection
{
/// `send` queues data for sending in one of five queues, indexed
/// by a numeric priority.
/// `MAX_PRIORITY` is the highest (least urgent) priority index.
/// `DEFAULT_PRIORITY` is the default priority
enum MAX_PRIORITY = 4;
enum DEFAULT_PRIORITY = 2; /// ditto
/// This is the default value for the `disconnect` `reason` string parameter.
static const defaultDisconnectReason = "Software closed the connection";
/// Get connection state.
@property ConnectionState state();
/// Has a connection been established?
deprecated final @property bool connected() { return state == ConnectionState.connected; }
/// Are we in the process of disconnecting? (Waiting for data to be flushed)
deprecated final @property bool disconnecting() { return state == ConnectionState.disconnecting; }
/// Queue Data for sending.
void send(scope Data[] data, int priority = DEFAULT_PRIORITY);
/// ditto
final void send(Data datum, int priority = DEFAULT_PRIORITY)
{
this.send(datum.asSlice, priority);
}
/// Terminate the connection.
void disconnect(string reason = defaultDisconnectReason, DisconnectType type = DisconnectType.requested);
/// Callback setter for when a connection has been established
/// (if applicable).
alias ConnectHandler = void delegate();
@property void handleConnect(ConnectHandler value); /// ditto
/// Callback setter for when new data is read.
alias ReadDataHandler = void delegate(Data data);
@property void handleReadData(ReadDataHandler value); /// ditto
/// Callback setter for when a connection was closed.
alias DisconnectHandler = void delegate(string reason, DisconnectType type);
@property void handleDisconnect(DisconnectHandler value); /// ditto
/// Callback setter for when all queued data has been sent.
alias BufferFlushedHandler = void delegate();
@property void handleBufferFlushed(BufferFlushedHandler value); /// ditto
}
// ***************************************************************************
/// Implementation of `IConnection` using a socket.
/// Implements receiving data when readable and sending queued data
/// when writable.
class Connection : GenericSocket, IConnection
{
private:
ConnectionState _state;
final @property ConnectionState state(ConnectionState value) { return _state = value; }
public:
/// Get connection state.
override @property ConnectionState state() { return _state; }
protected:
abstract sizediff_t doSend(scope const(void)[] buffer);
enum sizediff_t doReceiveEOF = -1;
abstract sizediff_t doReceive(scope void[] buffer);
/// The send buffers.
DataVec[MAX_PRIORITY+1] outQueue;
/// Whether the first item from this queue (if any) has been partially sent (and thus can't be canceled).
int partiallySent = -1;
/// Constructor used by a ServerSocket for new connections
this(Socket conn)
{
this();
this.conn = conn;
state = conn is null ? ConnectionState.disconnected : ConnectionState.connected;
if (conn)
socketManager.register(this);
updateFlags();
}
final void updateFlags()
{
if (state == ConnectionState.connecting)
notifyWrite = true;
else
notifyWrite = writePending;
notifyRead = state == ConnectionState.connected && readDataHandler;
debug(ASOCKETS) stderr.writefln("[%s] updateFlags: %s %s", conn ? conn.handle : -1, notifyRead, notifyWrite);
}
// We reuse the same buffer across read calls.
// It is allocated on the first read, and also
// if the user code decides to keep a reference to it.
static Data inBuffer;
/// Called when a socket is readable.
override void onReadable()
{
// TODO: use FIONREAD when Phobos gets ioctl support (issue 6649)
if (!inBuffer)
inBuffer = Data(0x10000);
else
inBuffer = inBuffer.ensureUnique();
sizediff_t received;
inBuffer.enter((scope contents) {
received = doReceive(contents);
});
if (received == doReceiveEOF)
return disconnect("Connection closed", DisconnectType.graceful);
if (received == Socket.ERROR)
{
// if (wouldHaveBlocked)
// {
// debug (ASOCKETS) writefln("\t\t%s: wouldHaveBlocked or recv()", this);
// return;
// }
// else
onError("recv() error: " ~ lastSocketError);
}
else
{
debug (PRINTDATA)
{
stderr.writefln("== %s <- %s ==", localAddressStr, remoteAddressStr);
stderr.write(hexDump(inBuffer.unsafeContents[0 .. received]));
stderr.flush();
}
if (state == ConnectionState.disconnecting)
{
debug (ASOCKETS) stderr.writefln("\t\t%s: Discarding received data because we are disconnecting", this);
}
else
if (!readDataHandler)
{
debug (ASOCKETS) stderr.writefln("\t\t%s: Discarding received data because there is no data handler", this);
}
else
{
auto data = inBuffer[0 .. received];
readDataHandler(data);
}
}
}
/// Called when an error occurs on the socket.
override void onError(string reason)
{
if (state == ConnectionState.disconnecting)
{
debug (ASOCKETS) stderr.writefln("Socket error while disconnecting @ %s: %s".format(cast(void*)this, reason));
return close();
}
assert(state == ConnectionState.resolving || state == ConnectionState.connecting || state == ConnectionState.connected);
disconnect("Socket error: " ~ reason, DisconnectType.error);
}
this()
{
}
public:
/// Close a connection. If there is queued data waiting to be sent, wait until it is sent before disconnecting.
/// The disconnect handler will be called immediately, even when not all data has been flushed yet.
void disconnect(string reason = defaultDisconnectReason, DisconnectType type = DisconnectType.requested)
{
//scope(success) updateFlags(); // Work around scope(success) breaking debugger stack traces
assert(state.disconnectable, "Attempting to disconnect on a %s socket".format(state));
if (writePending)
{
if (type==DisconnectType.requested)
{
assert(conn, "Attempting to disconnect on an uninitialized socket");
// queue disconnect after all data is sent
debug (ASOCKETS) stderr.writefln("[%s] Queueing disconnect: %s", remoteAddressStr, reason);
state = ConnectionState.disconnecting;
//setIdleTimeout(30.seconds);
if (disconnectHandler)
disconnectHandler(reason, type);
updateFlags();
return;
}
else
discardQueues();
}
debug (ASOCKETS) stderr.writefln("Disconnecting @ %s: %s", cast(void*)this, reason);
if ((state == ConnectionState.connecting && conn) || state == ConnectionState.connected)
close();
else
{
assert(conn is null, "Registered but %s socket".format(state));
if (state == ConnectionState.resolving)
state = ConnectionState.disconnected;
}
if (disconnectHandler)
disconnectHandler(reason, type);
updateFlags();
}
private final void close()
{
assert(conn, "Attempting to close an unregistered socket");
socketManager.unregister(this);
conn.close();
conn = null;
outQueue[] = DataVec.init;
state = ConnectionState.disconnected;
}
/// Append data to the send buffer.
void send(scope Data[] data, int priority = DEFAULT_PRIORITY)
{
assert(state == ConnectionState.connected, "Attempting to send on a %s socket".format(state));
outQueue[priority] ~= data;
notifyWrite = true; // Fast updateFlags()
debug (PRINTDATA)
{