eventcore.drivers.posix.sockets 1/452(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
8618
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
module eventcore.drivers.posix.sockets; @safe: import eventcore.driver; import eventcore.drivers.posix.driver; import eventcore.internal.utils; import std.algorithm.comparison : among, min, max; import std.socket : Address, AddressFamily, InternetAddress, Internet6Address, UnknownAddress; version (Posix) { import std.socket : UnixAddress; import core.sys.posix.netdb : AI_ADDRCONFIG, AI_V4MAPPED, addrinfo, freeaddrinfo, getaddrinfo; import core.sys.posix.netinet.in_; import core.sys.posix.netinet.tcp; import core.sys.posix.sys.un; import core.sys.posix.unistd : close, read, write; import core.stdc.errno : errno, EAGAIN, EINPROGRESS; import core.sys.posix.fcntl; version (linux) enum SO_REUSEPORT = 15; else enum SO_REUSEPORT = 0x200; static if (!is(typeof(O_CLOEXEC))) { version (linux) enum O_CLOEXEC = 0x80000; else version (FreeBSD) enum O_CLOEXEC = 0x100000; else version (DragonFlyBSD) enum O_CLOEXEC = 0x0020000; else version (NetBSD) enum O_CLOEXEC = 0x400000; else version (OpenBSD) enum O_CLOEXEC = 0x10000; else version (OSX) enum O_CLOEXEC = 0x1000000; } } version (linux) { extern (C) int accept4(int sockfd, sockaddr *addr, socklen_t *addrlen, int flags) nothrow @nogc; static if (!is(typeof(SOCK_NONBLOCK))) enum SOCK_NONBLOCK = 0x800; static if (!is(typeof(SOCK_CLOEXEC))) enum SOCK_CLOEXEC = 0x80000; static if (__VERSION__ < 2077) { enum IP_ADD_MEMBERSHIP = 35; enum IP_MULTICAST_LOOP = 34; } else import core.sys.linux.netinet.in_ : IP_ADD_MEMBERSHIP, IP_MULTICAST_LOOP; } version(OSX) { static if (__VERSION__ < 2077) { enum IP_ADD_MEMBERSHIP = 12; enum IP_MULTICAST_LOOP = 11; } else import core.sys.darwin.netinet.in_ : IP_ADD_MEMBERSHIP, IP_MULTICAST_LOOP; } version(FreeBSD) { static if (__VERSION__ < 2077) { enum IP_ADD_MEMBERSHIP = 12; enum IP_MULTICAST_LOOP = 11; } else import core.sys.freebsd.netinet.in_ : IP_ADD_MEMBERSHIP, IP_MULTICAST_LOOP; } version(DragonFlyBSD) { import core.sys.dragonflybsd.netinet.in_ : IP_ADD_MEMBERSHIP, IP_MULTICAST_LOOP; } version (Solaris) { enum IP_ADD_MEMBERSHIP = 0x13; enum IP_MULTICAST_LOOP = 0x12; } version (Windows) { import core.sys.windows.windows; import core.sys.windows.winsock2; alias sockaddr_storage = SOCKADDR_STORAGE; alias EAGAIN = WSAEWOULDBLOCK; enum SHUT_RDWR = SD_BOTH; enum SHUT_RD = SD_RECEIVE; enum SHUT_WR = SD_SEND; extern (C) int read(int fd, void *buffer, uint count) nothrow; extern (C) int write(int fd, const(void) *buffer, uint count) nothrow; extern (C) int close(int fd) nothrow @safe; } final class PosixEventDriverSockets(Loop : PosixEventLoop) : EventDriverSockets { @safe: /*@nogc:*/ nothrow: private Loop m_loop; this(Loop loop) { m_loop = loop; } final override StreamSocketFD connectStream(scope Address address, scope Address bind_address, ConnectCallback on_connect) { assert(on_connect !is null); auto sockfd = createSocket(address.addressFamily, SOCK_STREAM); if (sockfd == -1) { on_connect(StreamSocketFD.invalid, ConnectStatus.socketCreateFailure); return StreamSocketFD.invalid; } auto sock = cast(StreamSocketFD)sockfd; void invalidateSocket() @nogc @trusted nothrow { closeSocket(sockfd); sock = StreamSocketFD.invalid; } int bret; if (bind_address !is null) () @trusted { bret = bind(cast(sock_t)sock, bind_address.name, bind_address.nameLen); } (); if (bret != 0) { invalidateSocket(); on_connect(sock, ConnectStatus.bindFailure); return sock; } m_loop.initFD(sock, FDFlags.none, StreamSocketSlot.init); m_loop.registerFD(sock, EventMask.read|EventMask.write|EventMask.status); m_loop.setNotifyCallback!(EventType.status)(sock, &onConnectError); releaseRef(sock); // onConnectError callback is weak reference auto ret = () @trusted { return connect(cast(sock_t)sock, address.name, address.nameLen); } (); if (ret == 0) { m_loop.m_fds[sock].specific.state = ConnectionState.connected; on_connect(sock, ConnectStatus.connected); } else { auto err = getSocketError(); if (err.among!(EAGAIN, EINPROGRESS)) { with (m_loop.m_fds[sock].streamSocket) { connectCallback = on_connect; state = ConnectionState.connecting; } m_loop.setNotifyCallback!(EventType.write)(sock, &onConnect); } else { m_loop.clearFD!StreamSocketSlot(sock); m_loop.unregisterFD(sock, EventMask.read|EventMask.write|EventMask.status); invalidateSocket(); on_connect(StreamSocketFD.invalid, ConnectStatus.unknownError); return StreamSocketFD.invalid; } } return sock; } final override void cancelConnectStream(StreamSocketFD sock) { assert(sock != StreamSocketFD.invalid, "Invalid socket descriptor"); with (m_loop.m_fds[sock].streamSocket) { assert(state == ConnectionState.connecting, "Unable to cancel connect on the socket that is not in connecting state"); state = ConnectionState.closed; connectCallback = null; m_loop.setNotifyCallback!(EventType.status)(sock, null); m_loop.setNotifyCallback!(EventType.write)(sock, null); m_loop.clearFD!StreamSocketSlot(sock); m_loop.unregisterFD(sock, EventMask.read|EventMask.write|EventMask.status); closeSocket(cast(sock_t)sock.value); } } final override StreamSocketFD adoptStream(int socket) { auto fd = StreamSocketFD(socket); if (m_loop.m_fds[fd].common.refCount) // FD already in use? return StreamSocketFD.invalid; setSocketNonBlocking(fd); m_loop.initFD(fd, FDFlags.none, StreamSocketSlot.init); m_loop.registerFD(fd, EventMask.read|EventMask.write|EventMask.status); return fd; } private void onConnect(FD fd) { auto sock = cast(StreamSocketFD)fd; auto l = lockHandle(sock); m_loop.setNotifyCallback!(EventType.write)(sock, null); with (m_loop.m_fds[sock].streamSocket) { state = ConnectionState.connected; auto cb = connectCallback; connectCallback = null; if (cb) cb(sock, ConnectStatus.connected); } } private void onConnectError(FD sock) { // FIXME: determine the correct kind of error! with (m_loop.m_fds[sock].streamSocket) { state = ConnectionState.closed; auto cb = connectCallback; connectCallback = null; if (cb) cb(cast(StreamSocketFD)sock, ConnectStatus.refused); } } alias listenStream = EventDriverSockets.listenStream; final override StreamListenSocketFD listenStream(scope Address address, StreamListenOptions options, AcceptCallback on_accept) { auto sockfd = createSocket(address.addressFamily, SOCK_STREAM); if (sockfd == -1) return StreamListenSocketFD.invalid; auto sock = cast(StreamListenSocketFD)sockfd; void invalidateSocket() @nogc @trusted nothrow { closeSocket(sockfd); sock = StreamSocketFD.invalid; } () @trusted { int tmp_reuse = 1; // FIXME: error handling! if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &tmp_reuse, tmp_reuse.sizeof) != 0) { invalidateSocket(); return; } version (Windows) {} else { if ((options & StreamListenOptions.reusePort) && setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &tmp_reuse, tmp_reuse.sizeof) != 0) { invalidateSocket(); return; } } if (bind(sockfd, address.name, address.nameLen) != 0) { invalidateSocket(); return; } if (listen(sockfd, getBacklogSize()) != 0) { invalidateSocket(); return; } } (); if (sock == StreamListenSocketFD.invalid) return sock; m_loop.initFD(sock, FDFlags.none, StreamListenSocketSlot.init); if (on_accept) waitForConnections(sock, on_accept); return sock; } final override void waitForConnections(StreamListenSocketFD sock, AcceptCallback on_accept) { m_loop.registerFD(sock, EventMask.read, false); m_loop.m_fds[sock].streamListen.acceptCallback = on_accept; m_loop.setNotifyCallback!(EventType.read)(sock, &onAccept); onAccept(sock); } private void onAccept(FD listenfd) { sock_t sockfd; sockaddr_storage addr; socklen_t addr_len = addr.sizeof; version (linux) { () @trusted { sockfd = accept4(cast(sock_t)listenfd, () @trusted { return cast(sockaddr*)&addr; } (), &addr_len, SOCK_NONBLOCK | SOCK_CLOEXEC); } (); if (sockfd == -1) return; } else { () @trusted { sockfd = accept(cast(sock_t)listenfd, () @trusted { return cast(sockaddr*)&addr; } (), &addr_len); } (); if (sockfd == -1) return; setSocketNonBlocking(cast(SocketFD)sockfd, true); } auto fd = cast(StreamSocketFD)sockfd; m_loop.initFD(fd, FDFlags.none, StreamSocketSlot.init); m_loop.m_fds[fd].streamSocket.state = ConnectionState.connected; m_loop.registerFD(fd, EventMask.read|EventMask.write|EventMask.status); m_loop.setNotifyCallback!(EventType.status)(fd, &onConnectError); releaseRef(fd); // onConnectError callback is weak reference //print("accept %d", sockfd); scope RefAddress addrc = new RefAddress(() @trusted { return cast(sockaddr*)&addr; } (), addr_len); m_loop.m_fds[listenfd].streamListen.acceptCallback(cast(StreamListenSocketFD)listenfd, fd, addrc); } ConnectionState getConnectionState(StreamSocketFD sock) { return m_loop.m_fds[sock].streamSocket.state; } final override bool getLocalAddress(SocketFD sock, scope RefAddress dst) { socklen_t addr_len = dst.nameLen; if (() @trusted { return getsockname(cast(sock_t)sock, dst.name, &addr_len); } () != 0) return false; dst.cap(addr_len); return true; } final override bool getRemoteAddress(SocketFD sock, scope RefAddress dst) { socklen_t addr_len = dst.nameLen; if (() @trusted { return getpeername(cast(sock_t)sock, dst.name, &addr_len); } () != 0) return false; dst.cap(addr_len); return true; } final override void setTCPNoDelay(StreamSocketFD socket, bool enable) { int opt = enable; () @trusted { setsockopt(cast(sock_t)socket, IPPROTO_TCP, TCP_NODELAY, cast(char*)&opt, opt.sizeof); } (); } final override void setKeepAlive(StreamSocketFD socket, bool enable) { ubyte opt = enable; () @trusted { setsockopt(cast(sock_t)socket, SOL_SOCKET, SO_KEEPALIVE, cast(char*)&opt, opt.sizeof); } (); } final override void read(StreamSocketFD socket, ubyte[] buffer, IOMode mode, IOCallback on_read_finish) { /*if (buffer.length == 0) { on_read_finish(socket, IOStatus.ok, 0); return; }*/ sizediff_t ret; () @trusted { ret = .recv(cast(sock_t)socket, buffer.ptr, min(buffer.length, int.max), 0); } (); if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { print("sock error %s!", err); on_read_finish(socket, IOStatus.error, 0); return; } } if (ret == 0 && buffer.length > 0) { on_read_finish(socket, IOStatus.disconnected, 0); return; } if (ret < 0 && mode == IOMode.immediate) { on_read_finish(socket, IOStatus.wouldBlock, 0); return; } if (ret >= 0) { buffer = buffer[ret .. $]; if (mode != IOMode.all || buffer.length == 0) { on_read_finish(socket, IOStatus.ok, ret); return; } } // NOTE: since we know that not all data was read from the stream // socket, the next call to recv is guaranteed to return EGAIN // and we can avoid that call. with (m_loop.m_fds[socket].streamSocket) { readCallback = on_read_finish; readMode = mode; bytesRead = ret > 0 ? ret : 0; readBuffer = buffer; } m_loop.setNotifyCallback!(EventType.read)(socket, &onSocketRead); } override void cancelRead(StreamSocketFD socket) { assert(m_loop.m_fds[socket].streamSocket.readCallback !is null, "Cancelling read when there is no read in progress."); m_loop.setNotifyCallback!(EventType.read)(socket, null); with (m_loop.m_fds[socket].streamSocket) { readBuffer = null; } } private void onSocketRead(FD fd) { auto slot = () @trusted { return &m_loop.m_fds[fd].streamSocket(); } (); auto socket = cast(StreamSocketFD)fd; void finalize()(IOStatus status) { auto l = lockHandle(socket); m_loop.setNotifyCallback!(EventType.read)(socket, null); assert(m_loop.m_fds[socket].common.refCount > 0); //m_fds[fd].readBuffer = null; slot.readCallback(socket, status, slot.bytesRead); assert(m_loop.m_fds[socket].common.refCount > 0); } sizediff_t ret = 0; () @trusted { ret = .recv(cast(sock_t)socket, slot.readBuffer.ptr, min(slot.readBuffer.length, int.max), 0); } (); if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { finalize(IOStatus.error); return; } } if (ret == 0 && slot.readBuffer.length) { slot.state = ConnectionState.passiveClose; finalize(IOStatus.disconnected); return; } if (ret > 0 || !slot.readBuffer.length) { slot.bytesRead += ret; slot.readBuffer = slot.readBuffer[ret .. $]; if (slot.readMode != IOMode.all || slot.readBuffer.length == 0) { finalize(IOStatus.ok); return; } } } final override void write(StreamSocketFD socket, const(ubyte)[] buffer, IOMode mode, IOCallback on_write_finish) { if (buffer.length == 0) { on_write_finish(socket, IOStatus.ok, 0); return; } sizediff_t ret; () @trusted { ret = .send(cast(sock_t)socket, buffer.ptr, min(buffer.length, int.max), 0); } (); if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { on_write_finish(socket, IOStatus.error, 0); return; } if (mode == IOMode.immediate) { on_write_finish(socket, IOStatus.wouldBlock, 0); return; } } size_t bytes_written = 0; if (ret >= 0) { bytes_written += ret; buffer = buffer[ret .. $]; if (mode != IOMode.all || buffer.length == 0) { on_write_finish(socket, IOStatus.ok, bytes_written); return; } } // NOTE: since we know that not all data was writtem to the stream // socket, the next call to send is guaranteed to return EGAIN // and we can avoid that call. with (m_loop.m_fds[socket].streamSocket) { writeCallback = on_write_finish; writeMode = mode; bytesWritten = ret >= 0 ? ret : 0; writeBuffer = buffer; } m_loop.setNotifyCallback!(EventType.write)(socket, &onSocketWrite); } override void cancelWrite(StreamSocketFD socket) { assert(m_loop.m_fds[socket].streamSocket.writeCallback !is null, "Cancelling write when there is no write in progress."); m_loop.setNotifyCallback!(EventType.write)(socket, null); m_loop.m_fds[socket].streamSocket.writeBuffer = null; } private void onSocketWrite(FD fd) { auto slot = () @trusted { return &m_loop.m_fds[fd].streamSocket(); } (); auto socket = cast(StreamSocketFD)fd; sizediff_t ret; () @trusted { ret = .send(cast(sock_t)socket, slot.writeBuffer.ptr, min(slot.writeBuffer.length, int.max), 0); } (); if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { auto l = lockHandle(socket); m_loop.setNotifyCallback!(EventType.write)(socket, null); slot.writeCallback(socket, IOStatus.error, slot.bytesRead); return; } } if (ret >= 0) { slot.bytesWritten += ret; slot.writeBuffer = slot.writeBuffer[ret .. $]; if (slot.writeMode != IOMode.all || slot.writeBuffer.length == 0) { auto l = lockHandle(socket); m_loop.setNotifyCallback!(EventType.write)(socket, null); slot.writeCallback(cast(StreamSocketFD)socket, IOStatus.ok, slot.bytesWritten); return; } } } final override void waitForData(StreamSocketFD socket, IOCallback on_data_available) { sizediff_t ret; ubyte dummy; () @trusted { ret = recv(cast(sock_t)socket, &dummy, 1, MSG_PEEK); } (); if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { on_data_available(socket, IOStatus.error, 0); return; } } size_t bytes_read = 0; if (ret == 0) { on_data_available(socket, IOStatus.disconnected, 0); return; } if (ret > 0) { on_data_available(socket, IOStatus.ok, 0); return; } with (m_loop.m_fds[socket].streamSocket) { readCallback = on_data_available; readMode = IOMode.once; bytesRead = 0; readBuffer = null; } m_loop.setNotifyCallback!(EventType.read)(socket, &onSocketDataAvailable); } private void onSocketDataAvailable(FD fd) { auto slot = () @trusted { return &m_loop.m_fds[fd].streamSocket(); } (); auto socket = cast(StreamSocketFD)fd; void finalize()(IOStatus status) { auto l = lockHandle(socket); m_loop.setNotifyCallback!(EventType.read)(socket, null); //m_fds[fd].readBuffer = null; slot.readCallback(socket, status, 0); } sizediff_t ret; ubyte tmp; () @trusted { ret = recv(cast(sock_t)socket, &tmp, 1, MSG_PEEK); } (); if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) finalize(IOStatus.error); } else finalize(ret ? IOStatus.ok : IOStatus.disconnected); } final override void shutdown(StreamSocketFD socket, bool shut_read, bool shut_write) { auto st = m_loop.m_fds[socket].streamSocket.state; () @trusted { .shutdown(cast(sock_t)socket, shut_read ? shut_write ? SHUT_RDWR : SHUT_RD : shut_write ? SHUT_WR : 0); } (); if (st == ConnectionState.passiveClose) shut_read = true; if (st == ConnectionState.activeClose) shut_write = true; m_loop.m_fds[socket].streamSocket.state = shut_read ? shut_write ? ConnectionState.closed : ConnectionState.passiveClose : shut_write ? ConnectionState.activeClose : ConnectionState.connected; } final override DatagramSocketFD createDatagramSocket(scope Address bind_address, scope Address target_address) { return createDatagramSocketInternal(bind_address, target_address, false); } package DatagramSocketFD createDatagramSocketInternal(scope Address bind_address, scope Address target_address, bool is_internal = true) { auto sockfd = createSocket(bind_address.addressFamily, SOCK_DGRAM); if (sockfd == -1) return DatagramSocketFD.invalid; auto sock = cast(DatagramSocketFD)sockfd; if (bind_address && () @trusted { return bind(sockfd, bind_address.name, bind_address.nameLen); } () != 0) { closeSocket(sockfd); return DatagramSocketFD.init; } if (target_address) { int ret; if (target_address is bind_address) { // special case of bind_address==target_address: determine the actual bind address // in case of a zero port sockaddr_storage sa; socklen_t addr_len = sa.sizeof; if (() @trusted { return getsockname(sockfd, cast(sockaddr*)&sa, &addr_len); } () != 0) { closeSocket(sockfd); return DatagramSocketFD.init; } ret = () @trusted { return connect(sockfd, cast(sockaddr*)&sa, addr_len); } (); } else ret = () @trusted { return connect(sockfd, target_address.name, target_address.nameLen); } (); if (ret != 0) { closeSocket(sockfd); return DatagramSocketFD.init; } } m_loop.initFD(sock, is_internal ? FDFlags.internal : FDFlags.none, DgramSocketSlot.init); m_loop.registerFD(sock, EventMask.read|EventMask.write|EventMask.status); return sock; } final override DatagramSocketFD adoptDatagramSocket(int socket) { return adoptDatagramSocketInternal(socket, false); } package DatagramSocketFD adoptDatagramSocketInternal(int socket, bool is_internal = true, bool close_on_exec = false) { auto fd = DatagramSocketFD(socket); if (m_loop.m_fds[fd].common.refCount) // FD already in use? return DatagramSocketFD.init; setSocketNonBlocking(fd, close_on_exec); m_loop.initFD(fd, is_internal ? FDFlags.internal : FDFlags.none, DgramSocketSlot.init); m_loop.registerFD(fd, EventMask.read|EventMask.write|EventMask.status); return fd; } final override void setTargetAddress(DatagramSocketFD socket, scope Address target_address) { () @trusted { connect(cast(sock_t)socket, target_address.name, target_address.nameLen); } (); } final override bool setBroadcast(DatagramSocketFD socket, bool enable) { int tmp_broad = enable; return () @trusted { return setsockopt(cast(sock_t)socket, SOL_SOCKET, SO_BROADCAST, &tmp_broad, tmp_broad.sizeof); } () == 0; } final override bool joinMulticastGroup(DatagramSocketFD socket, scope Address multicast_address, uint interface_index = 0) { switch (multicast_address.addressFamily) { default: assert(false, "Multicast only supported for IPv4/IPv6 sockets."); case AddressFamily.INET: struct ip_mreq { in_addr imr_multiaddr; /* IP multicast address of group */ in_addr imr_interface; /* local IP address of interface */ } auto addr = () @trusted { return cast(sockaddr_in*)multicast_address.name; } (); ip_mreq mreq; mreq.imr_multiaddr = addr.sin_addr; mreq.imr_interface.s_addr = htonl(interface_index); return () @trusted { return setsockopt(cast(sock_t)socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, ip_mreq.sizeof); } () == 0; case AddressFamily.INET6: version (Windows) { struct ipv6_mreq { in6_addr ipv6mr_multiaddr; uint ipv6mr_interface; } } auto addr = () @trusted { return cast(sockaddr_in6*)multicast_address.name; } (); ipv6_mreq mreq; mreq.ipv6mr_multiaddr = addr.sin6_addr; mreq.ipv6mr_interface = htonl(interface_index); return () @trusted { return setsockopt(cast(sock_t)socket, IPPROTO_IP, IPV6_JOIN_GROUP, &mreq, ipv6_mreq.sizeof); } () == 0; } } void receive(DatagramSocketFD socket, ubyte[] buffer, IOMode mode, DatagramIOCallback on_receive_finish) @trusted { // DMD 2.072.0-b2: scope considered unsafe import std.typecons : scoped; assert(mode != IOMode.all, "Only IOMode.immediate and IOMode.once allowed for datagram sockets."); sizediff_t ret; sockaddr_storage src_addr; socklen_t src_addr_len = src_addr.sizeof; () @trusted { ret = .recvfrom(cast(sock_t)socket, buffer.ptr, min(buffer.length, int.max), 0, cast(sockaddr*)&src_addr, &src_addr_len); } (); if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { print("sock error %s for %s!", err, socket); on_receive_finish(socket, IOStatus.error, 0, null); return; } if (mode == IOMode.immediate) { on_receive_finish(socket, IOStatus.wouldBlock, 0, null); } else { with (m_loop.m_fds[socket].datagramSocket) { readCallback = on_receive_finish; readMode = mode; bytesRead = 0; readBuffer = buffer; } m_loop.setNotifyCallback!(EventType.read)(socket, &onDgramRead); } return; } scope src_addrc = new RefAddress(() @trusted { return cast(sockaddr*)&src_addr; } (), src_addr_len); on_receive_finish(socket, IOStatus.ok, ret, src_addrc); } void cancelReceive(DatagramSocketFD socket) { assert(m_loop.m_fds[socket].datagramSocket.readCallback !is null, "Cancelling read when there is no read in progress."); m_loop.setNotifyCallback!(EventType.read)(socket, null); m_loop.m_fds[socket].datagramSocket.readBuffer = null; } private void onDgramRead(FD fd) @trusted { // DMD 2.072.0-b2: scope considered unsafe auto slot = () @trusted { return &m_loop.m_fds[fd].datagramSocket(); } (); auto socket = cast(DatagramSocketFD)fd; sizediff_t ret; sockaddr_storage src_addr; socklen_t src_addr_len = src_addr.sizeof; () @trusted { ret = .recvfrom(cast(sock_t)socket, slot.readBuffer.ptr, min(slot.readBuffer.length, int.max), 0, cast(sockaddr*)&src_addr, &src_addr_len); } (); if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { auto l = lockHandle(socket); m_loop.setNotifyCallback!(EventType.read)(socket, null); slot.readCallback(socket, IOStatus.error, 0, null); return; } } auto l = lockHandle(socket); m_loop.setNotifyCallback!(EventType.read)(socket, null); scope src_addrc = new RefAddress(() @trusted { return cast(sockaddr*)&src_addr; } (), src_addr.sizeof); () @trusted { return cast(DatagramIOCallback)slot.readCallback; } ()(socket, IOStatus.ok, ret, src_addrc); } void send(DatagramSocketFD socket, const(ubyte)[] buffer, IOMode mode, Address target_address, DatagramIOCallback on_send_finish) { assert(mode != IOMode.all, "Only IOMode.immediate and IOMode.once allowed for datagram sockets."); sizediff_t ret; if (target_address) { () @trusted { ret = .sendto(cast(sock_t)socket, buffer.ptr, min(buffer.length, int.max), 0, target_address.name, target_address.nameLen); } (); m_loop.m_fds[socket].datagramSocket.targetAddr = target_address; } else { () @trusted { ret = .send(cast(sock_t)socket, buffer.ptr, min(buffer.length, int.max), 0); } (); } if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { print("sock error %s!", err); on_send_finish(socket, IOStatus.error, 0, null); return; } if (mode == IOMode.immediate) { on_send_finish(socket, IOStatus.wouldBlock, 0, null); } else { with (m_loop.m_fds[socket].datagramSocket) { writeCallback = on_send_finish; writeMode = mode; bytesWritten = 0; writeBuffer = buffer; } m_loop.setNotifyCallback!(EventType.write)(socket, &onDgramWrite); } return; } on_send_finish(socket, IOStatus.ok, ret, null); } void cancelSend(DatagramSocketFD socket) { assert(m_loop.m_fds[socket].datagramSocket.writeCallback !is null, "Cancelling write when there is no write in progress."); m_loop.setNotifyCallback!(EventType.write)(socket, null); m_loop.m_fds[socket].datagramSocket.writeBuffer = null; } private void onDgramWrite(FD fd) { auto slot = () @trusted { return &m_loop.m_fds[fd].datagramSocket(); } (); auto socket = cast(DatagramSocketFD)fd; sizediff_t ret; if (slot.targetAddr) { () @trusted { ret = .sendto(cast(sock_t)socket, slot.writeBuffer.ptr, min(slot.writeBuffer.length, int.max), 0, slot.targetAddr.name, slot.targetAddr.nameLen); } (); } else { () @trusted { ret = .send(cast(sock_t)socket, slot.writeBuffer.ptr, min(slot.writeBuffer.length, int.max), 0); } (); } if (ret < 0) { auto err = getSocketError(); if (!err.among!(EAGAIN, EINPROGRESS)) { auto l = lockHandle(socket); m_loop.setNotifyCallback!(EventType.write)(socket, null); () @trusted { return cast(DatagramIOCallback)slot.writeCallback; } ()(socket, IOStatus.error, 0, null); return; } } auto l = lockHandle(socket); m_loop.setNotifyCallback!(EventType.write)(socket, null); () @trusted { return cast(DatagramIOCallback)slot.writeCallback; } ()(socket, IOStatus.ok, ret, null); } final override void addRef(SocketFD fd) { auto slot = () @trusted { return &m_loop.m_fds[fd]; } (); assert(slot.common.refCount > 0, "Adding reference to unreferenced socket FD."); slot.common.refCount++; } final override bool releaseRef(SocketFD fd) { import taggedalgebraic : hasType; auto slot = () @trusted { return &m_loop.m_fds[fd]; } (); nogc_assert(slot.common.refCount > 0, "Releasing reference to unreferenced socket FD."); // listening sockets have an incremented the reference count because of setNotifyCallback int base_refcount = slot.specific.hasType!StreamListenSocketSlot ? 1 : 0; if (--slot.common.refCount == base_refcount) { m_loop.unregisterFD(fd, EventMask.read|EventMask.write|EventMask.status); switch (slot.specific.kind) with (slot.specific.Kind) { default: assert(false, "File descriptor slot is not a socket."); case streamSocket: m_loop.clearFD!StreamSocketSlot(fd); break; case streamListen: m_loop.setNotifyCallback!(EventType.read)(fd, null); m_loop.clearFD!StreamListenSocketSlot(fd); break; case datagramSocket: m_loop.clearFD!DgramSocketSlot(fd); break; } closeSocket(cast(sock_t)fd); return false; } return true; } final override bool setOption(DatagramSocketFD socket, DatagramSocketOption option, bool enable) { int proto, opt; final switch (option) { case DatagramSocketOption.broadcast: proto = SOL_SOCKET; opt = SO_BROADCAST; break; case DatagramSocketOption.multicastLoopback: proto = IPPROTO_IP; opt = IP_MULTICAST_LOOP; break; } int tmp = enable; return () @trusted { return setsockopt(cast(sock_t)socket, proto, opt, &tmp, tmp.sizeof); } () == 0; } final override bool setOption(StreamSocketFD socket, StreamSocketOption option, bool enable) { int proto, opt; final switch (option) { case StreamSocketOption.noDelay: proto = IPPROTO_TCP; opt = TCP_NODELAY; break; case StreamSocketOption.keepAlive: proto = SOL_SOCKET; opt = SO_KEEPALIVE; break; } int tmp = enable; return () @trusted { return setsockopt(cast(sock_t)socket, proto, opt, &tmp, tmp.sizeof); } () == 0; } final protected override void* rawUserData(StreamSocketFD descriptor, size_t size, DataInitializer initialize, DataInitializer destroy) @system { return m_loop.rawUserDataImpl(descriptor, size, initialize, destroy); } final protected override void* rawUserData(StreamListenSocketFD descriptor, size_t size, DataInitializer initialize, DataInitializer destroy) @system { return m_loop.rawUserDataImpl(descriptor, size, initialize, destroy); } final protected override void* rawUserData(DatagramSocketFD descriptor, size_t size, DataInitializer initialize, DataInitializer destroy) @system { return m_loop.rawUserDataImpl(descriptor, size, initialize, destroy); } private sock_t createSocket(AddressFamily family, int type) { sock_t sock; version (linux) { () @trusted { sock = socket(family, type | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); } (); if (sock == -1) return -1; } else { () @trusted { sock = socket(family, type, 0); } (); if (sock == -1) return -1; setSocketNonBlocking(cast(SocketFD)sock, true); } return sock; } // keeps a scoped reference to a handle to avoid it getting destroyed private auto lockHandle(H)(H handle) { addRef(handle); static struct R { PosixEventDriverSockets drv; H handle; @disable this(this); ~this() { drv.releaseRef(handle); } } return R(this, handle); } } package struct StreamSocketSlot { alias Handle = StreamSocketFD; size_t bytesRead; ubyte[] readBuffer; IOMode readMode; IOCallback readCallback; // FIXME: this type only works for stream sockets size_t bytesWritten; const(ubyte)[] writeBuffer; IOMode writeMode; IOCallback writeCallback; // FIXME: this type only works for stream sockets ConnectCallback connectCallback; ConnectionState state; } package struct StreamListenSocketSlot { alias Handle = StreamListenSocketFD; AcceptCallback acceptCallback; } package struct DgramSocketSlot { alias Handle = DatagramSocketFD; size_t bytesRead; ubyte[] readBuffer; IOMode readMode; DatagramIOCallback readCallback; // FIXME: this type only works for stream sockets size_t bytesWritten; const(ubyte)[] writeBuffer; IOMode writeMode; DatagramIOCallback writeCallback; // FIXME: this type only works for stream sockets Address targetAddr; } private void closeSocket(sock_t sockfd) @nogc nothrow { version (Windows) () @trusted { closesocket(sockfd); } (); else close(sockfd); } private void setSocketNonBlocking(SocketFD sockfd, bool close_on_exec = false) @nogc nothrow { version (Windows) { uint enable = 1; () @trusted { ioctlsocket(sockfd, FIONBIO, &enable); } (); } else { int f = O_NONBLOCK; if (close_on_exec) f |= O_CLOEXEC; () @trusted { fcntl(cast(int)sockfd, F_SETFL, f); } (); } } private int getSocketError() @nogc nothrow { version (Windows) return WSAGetLastError(); else return errno; } private int getBacklogSize() @trusted @nogc nothrow { int backlog = 128; version (linux) { import core.stdc.stdio : fclose, fopen, fscanf; auto somaxconn = fopen("/proc/sys/net/core/somaxconn", "re"); if (somaxconn) { int tmp; if (fscanf(somaxconn, "%d", &tmp) == 1) backlog = tmp; fclose(somaxconn); } } return backlog; }