-
Notifications
You must be signed in to change notification settings - Fork 30
/
posix.d
2785 lines (2356 loc) · 76.5 KB
/
posix.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
module libasync.posix;
version (Posix):
import libasync.types;
import std.string : toStringz;
import std.conv : to;
import std.datetime : Duration, msecs, seconds, SysTime;
import std.traits : isIntegral;
import std.typecons : Tuple, tuple;
import std.container : Array;
import core.stdc.errno;
import libasync.events;
import libasync.internals.memory : FreeListObjectAlloc;
import libasync.internals.hashmap;
import libasync.internals.path;
import core.sys.posix.signal;
import libasync.posix2;
import core.sync.mutex;
enum SOCKET_ERROR = -1;
alias fd_t = int;
version(linux) {
import libasync.internals.epoll;
const EPOLL = true;
extern(C) nothrow @nogc {
int __libc_current_sigrtmin();
int __libc_current_sigrtmax();
}
bool g_signalsBlocked;
package nothrow void blockSignals() {
try {
/// Block signals to reserve SIGRTMIN .. " +30 for AsyncSignal
sigset_t mask;
// todo: use more signals for more event loops per thread.. (is this necessary?)
//foreach (j; __libc_current_sigrtmin() .. __libc_current_sigrtmax() + 1) {
//import std.stdio : writeln;
//try writeln("Blocked signal " ~ (__libc_current_sigrtmin() + j).to!string ~ " in instance " ~ m_instanceId.to!string); catch {}
sigemptyset(&mask);
sigaddset(&mask, cast(int) __libc_current_sigrtmin());
pthread_sigmask(SIG_BLOCK, &mask, null);
//}
} catch {}
}
static this() {
blockSignals();
g_signalsBlocked = true;
}
}
version(OSX) {
import libasync.internals.kqueue;
const EPOLL = false;
}
version(FreeBSD) {
import libasync.internals.kqueue;
const EPOLL = false;
}
__gshared Mutex g_mutex;
static if (!EPOLL) {
private struct DWFileInfo {
fd_t folder;
Path path;
SysTime lastModified;
bool is_dir;
}
}
private struct DWFolderInfo {
WatchInfo wi;
fd_t fd;
}
package struct EventLoopImpl {
static if (EPOLL) {
pragma(msg, "Using Linux EPOLL for events");
}
else /* if KQUEUE */
{
pragma(msg, "Using FreeBSD KQueue for events");
}
package:
alias error_t = EPosix;
nothrow:
private:
/// members
EventLoop m_evLoop;
ushort m_instanceId;
bool m_started;
StatusInfo m_status;
error_t m_error = EPosix.EOK;
EventInfo* m_evSignal;
static if (EPOLL){
fd_t m_epollfd;
HashMap!(Tuple!(fd_t, uint), DWFolderInfo) m_dwFolders; // uint = inotify_add_watch(Path)
}
else /* if KQUEUE */
{
fd_t m_kqueuefd;
HashMap!(fd_t, EventInfo*) m_watchers; // fd_t = id++ per AsyncDirectoryWatcher
HashMap!(fd_t, DWFolderInfo) m_dwFolders; // fd_t = open(folder)
HashMap!(fd_t, DWFileInfo) m_dwFiles; // fd_t = open(file)
HashMap!(fd_t, Array!(DWChangeInfo)*) m_changes; // fd_t = id++ per AsyncDirectoryWatcher
}
package:
/// workaround for IDE indent bug on too big files
mixin RunKill!();
@property bool started() const {
return m_started;
}
bool init(EventLoop evl)
in { assert(!m_started); }
body
{
import core.atomic;
shared static ushort i;
string* failer = null;
m_instanceId = i;
static if (!EPOLL) g_threadId = new size_t(cast(size_t)m_instanceId);
core.atomic.atomicOp!"+="(i, cast(ushort) 1);
m_evLoop = evl;
import core.thread;
try Thread.getThis().priority = Thread.PRIORITY_MAX;
catch (Exception e) { assert(false, "Could not set thread priority"); }
try
if (!g_mutex)
g_mutex = new Mutex;
catch {}
static if (EPOLL)
{
if (!g_signalsBlocked)
blockSignals();
assert(m_instanceId <= __libc_current_sigrtmax(), "An additional event loop is unsupported due to SIGRTMAX restrictions in Linux Kernel");
m_epollfd = epoll_create1(0);
if (catchError!"epoll_create1"(m_epollfd))
return false;
import core.sys.linux.sys.signalfd;
import core.thread : getpid;
fd_t err;
fd_t sfd;
sigset_t mask;
try {
sigemptyset(&mask);
sigaddset(&mask, __libc_current_sigrtmin());
err = pthread_sigmask(SIG_BLOCK, &mask, null);
if (catchError!"sigprocmask"(err))
{
m_status.code = Status.EVLOOP_FAILURE;
return false;
}
} catch { }
sfd = signalfd(-1, &mask, SFD_NONBLOCK);
assert(sfd > 0, "Failed to setup signalfd in epoll");
EventType evtype;
epoll_event _event;
_event.events = EPOLLIN;
evtype = EventType.Signal;
try
m_evSignal = FreeListObjectAlloc!EventInfo.alloc(sfd, evtype, EventObject.init, m_instanceId);
catch (Exception e){
assert(false, "Allocation error");
}
_event.data.ptr = cast(void*) m_evSignal;
err = epoll_ctl(m_epollfd, EPOLL_CTL_ADD, sfd, &_event);
if (catchError!"EPOLL_CTL_ADD(sfd)"(err))
{
return false;
}
}
else /* if KQUEUE */
{
try {
if (!gs_queueMutex) {
gs_queueMutex = FreeListObjectAlloc!ReadWriteMutex.alloc();
gs_signalQueue = Array!(Array!AsyncSignal)();
gs_idxQueue = Array!(Array!size_t)();
}
if (g_evIdxAvailable.empty) {
g_evIdxAvailable.reserve(32);
foreach (k; g_evIdxAvailable.length .. g_evIdxAvailable.capacity) {
g_evIdxAvailable.insertBack(k + 1);
}
g_evIdxCapacity = 32;
g_idxCapacity = 32;
}
} catch { assert(false, "Initialization failed"); }
m_kqueuefd = kqueue();
int err;
try {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGXCPU);
err = sigprocmask(SIG_BLOCK, &mask, null);
} catch {}
EventType evtype = EventType.Signal;
// use GC because FreeListObjectAlloc fails at emplace for shared objects
try
m_evSignal = FreeListObjectAlloc!EventInfo.alloc(SIGXCPU, evtype, EventObject.init, m_instanceId);
catch (Exception e) {
assert(false, "Failed to allocate resources");
}
if (catchError!"siprocmask"(err))
return 0;
kevent_t _event;
EV_SET(&_event, SIGXCPU, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0, m_evSignal);
err = kevent(m_kqueuefd, &_event, 1, null, 0, null);
if (catchError!"kevent_add(SIGXCPU)"(err))
assert(false, "Add SIGXCPU failed at kevent call");
}
try log("init in thread " ~ Thread.getThis().name); catch {}
return true;
}
void exit() {
import core.sys.posix.unistd : close;
static if (EPOLL) {
close(m_epollfd); // not necessary?
// not necessary:
//try FreeListObjectAlloc!EventInfo.free(m_evSignal);
//catch (Exception e) { assert(false, "Failed to free resources"); }
}
else
close(m_kqueuefd);
}
@property const(StatusInfo) status() const {
return m_status;
}
@property string error() const {
string* ptr;
return ((ptr = (m_error in EPosixMessages)) !is null) ? *ptr : string.init;
}
bool loop(Duration timeout = 0.seconds)
//in { assert(Fiber.getThis() is null); }
{
import libasync.internals.memory;
bool success = true;
int num;
static if (EPOLL) {
static align(1) epoll_event[] events;
if (events is null)
{
try events = new epoll_event[128];
catch (Exception e) {
assert(false, "Could not allocate events array: " ~ e.msg);
}
}
int timeout_ms;
if (timeout == 0.seconds)
timeout_ms = -1;
else timeout_ms = cast(int)timeout.total!"msecs";
/// Retrieve pending events
num = epoll_wait(m_epollfd, cast(epoll_event*)&events[0], 128, timeout_ms);
assert(events !is null && events.length <= 128);
}
else /* if KQUEUE */ {
import core.sys.posix.time : time_t;
import core.sys.posix.config : c_long;
static kevent_t[] events;
if (events.length == 0) {
try events = allocArray!kevent_t(manualAllocator(), 128);
catch (Exception e) { assert(false, "Could not allocate events array"); }
}
time_t secs = timeout.split!("seconds", "nsecs")().seconds;
c_long ns = timeout.split!("seconds", "nsecs")().nsecs;
auto tspec = libasync.internals.kqueue.timespec(secs, ns);
num = kevent(m_kqueuefd, null, 0, cast(kevent_t*) events, cast(int) events.length, &tspec);
}
auto errors = [ tuple(EINTR, Status.EVLOOP_TIMEOUT) ];
if (catchEvLoopErrors!"event_poll'ing"(num, errors))
return false;
if (num > 0)
log("Got " ~ num.to!string ~ " event(s)");
foreach(i; 0 .. num) {
success = false;
m_status = StatusInfo.init;
static if (EPOLL)
{
epoll_event _event = events[i];
try log("Event " ~ i.to!string ~ " of: " ~ events.length.to!string); catch {}
EventInfo* info = cast(EventInfo*) _event.data.ptr;
int event_flags = cast(int) _event.events;
}
else /* if KQUEUE */
{
kevent_t _event = events[i];
EventInfo* info = cast(EventInfo*) _event.udata;
//log("Got info");
int event_flags = (_event.filter << 16) | (_event.flags & 0xffff);
//log("event flags");
}
//if (info.owner != m_instanceId)
// try log("Event " ~ (cast(int)(info.evType)).to!string ~ " is invalid: supposidly created in instance #" ~ info.owner.to!string ~ ", received in " ~ m_instanceId.to!string ~ " event: " ~ event_flags.to!string);
// catch{}
//log("owner");
final switch (info.evType) {
case EventType.TCPAccept:
if (info.fd == 0)
break;
success = onTCPAccept(info.fd, info.evObj.tcpAcceptHandler, event_flags);
break;
case EventType.Notifier:
log("Got notifier!");
try info.evObj.notifierHandler();
catch (Exception e) {
setInternalError!"notifierHandler"(Status.ERROR);
}
break;
case EventType.DirectoryWatcher:
log("Got DirectoryWatcher event!");
static if (!EPOLL) {
// in KQUEUE all events will be consumed here, because they must be pre-processed
try {
DWFileEvent fevent;
if (_event.fflags & (NOTE_LINK | NOTE_WRITE))
fevent = DWFileEvent.CREATED;
else if (_event.fflags & NOTE_DELETE)
fevent = DWFileEvent.DELETED;
else if (_event.fflags & (NOTE_ATTRIB | NOTE_EXTEND | NOTE_WRITE))
fevent = DWFileEvent.MODIFIED;
else if (_event.fflags & NOTE_RENAME)
fevent = DWFileEvent.MOVED_FROM;
else if (_event.fflags & NOTE_RENAME)
fevent = DWFileEvent.MOVED_TO;
else
assert(false, "No event found?");
DWFolderInfo fi = m_dwFolders.get(cast(fd_t)_event.ident, DWFolderInfo.init);
if (fi == DWFolderInfo.init) {
DWFileInfo tmp = m_dwFiles.get(cast(fd_t)_event.ident, DWFileInfo.init);
assert(tmp != DWFileInfo.init, "The event loop returned an invalid file's file descriptor for the directory watcher");
fi = m_dwFolders.get(cast(fd_t) tmp.folder, DWFolderInfo.init);
assert(fi != DWFolderInfo.init, "The event loop returned an invalid folder file descriptor for the directory watcher");
}
// all recursive events will be generated here
if (!compareFolderFiles(fi, fevent)) {
continue;
}
} catch (Exception e) {
log("Could not process DirectoryWatcher event: " ~ e.msg);
break;
}
}
try info.evObj.dwHandler();
catch (Exception e) {
setInternalError!"dwHandler"(Status.ERROR);
}
break;
case EventType.Timer:
try log("Got timer! " ~ info.fd.to!string); catch {}
static if (EPOLL) {
static long val;
import core.sys.posix.unistd : read;
read(info.evObj.timerHandler.ctxt.id, &val, long.sizeof);
}
try info.evObj.timerHandler();
catch (Exception e) {
setInternalError!"timerHandler"(Status.ERROR);
}
static if (!EPOLL) {
if (info.evObj.timerHandler.ctxt.oneShot && !info.evObj.timerHandler.ctxt.rearmed) {
destroyIndex(info.evObj.timerHandler.ctxt);
info.evObj.timerHandler.ctxt.id = 0;
}
}
break;
case EventType.Signal:
try log("Got signal!"); catch {}
static if (EPOLL) {
try log("Got signal: " ~ info.fd.to!string ~ " of type: " ~ info.evType.to!string); catch {}
import core.sys.linux.sys.signalfd : signalfd_siginfo;
import core.sys.posix.unistd : read;
signalfd_siginfo fdsi;
fd_t err = cast(fd_t)read(info.fd, &fdsi, fdsi.sizeof);
shared AsyncSignal sig = cast(shared AsyncSignal) cast(void*) fdsi.ssi_ptr;
try sig.handler();
catch (Exception e) {
setInternalError!"signal handler"(Status.ERROR);
}
}
else /* if KQUEUE */
{
static AsyncSignal[] sigarr;
if (sigarr.length == 0) {
try sigarr = new AsyncSignal[32];
catch (Exception e) { assert(false, "Could not allocate signals array"); }
}
bool more = popSignals(sigarr);
foreach (AsyncSignal sig; sigarr)
{
shared AsyncSignal ptr = cast(shared AsyncSignal) sig;
if (ptr is null)
break;
try (cast(shared AsyncSignal)sig).handler();
catch (Exception e) {
setInternalError!"signal handler"(Status.ERROR);
}
}
}
break;
case EventType.UDPSocket:
import core.sys.posix.unistd : close;
success = onUDPTraffic(info.fd, info.evObj.udpHandler, event_flags);
nothrow void abortHandler(bool graceful) {
close(info.fd);
info.evObj.udpHandler.conn.socket = 0;
try info.evObj.udpHandler(UDPEvent.ERROR);
catch (Exception e) { }
try FreeListObjectAlloc!EventInfo.free(info);
catch (Exception e){ assert(false, "Error freeing resources"); }
}
if (!success && m_status.code == Status.ABORT) {
abortHandler(true);
}
else if (!success && m_status.code == Status.ERROR) {
abortHandler(false);
}
break;
case EventType.TCPTraffic:
assert(info.evObj.tcpEvHandler.conn !is null, "TCP Connection invalid");
success = onTCPTraffic(info.fd, info.evObj.tcpEvHandler, event_flags, info.evObj.tcpEvHandler.conn);
nothrow void abortTCPHandler(bool graceful) {
nothrow void closeAll() {
try log("closeAll()"); catch {}
if (info.evObj.tcpEvHandler.conn.connected)
closeSocket(info.fd, true, true);
info.evObj.tcpEvHandler.conn.socket = 0;
}
/// Close the connection after an unexpected socket error
if (graceful) {
try info.evObj.tcpEvHandler(TCPEvent.CLOSE);
catch (Exception e) { }
closeAll();
}
/// Kill the connection after an internal error
else {
try info.evObj.tcpEvHandler(TCPEvent.ERROR);
catch (Exception e) { }
closeAll();
}
if (info.evObj.tcpEvHandler.conn.inbound) {
log("Freeing inbound connection FD#" ~ info.fd.to!string);
try FreeListObjectAlloc!AsyncTCPConnection.free(info.evObj.tcpEvHandler.conn);
catch (Exception e){ assert(false, "Error freeing resources"); }
}
try FreeListObjectAlloc!EventInfo.free(info);
catch (Exception e){ assert(false, "Error freeing resources"); }
}
if (!success && m_status.code == Status.ABORT) {
abortTCPHandler(true);
}
else if (!success && m_status.code == Status.ERROR) {
abortTCPHandler(false);
}
break;
}
}
return success;
}
bool setOption(T)(fd_t fd, TCPOption option, in T value) {
m_status = StatusInfo.init;
import std.traits : isIntegral;
import libasync.internals.socket_compat : socklen_t, setsockopt, SO_REUSEADDR, SO_KEEPALIVE, SO_RCVBUF, SO_SNDBUF, SO_RCVTIMEO, SO_SNDTIMEO, SO_LINGER, SOL_SOCKET, IPPROTO_TCP, TCP_NODELAY, TCP_QUICKACK, TCP_KEEPCNT, TCP_KEEPINTVL, TCP_KEEPIDLE, TCP_CONGESTION, TCP_CORK, TCP_DEFER_ACCEPT;
int err;
nothrow bool errorHandler() {
if (catchError!"setOption:"(err)) {
try m_status.text ~= option.to!string;
catch (Exception e){ assert(false, "to!string conversion failure"); }
return false;
}
return true;
}
final switch (option) {
case TCPOption.NODELAY: // true/false
static if (!is(T == bool))
assert(false, "NODELAY value type must be bool, not " ~ T.stringof);
else {
int val = value?1:0;
socklen_t len = val.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, len);
return errorHandler();
}
case TCPOption.REUSEADDR: // true/false
static if (!is(T == bool))
assert(false, "REUSEADDR value type must be bool, not " ~ T.stringof);
else {
int val = value?1:0;
socklen_t len = val.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, len);
if (!errorHandler())
return false;
// BSD systems have SO_REUSEPORT
import libasync.internals.socket_compat : SO_REUSEPORT;
err = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, len);
// Not all linux kernels support SO_REUSEPORT
version(linux) {
// ignore invalid and not supported errors on linux
if (errno == EINVAL || errno == ENOPROTOOPT) {
return true;
}
}
return errorHandler();
}
case TCPOption.QUICK_ACK:
static if (!is(T == bool))
assert(false, "QUICK_ACK value type must be bool, not " ~ T.stringof);
else {
static if (EPOLL) {
int val = value?1:0;
socklen_t len = val.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &val, len);
return errorHandler();
}
else /* not linux */ {
return false;
}
}
case TCPOption.KEEPALIVE_ENABLE: // true/false
static if (!is(T == bool))
assert(false, "KEEPALIVE_ENABLE value type must be bool, not " ~ T.stringof);
else
{
int val = value?1:0;
socklen_t len = val.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, len);
return errorHandler();
}
case TCPOption.KEEPALIVE_COUNT: // ##
static if (!isIntegral!T)
assert(false, "KEEPALIVE_COUNT value type must be integral, not " ~ T.stringof);
else {
int val = value.total!"msecs".to!uint;
socklen_t len = val.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &val, len);
return errorHandler();
}
case TCPOption.KEEPALIVE_INTERVAL: // wait ## seconds
static if (!is(T == Duration))
assert(false, "KEEPALIVE_INTERVAL value type must be Duration, not " ~ T.stringof);
else {
int val;
try val = value.total!"seconds".to!uint; catch { return false; }
socklen_t len = val.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &val, len);
return errorHandler();
}
case TCPOption.KEEPALIVE_DEFER: // wait ## seconds until start
static if (!is(T == Duration))
assert(false, "KEEPALIVE_DEFER value type must be Duration, not " ~ T.stringof);
else {
int val;
try val = value.total!"seconds".to!uint; catch { return false; }
socklen_t len = val.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &val, len);
return errorHandler();
}
case TCPOption.BUFFER_RECV: // bytes
static if (!isIntegral!T)
assert(false, "BUFFER_RECV value type must be integral, not " ~ T.stringof);
else {
int val = value.to!int;
socklen_t len = val.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &val, len);
return errorHandler();
}
case TCPOption.BUFFER_SEND: // bytes
static if (!isIntegral!T)
assert(false, "BUFFER_SEND value type must be integral, not " ~ T.stringof);
else {
int val = value.to!int;
socklen_t len = val.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &val, len);
return errorHandler();
}
case TCPOption.TIMEOUT_RECV:
static if (!is(T == Duration))
assert(false, "TIMEOUT_RECV value type must be Duration, not " ~ T.stringof);
else {
import core.sys.posix.sys.time : timeval;
time_t secs = cast(time_t) value.split!("seconds", "usecs")().seconds;
suseconds_t us;
try us = value.split!("seconds", "usecs")().usecs.to!suseconds_t; catch {}
timeval t = timeval(secs, us);
socklen_t len = t.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &t, len);
return errorHandler();
}
case TCPOption.TIMEOUT_SEND:
static if (!is(T == Duration))
assert(false, "TIMEOUT_SEND value type must be Duration, not " ~ T.stringof);
else {
import core.sys.posix.sys.time : timeval;
time_t secs = value.split!("seconds", "usecs")().seconds;
suseconds_t us;
try us = value.split!("seconds", "usecs")().usecs.to!suseconds_t; catch {}
timeval t = timeval(secs, us);
socklen_t len = t.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &t, len);
return errorHandler();
}
case TCPOption.TIMEOUT_HALFOPEN:
static if (!is(T == Duration))
assert(false, "TIMEOUT_SEND value type must be Duration, not " ~ T.stringof);
else {
uint val;
try val = value.total!"msecs".to!uint; catch {
return false;
}
socklen_t len = val.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &val, len);
return errorHandler();
}
case TCPOption.LINGER: // bool onOff, int seconds
static if (!is(T == Tuple!(bool, int)))
assert(false, "LINGER value type must be Tuple!(bool, int), not " ~ T.stringof);
else {
linger l = linger(val[0]?1:0, val[1]);
socklen_t llen = l.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, llen);
return errorHandler();
}
case TCPOption.CONGESTION:
static if (!isIntegral!T)
assert(false, "CONGESTION value type must be integral, not " ~ T.stringof);
else {
int val = value.to!int;
len = int.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_CONGESTION, &val, len);
return errorHandler();
}
case TCPOption.CORK:
static if (!isIntegral!T)
assert(false, "CORK value type must be int, not " ~ T.stringof);
else {
static if (EPOLL) {
int val = value.to!int;
socklen_t len = val.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_CORK, &val, len);
return errorHandler();
}
else /* if KQUEUE */ {
int val = value.to!int;
socklen_t len = val.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_NOPUSH, &val, len);
return errorHandler();
}
}
case TCPOption.DEFER_ACCEPT: // seconds
static if (!isIntegral!T)
assert(false, "DEFER_ACCEPT value type must be integral, not " ~ T.stringof);
else {
static if (EPOLL) {
int val = value.to!int;
socklen_t len = val.sizeof;
err = setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &val, len);
return errorHandler();
}
else /* if KQUEUE */ {
// todo: Emulate DEFER_ACCEPT with ACCEPT_FILTER(9)
/*int val = value.to!int;
socklen_t len = val.sizeof;
err = setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &val, len);
return errorHandler();
*/
assert(false, "TCPOption.DEFER_ACCEPT is not implemented");
}
}
}
}
uint recv(in fd_t fd, ref ubyte[] data)
{
try log("Recv from FD: " ~ fd.to!string); catch {}
m_status = StatusInfo.init;
import libasync.internals.socket_compat : recv;
int ret = cast(int) recv(fd, cast(void*) data.ptr, data.length, cast(int)0);
static if (LOG) log(".recv " ~ ret.to!string ~ " bytes of " ~ data.length.to!string ~ " @ " ~ fd.to!string);
if (catchError!".recv"(ret)){ // ret == SOCKET_ERROR == -1 ?
if (m_error == EPosix.EWOULDBLOCK || m_error == EPosix.EAGAIN)
m_status.code = Status.ASYNC;
return 0; // TODO: handle some errors more specifically
}
m_status.code = Status.OK;
return cast(uint) ret < 0 ? 0 : ret;
}
uint send(in fd_t fd, in ubyte[] data)
{
try log("Send to FD: " ~ fd.to!string); catch {}
m_status = StatusInfo.init;
import libasync.internals.socket_compat : send;
int ret = cast(int) send(fd, cast(const(void)*) data.ptr, data.length, cast(int)0);
if (catchError!"send"(ret)) { // ret == -1
if (m_error == EPosix.EWOULDBLOCK || m_error == EPosix.EAGAIN) {
m_status.code = Status.ASYNC;
return 0;
}
}
m_status.code = Status.OK;
return cast(uint) ret < 0 ? 0 : ret;
}
uint recvFrom(in fd_t fd, ref ubyte[] data, ref NetworkAddress addr)
{
import libasync.internals.socket_compat : recvfrom, AF_INET6, AF_INET, socklen_t;
m_status = StatusInfo.init;
addr.family = AF_INET6;
socklen_t addrLen = addr.sockAddrLen;
long ret = recvfrom(fd, cast(void*) data.ptr, data.length, 0, addr.sockAddr, &addrLen);
if (addrLen < addr.sockAddrLen) {
addr.family = AF_INET;
}
try log("RECVFROM " ~ ret.to!string ~ "B"); catch {}
if (catchError!".recvfrom"(ret)) { // ret == -1
if (m_error == EPosix.EWOULDBLOCK || m_error == EPosix.EAGAIN)
m_status.code = Status.ASYNC;
return 0;
}
m_status.code = Status.OK;
return cast(uint) ret;
}
uint sendTo(in fd_t fd, in ubyte[] data, in NetworkAddress addr)
{
import libasync.internals.socket_compat : sendto;
m_status = StatusInfo.init;
try log("SENDTO " ~ data.length.to!string ~ "B");
catch{}
long ret = sendto(fd, cast(void*) data.ptr, data.length, 0, addr.sockAddr, addr.sockAddrLen);
if (catchError!".sendto"(ret)) { // ret == -1
if (m_error == EPosix.EWOULDBLOCK || m_error == EPosix.EAGAIN)
m_status.code = Status.ASYNC;
return 0;
}
m_status.code = Status.OK;
return cast(uint) ret;
}
NetworkAddress localAddr(in fd_t fd, bool ipv6) {
NetworkAddress ret;
import libasync.internals.socket_compat : getsockname, AF_INET, AF_INET6, socklen_t, sockaddr;
if (ipv6)
ret.family = AF_INET6;
else
ret.family = AF_INET;
socklen_t len = ret.sockAddrLen;
int err = getsockname(fd, ret.sockAddr, &len);
if (catchError!"getsockname"(err))
return NetworkAddress.init;
if (len > ret.sockAddrLen)
ret.family = AF_INET6;
return ret;
}
bool notify(in fd_t fd, AsyncNotifier ctxt)
{
static if (EPOLL)
{
import core.sys.posix.unistd : write;
long val = 1;
fd_t err = cast(fd_t) write(fd, &val, long.sizeof);
if (catchError!"write(notify)"(err)) {
return false;
}
return true;
}
else /* if KQUEUE */
{
kevent_t _event;
EV_SET(&_event, fd, EVFILT_USER, EV_ENABLE | EV_CLEAR, NOTE_TRIGGER | 0x1, 0, ctxt.evInfo);
int err = kevent(m_kqueuefd, &_event, 1, null, 0, null);
if (catchError!"kevent_notify"(err)) {
return false;
}
return true;
}
}
bool notify(in fd_t fd, shared AsyncSignal ctxt)
{
static if (EPOLL)
{
sigval sigvl;
fd_t err;
sigvl.sival_ptr = cast(void*) ctxt;
try err = pthread_sigqueue(ctxt.pthreadId, fd, sigvl); catch {}
if (catchError!"sigqueue"(err)) {
return false;
}
}
else /* if KQUEUE */
{
import core.thread : getpid;
addSignal(ctxt);
try {
log("Notified fd: " ~ fd.to!string ~ " of PID " ~ getpid().to!string);
int err = core.sys.posix.signal.kill(getpid(), SIGXCPU);
if (catchError!"notify(signal)"(err))
assert(false, "Signal could not be raised");
} catch {}
}
return true;
}
// no known uses
uint read(in fd_t fd, ref ubyte[] data)
{
m_status = StatusInfo.init;
return 0;
}
// no known uses
uint write(in fd_t fd, in ubyte[] data)
{
m_status = StatusInfo.init;
return 0;
}
uint watch(in fd_t fd, in WatchInfo info) {
// note: info.wd is still 0 at this point.
m_status = StatusInfo.init;
import core.sys.linux.sys.inotify;
import std.file : dirEntries, isDir, SpanMode;
static if (EPOLL) {
// Manually handle recursivity... All events show up under the same inotify
uint events = info.events; // values for this API were pulled from inotify
if (events & IN_DELETE)
events |= IN_DELETE_SELF;
if (events & IN_MOVED_FROM)
events |= IN_MOVE_SELF;
nothrow fd_t addFolderRecursive(Path path) {
fd_t ret;
try {
ret = inotify_add_watch(fd, path.toNativeString().toStringz, events);
if (catchError!"inotify_add_watch"(ret))
return fd_t.init;
try log("inotify_add_watch(" ~ DWFolderInfo(WatchInfo(info.events, path, info.recursive, ret), fd).to!string ~ ")"); catch {}
assert(m_dwFolders.get(tuple(cast(fd_t) fd, cast(uint)ret), DWFolderInfo.init) == DWFolderInfo.init, "Could not get a unique watch descriptor for path, got: " ~ m_dwFolders[tuple(cast(fd_t)fd, cast(uint)ret)].to!string);
m_dwFolders[tuple(cast(fd_t)fd, cast(uint)ret)] = DWFolderInfo(WatchInfo(info.events, path, info.recursive, ret), fd);
if (info.recursive) {
foreach (de; path.toNativeString().dirEntries(SpanMode.shallow))
{
Path de_path = Path(de.name);
if (!de_path.absolute)
de_path = path ~ Path(de.name);
if (isDir(de_path.toNativeString()))
if (addFolderRecursive(de_path) == 0)
return 0;
}
}
} catch (Exception e) {
try setInternalError!"inotify_add_watch"(Status.ERROR, "Could not add directory " ~ path.toNativeString() ~ ": " ~ e.toString() ); catch {}
return 0;
}
return ret;
}
return addFolderRecursive(info.path);
} else /* if KQUEUE */ {
/// Manually handle recursivity & file tracking. Each folder is an event!
/// E.g. file creation shows up as a folder change, we must be prepared to seek the file.
import core.sys.posix.fcntl;
import libasync.internals.kqueue;
uint events;
if (info.events & DWFileEvent.CREATED)
events |= NOTE_LINK | NOTE_WRITE;
if (info.events & DWFileEvent.DELETED)
events |= NOTE_DELETE;
if (info.events & DWFileEvent.MODIFIED)
events |= NOTE_ATTRIB | NOTE_EXTEND | NOTE_WRITE;
if (info.events & DWFileEvent.MOVED_FROM)