vibe.core.net 0/108(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
860
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
/** TCP/UDP connection and server handling. Copyright: © 2012-2014 RejectedSoftware e.K. Authors: Sönke Ludwig License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. */ module vibe.core.net; public import vibe.core.stream; public import std.socket : AddressFamily; import vibe.core.driver; import vibe.core.log; import core.sys.posix.netinet.in_; import core.time; import std.exception; import std.functional; import std.string; @safe: /** Resolves the given host name/IP address string. Setting use_dns to false will only allow IP address strings but also guarantees that the call will not block. */ NetworkAddress resolveHost(string host, AddressFamily address_family = AddressFamily.UNSPEC, bool use_dns = true) { return resolveHost(host, cast(ushort)address_family, use_dns); } /// ditto NetworkAddress resolveHost(string host, ushort address_family, bool use_dns = true) { return getEventDriver().resolveHost(host, address_family, use_dns); } /** Starts listening on the specified port. 'connection_callback' will be called for each client that connects to the server socket. Each new connection gets its own fiber. The stream parameter then allows to perform blocking I/O on the client socket. The address parameter can be used to specify the network interface on which the server socket is supposed to listen for connections. By default, all IPv4 and IPv6 interfaces will be used. Using a `@system` callback is scheduled for deprecation. Use a `@safe` callback instead. */ TCPListener[] listenTCP(ushort port, void delegate(TCPConnection stream) @safe connection_callback, TCPListenOptions options = TCPListenOptions.defaults) { TCPListener[] ret; try ret ~= listenTCP(port, connection_callback, "::", options); catch (Exception e) logDiagnostic("Failed to listen on \"::\": %s", e.msg); try ret ~= listenTCP(port, connection_callback, "0.0.0.0", options); catch (Exception e) logDiagnostic("Failed to listen on \"0.0.0.0\": %s", e.msg); enforce(ret.length > 0, format("Failed to listen on all interfaces on port %s", port)); return ret; } /// ditto TCPListener listenTCP(ushort port, void delegate(TCPConnection stream) @safe connection_callback, string address, TCPListenOptions options = TCPListenOptions.defaults) { return getEventDriver().listenTCP(port, connection_callback, address, options); } /// ditto TCPListener[] listenTCP(ushort port, void delegate(TCPConnection stream) @system connection_callback, TCPListenOptions options = TCPListenOptions.defaults) @system { return listenTCP(port, (s) @trusted => connection_callback(s), options); } /// ditto TCPListener listenTCP(ushort port, void delegate(TCPConnection stream) @system connection_callback, string address, TCPListenOptions options = TCPListenOptions.defaults) @system { return listenTCP(port, (s) @trusted => connection_callback(s), address, options); } /** Starts listening on the specified port. This function is the same as listenTCP but takes a function callback instead of a delegate. */ TCPListener[] listenTCP_s(ushort port, void function(TCPConnection stream) @safe connection_callback, TCPListenOptions options = TCPListenOptions.defaults) { return listenTCP(port, () @trusted { return toDelegate(connection_callback); } (), options); } /// ditto TCPListener listenTCP_s(ushort port, void function(TCPConnection stream) @safe connection_callback, string address, TCPListenOptions options = TCPListenOptions.defaults) { return listenTCP(port, () @trusted { return toDelegate(connection_callback); } (), address, options); } /** Establishes a connection to the given host/port. */ TCPConnection connectTCP(string host, ushort port, string bind_interface = null, ushort bind_port = 0) { NetworkAddress addr = resolveHost(host); if (addr.family != AddressFamily.UNIX) addr.port = port; NetworkAddress bind_address; if (bind_interface.length) bind_address = resolveHost(bind_interface, addr.family); else { bind_address.family = addr.family; if (bind_address.family == AddressFamily.INET) bind_address.sockAddrInet4.sin_addr.s_addr = 0; else if (bind_address.family != AddressFamily.UNIX) bind_address.sockAddrInet6.sin6_addr.s6_addr[] = 0; } if (addr.family != AddressFamily.UNIX) bind_address.port = bind_port; return getEventDriver().connectTCP(addr, bind_address); } /// ditto TCPConnection connectTCP(NetworkAddress addr, NetworkAddress bind_address = anyAddress) { if (bind_address.family == AddressFamily.UNSPEC) { bind_address.family = addr.family; if (bind_address.family == AddressFamily.INET) bind_address.sockAddrInet4.sin_addr.s_addr = 0; else if (bind_address.family != AddressFamily.UNIX) bind_address.sockAddrInet6.sin6_addr.s6_addr[] = 0; if (bind_address.family != AddressFamily.UNIX) bind_address.port = 0; } enforce(addr.family == bind_address.family, "Destination address and bind address have different address families."); return getEventDriver().connectTCP(addr, bind_address); } /** Creates a bound UDP socket suitable for sending and receiving packets. */ UDPConnection listenUDP(ushort port, string bind_address = "0.0.0.0") { return getEventDriver().listenUDP(port, bind_address); } NetworkAddress anyAddress() { NetworkAddress ret; ret.family = AddressFamily.UNSPEC; return ret; } /** Represents a network/socket address. To construct a `NetworkAddress`, use either `resolveHost` or set the `family` property accordingly, followed by setting the fields of `sockAddrInet4`/`sockAddrInet6`/`sockAddrUnix`. */ struct NetworkAddress { version(Windows) { import core.sys.windows.winsock2 : sockaddr, sockaddr_in, sockaddr_in6; } version(Posix) { import core.sys.posix.sys.un : sockaddr_un; } @safe: private union { sockaddr addr; version (Posix) sockaddr_un addr_unix; sockaddr_in addr_ip4; sockaddr_in6 addr_ip6; } version(VibeLibasyncDriver) { static import libasync.events; this(libasync.events.NetworkAddress addr) @trusted { this.family = addr.family; switch (addr.family) { default: assert(false, "Got unsupported address family from libasync."); case AddressFamily.INET: this.addr_ip4 = *addr.sockAddrInet4; break; case AddressFamily.INET6: this.addr_ip6 = *addr.sockAddrInet6; break; } } T opCast(T)() @trusted if (is(T == libasync.events.NetworkAddress)) { T ret; ret.family = this.family; (cast(ubyte*)ret.sockAddr)[0 .. this.sockAddrLen] = (cast(ubyte*)this.sockAddr)[0 .. this.sockAddrLen]; return ret; } } /** Family of the socket address. */ @property ushort family() const pure nothrow { return addr.sa_family; } /// ditto @property void family(AddressFamily val) pure nothrow { addr.sa_family = cast(ubyte)val; } /// ditto @property void family(ushort val) pure nothrow { addr.sa_family = cast(ubyte)val; } /** The port in host byte order. */ @property ushort port() const pure nothrow { ushort nport; switch (this.family) { default: assert(false, "port() called for invalid address family."); case AddressFamily.INET: nport = addr_ip4.sin_port; break; case AddressFamily.INET6: nport = addr_ip6.sin6_port; break; } return () @trusted { return ntoh(nport); } (); } /// ditto @property void port(ushort val) pure nothrow { auto nport = () @trusted { return hton(val); } (); switch (this.family) { default: assert(false, "port() called for invalid address family."); case AddressFamily.INET: addr_ip4.sin_port = nport; break; case AddressFamily.INET6: addr_ip6.sin6_port = nport; break; } } /** A pointer to a sockaddr struct suitable for passing to socket functions. */ @property inout(sockaddr)* sockAddr() inout pure nothrow { return &addr; } /** Size of the sockaddr struct that is returned by sockAddr(). */ @property int sockAddrLen() const pure nothrow { switch (this.family) { default: assert(false, "sockAddrLen() called for invalid address family."); version (Posix) { case AddressFamily.UNIX: return addr_unix.sizeof; } case AddressFamily.INET: return addr_ip4.sizeof; case AddressFamily.INET6: return addr_ip6.sizeof; } } @property inout(sockaddr_in)* sockAddrInet4() inout pure nothrow in { assert (family == AddressFamily.INET); } body { return &addr_ip4; } @property inout(sockaddr_in6)* sockAddrInet6() inout pure nothrow in { assert (family == AddressFamily.INET6); } body { return &addr_ip6; } version (Posix) { @property inout(sockaddr_un)* sockAddrUnix() inout pure nothrow in { assert (family == AddressFamily.UNIX); } body { return &addr_unix; } } /** Returns a string representation of the IP address */ string toAddressString() const { import std.array : appender; auto ret = appender!string(); ret.reserve(40); toAddressString(str => ret.put(str)); return ret.data; } /// ditto void toAddressString(scope void delegate(const(char)[]) @safe sink) const { import std.array : appender; import std.format : formattedWrite; ubyte[2] _dummy = void; // Workaround for DMD regression in master switch (this.family) { default: assert(false, "toAddressString() called for invalid address family."); case AddressFamily.INET: { ubyte[4] ip = () @trusted { return (cast(ubyte*)&addr_ip4.sin_addr.s_addr)[0 .. 4]; } (); sink.formattedWrite("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); } break; case AddressFamily.INET6: { ubyte[16] ip = addr_ip6.sin6_addr.s6_addr; foreach (i; 0 .. 8) { if (i > 0) sink(":"); _dummy[] = ip[i*2 .. i*2+2]; sink.formattedWrite("%x", bigEndianToNative!ushort(_dummy)); } } break; version (Posix) { case AddressFamily.UNIX: import std.traits : hasMember; static if (hasMember!(sockaddr_un, "sun_len")) sink.formattedWrite("%s",() @trusted { return cast(char[])addr_unix.sun_path[0..addr_unix.sun_len]; } ()); else sink.formattedWrite("%s",() @trusted { return (cast(char*)addr_unix.sun_path.ptr).fromStringz; } ()); break; } } } /** Returns a full string representation of the address, including the port number. */ string toString() const { import std.array : appender; auto ret = appender!string(); toString(str => ret.put(str)); return ret.data; } /// ditto void toString(scope void delegate(const(char)[]) @safe sink) const { import std.format : formattedWrite; switch (this.family) { default: assert(false, "toString() called for invalid address family."); case AddressFamily.INET: toAddressString(sink); sink.formattedWrite(":%s", port); break; case AddressFamily.INET6: sink("["); toAddressString(sink); sink.formattedWrite("]:%s", port); break; case AddressFamily.UNIX: toAddressString(sink); break; } } unittest { void test(string ip) { auto res = () @trusted { return resolveHost(ip, AddressFamily.UNSPEC, false); } ().toAddressString(); assert(res == ip, "IP "~ip~" yielded wrong string representation: "~res); } test("1.2.3.4"); test("102:304:506:708:90a:b0c:d0e:f10"); } } /** Represents a single TCP connection. */ interface TCPConnection : ConnectionStream { /// Used to disable Nagle's algorithm. @property void tcpNoDelay(bool enabled); /// ditto @property bool tcpNoDelay() const; /// Enables TCP keep-alive packets. @property void keepAlive(bool enable); /// ditto @property bool keepAlive() const; /// Controls the read time out after which the connection is closed automatically. @property void readTimeout(Duration duration); /// ditto @property Duration readTimeout() const; /// Returns the IP address of the connected peer. @property string peerAddress() const; /// The local/bind address of the underlying socket. @property NetworkAddress localAddress() const; /// The address of the connected peer. @property NetworkAddress remoteAddress() const; } /** Represents a listening TCP socket. */ interface TCPListener { /// The local address at which TCP connections are accepted. @property NetworkAddress bindAddress(); /// Stops listening and closes the socket. void stopListening(); } /** Represents a bound and possibly 'connected' UDP socket. */ interface UDPConnection { /** Returns the address to which the UDP socket is bound. */ @property string bindAddress() const; /** Determines if the socket is allowed to send to broadcast addresses. */ @property bool canBroadcast() const; /// ditto @property void canBroadcast(bool val); /// The local/bind address of the underlying socket. @property NetworkAddress localAddress() const; /** Stops listening for datagrams and frees all resources. */ void close(); /** Locks the UDP connection to a certain peer. Once connected, the UDPConnection can only communicate with the specified peer. Otherwise communication with any reachable peer is possible. */ void connect(string host, ushort port); /// ditto void connect(NetworkAddress address); /** Sends a single packet. If peer_address is given, the packet is send to that address. Otherwise the packet will be sent to the address specified by a call to connect(). */ void send(in ubyte[] data, in NetworkAddress* peer_address = null); /** Receives a single packet. If a buffer is given, it must be large enough to hold the full packet. The timeout overload will throw an Exception if no data arrives before the specified duration has elapsed. */ ubyte[] recv(ubyte[] buf = null, NetworkAddress* peer_address = null); /// ditto ubyte[] recv(Duration timeout, ubyte[] buf = null, NetworkAddress* peer_address = null); /** Become member of IP multicast group The multiaddr parameter should be in the range 239.0.0.0-239.255.255.255. See https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xml#multicast-addresses-12 and https://www.iana.org/assignments/ipv6-multicast-addresses/ipv6-multicast-addresses.xhtml */ void addMembership(ref NetworkAddress multiaddr); /** Set IP multicast loopback This is on by default. All packets send will also loopback if enabled. Useful if more than one application is running on same host and both need each other's packets. */ @property void multicastLoopback(bool loop); } /** Flags to control the behavior of listenTCP. */ enum TCPListenOptions { /// Don't enable any particular option defaults = 0, /// Causes incoming connections to be distributed across the thread pool distribute = 1<<0, /// Disables automatic closing of the connection when the connection callback exits disableAutoClose = 1<<1, /** Enable port reuse on linux kernel version >=3.9, do nothing on other OS Does not affect libasync driver because it is always enabled by libasync. */ reusePort = 1<<2, } private pure nothrow { import std.bitmanip; ushort ntoh(ushort val) { version (LittleEndian) return swapEndian(val); else version (BigEndian) return val; else static assert(false, "Unknown endianness."); } ushort hton(ushort val) { version (LittleEndian) return swapEndian(val); else version (BigEndian) return val; else static assert(false, "Unknown endianness."); } }