vibe.http.websockets 0/435(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
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
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12210
12220
12230
12240
12250
12260
12270
12280
12290
12300
12310
12320
12330
12340
12350
12360
12370
12380
/** Implements WebSocket support and fallbacks for older browsers. Standards: $(LINK2 https://tools.ietf.org/html/rfc6455, RFC6455) Copyright: © 2012-2014 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Jan Krüger */ module vibe.http.websockets; /// @safe unittest { void handleConn(scope WebSocket sock) { // simple echo server while (sock.connected) { auto msg = sock.receiveText(); sock.send(msg); } } void startServer() { import vibe.http.router; auto router = new URLRouter; router.get("/ws", handleWebSockets(&handleConn)); // Start HTTP server using listenHTTP()... } } import vibe.core.core; import vibe.core.log; import vibe.core.net; import vibe.core.sync; import vibe.stream.operations; import vibe.http.server; import vibe.http.client; import vibe.core.connectionpool; import vibe.utils.array; import core.time; import std.array; import std.base64; import std.conv; import std.exception; import std.bitmanip; import std.digest.sha; import std.string; import std.functional; import std.uuid; import std.base64; import std.digest.sha; import vibe.crypto.cryptorand; @safe: alias WebSocketHandshakeDelegate = void delegate(scope WebSocket) nothrow; /// Exception thrown by $(D vibe.http.websockets). class WebSocketException: Exception { @safe pure nothrow: /// this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) { super(msg, file, line, next); } /// this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__) { super(msg, next, file, line); } } /** Returns a WebSocket client object that is connected to the specified host. */ WebSocket connectWebSocket(URL url, const(HTTPClientSettings) settings = defaultSettings) @safe { import std.typecons : Tuple, tuple; auto host = url.host; auto port = url.port; bool use_tls = (url.schema == "wss") ? true : false; if (port == 0) port = (use_tls) ? 443 : 80; static struct ConnInfo { string host; ushort port; bool useTLS; string proxyIP; ushort proxyPort; } static vibe.utils.array.FixedRingBuffer!(Tuple!(ConnInfo, ConnectionPool!HTTPClient), 16) s_connections; auto ckey = ConnInfo(host, port, use_tls, settings ? settings.proxyURL.host : null, settings ? settings.proxyURL.port : 0); ConnectionPool!HTTPClient pool; foreach (c; s_connections) if (c[0].host == host && c[0].port == port && c[0].useTLS == use_tls && (settings is null || (c[0].proxyIP == settings.proxyURL.host && c[0].proxyPort == settings.proxyURL.port))) pool = c[1]; if (!pool) { logDebug("Create HTTP client pool %s:%s %s proxy %s:%d", host, port, use_tls, (settings) ? settings.proxyURL.host : string.init, (settings) ? settings.proxyURL.port : 0); pool = new ConnectionPool!HTTPClient({ auto ret = new HTTPClient; ret.connect(host, port, use_tls, settings); return ret; }); if (s_connections.full) s_connections.popFront(); s_connections.put(tuple(ckey, pool)); } auto rng = secureRNG(); auto challengeKey = generateChallengeKey(rng); auto answerKey = computeAcceptKey(challengeKey); auto cl = pool.lockConnection(); auto res = cl.request((scope req){ req.requestURL = (url.localURI == "") ? "/" : url.localURI; req.method = HTTPMethod.GET; req.headers["Upgrade"] = "websocket"; req.headers["Connection"] = "Upgrade"; req.headers["Sec-WebSocket-Version"] = "13"; req.headers["Sec-WebSocket-Key"] = challengeKey; }); enforce(res.statusCode == HTTPStatus.switchingProtocols, "Server didn't accept the protocol upgrade request."); auto key = "sec-websocket-accept" in res.headers; enforce(key !is null, "Response is missing the Sec-WebSocket-Accept header."); enforce(*key == answerKey, "Response has wrong accept key"); auto conn = res.switchProtocol("websocket"); auto ws = new WebSocket(conn, null, rng); return ws; } /// ditto void connectWebSocket(URL url, scope WebSocketHandshakeDelegate del, const(HTTPClientSettings) settings = defaultSettings) @safe { bool use_tls = (url.schema == "wss") ? true : false; url.schema = use_tls ? "https" : "http"; /*scope*/auto rng = secureRNG(); auto challengeKey = generateChallengeKey(rng); auto answerKey = computeAcceptKey(challengeKey); requestHTTP(url, (scope req) { req.method = HTTPMethod.GET; req.headers["Upgrade"] = "websocket"; req.headers["Connection"] = "Upgrade"; req.headers["Sec-WebSocket-Version"] = "13"; req.headers["Sec-WebSocket-Key"] = challengeKey; }, (scope res) { enforce(res.statusCode == HTTPStatus.switchingProtocols, "Server didn't accept the protocol upgrade request."); auto key = "sec-websocket-accept" in res.headers; enforce(key !is null, "Response is missing the Sec-WebSocket-Accept header."); enforce(*key == answerKey, "Response has wrong accept key"); res.switchProtocol("websocket", (scope conn) @trusted { scope ws = new WebSocket(conn, null, rng); del(ws); }); } ); } /// Scheduled for deprecation - use a `@safe` callback instead. void connectWebSocket(URL url, scope void delegate(scope WebSocket) @system nothrow del, const(HTTPClientSettings) settings = defaultSettings) @system { connectWebSocket(url, (scope ws) @trusted => del(ws), settings); } /// Scheduled for deprecation - use a `nothrow` callback instead. void connectWebSocket(URL url, scope void delegate(scope WebSocket) @safe del, const(HTTPClientSettings) settings = defaultSettings) @safe { connectWebSocket(url, (scope ws) nothrow { try del(ws); catch (Exception e) logWarn("WebSocket handler failed: %s", e.msg); }, settings); } /// ditto void connectWebSocket(URL url, scope void delegate(scope WebSocket) @system del, const(HTTPClientSettings) settings = defaultSettings) @system { connectWebSocket(url, (scope ws) nothrow { try del(ws); catch (Exception e) logWarn("WebSocket handler failed: %s", e.msg); }, settings); } /** Establishes a web socket conection and passes it to the $(D on_handshake) delegate. */ void handleWebSocket(scope WebSocketHandshakeDelegate on_handshake, scope HTTPServerRequest req, scope HTTPServerResponse res) @safe { auto pUpgrade = "Upgrade" in req.headers; auto pConnection = "Connection" in req.headers; auto pKey = "Sec-WebSocket-Key" in req.headers; //auto pProtocol = "Sec-WebSocket-Protocol" in req.headers; auto pVersion = "Sec-WebSocket-Version" in req.headers; auto isUpgrade = false; if( pConnection ) { auto connectionTypes = split(*pConnection, ","); foreach( t ; connectionTypes ) { if( t.strip().toLower() == "upgrade" ) { isUpgrade = true; break; } } } string req_error; if (!isUpgrade) req_error = "WebSocket endpoint only accepts \"Connection: upgrade\" requests."; else if (!pUpgrade || icmp(*pUpgrade, "websocket") != 0) req_error = "WebSocket endpoint requires \"Upgrade: websocket\" header."; else if (!pVersion || *pVersion != "13") req_error = "Only version 13 of the WebSocket protocol is supported."; else if (!pKey) req_error = "Missing \"Sec-WebSocket-Key\" header."; if (req_error.length) { logDebug("Browser sent invalid WebSocket request: %s", req_error); res.statusCode = HTTPStatus.badRequest; res.writeBody(req_error); return; } auto accept = () @trusted { return cast(string)Base64.encode(sha1Of(*pKey ~ s_webSocketGuid)); } (); res.headers["Sec-WebSocket-Accept"] = accept; res.headers["Connection"] = "Upgrade"; ConnectionStream conn = res.switchProtocol("websocket"); WebSocket socket = new WebSocket(conn, req, null); try { on_handshake(socket); } catch (Exception e) { logDiagnostic("WebSocket handler failed: %s", e.msg); } socket.close(); } /// Scheduled for deprecation - use a `@safe` callback instead. void handleWebSocket(scope void delegate(scope WebSocket) @system nothrow on_handshake, scope HTTPServerRequest req, scope HTTPServerResponse res) @system { handleWebSocket((scope ws) @trusted => on_handshake(ws), req, res); } /// Scheduled for deprecation - use a `nothrow` callback instead. void handleWebSocket(scope void delegate(scope WebSocket) @safe on_handshake, scope HTTPServerRequest req, scope HTTPServerResponse res) { handleWebSocket((scope ws) nothrow { try on_handshake(ws); catch (Exception e) logWarn("WebSocket handler failed: %s", e.msg); }, req, res); } /// ditto void handleWebSocket(scope void delegate(scope WebSocket) @system on_handshake, scope HTTPServerRequest req, scope HTTPServerResponse res) @system { handleWebSocket((scope ws) nothrow { try on_handshake(ws); catch (Exception e) logWarn("WebSocket handler failed: %s", e.msg); }, req, res); } /** Returns a HTTP request handler that establishes web socket conections. */ HTTPServerRequestDelegateS handleWebSockets(void function(scope WebSocket) @safe nothrow on_handshake) @safe { return handleWebSockets(() @trusted { return toDelegate(on_handshake); } ()); } /// ditto HTTPServerRequestDelegateS handleWebSockets(WebSocketHandshakeDelegate on_handshake) @safe { void callback(scope HTTPServerRequest req, scope HTTPServerResponse res) @safe { auto pUpgrade = "Upgrade" in req.headers; auto pConnection = "Connection" in req.headers; auto pKey = "Sec-WebSocket-Key" in req.headers; //auto pProtocol = "Sec-WebSocket-Protocol" in req.headers; auto pVersion = "Sec-WebSocket-Version" in req.headers; auto isUpgrade = false; if( pConnection ) { auto connectionTypes = split(*pConnection, ","); foreach( t ; connectionTypes ) { if( t.strip().toLower() == "upgrade" ) { isUpgrade = true; break; } } } if( !(isUpgrade && pUpgrade && icmp(*pUpgrade, "websocket") == 0 && pKey && pVersion && *pVersion == "13") ) { logDebug("Browser sent invalid WebSocket request."); res.statusCode = HTTPStatus.badRequest; res.writeVoidBody(); return; } auto accept = () @trusted { return cast(string)Base64.encode(sha1Of(*pKey ~ s_webSocketGuid)); } (); res.headers["Sec-WebSocket-Accept"] = accept; res.headers["Connection"] = "Upgrade"; res.switchProtocol("websocket", (scope conn) { // TODO: put back 'scope' once it is actually enforced by DMD /*scope*/ auto socket = new WebSocket(conn, req, null); try on_handshake(socket); catch (Exception e) { logDiagnostic("WebSocket handler failed: %s", e.msg); } socket.close(); }); } return &callback; } /// Scheduled for deprecation - use a `@safe` callback instead. HTTPServerRequestDelegateS handleWebSockets(void delegate(scope WebSocket) @system nothrow on_handshake) @system { return handleWebSockets(delegate (scope ws) @trusted => on_handshake(ws)); } /// Scheduled for deprecation - use a `@safe` callback instead. HTTPServerRequestDelegateS handleWebSockets(void function(scope WebSocket) @system nothrow on_handshake) @system { return handleWebSockets(delegate (scope ws) @trusted => on_handshake(ws)); } /// Scheduled for deprecation - use a `nothrow` callback instead. HTTPServerRequestDelegateS handleWebSockets(void delegate(scope WebSocket) @safe on_handshake) { return handleWebSockets(delegate (scope ws) nothrow { try on_handshake(ws); catch (Exception e) logWarn("WebSocket handler failed: %s", e.msg); }); } /// ditto HTTPServerRequestDelegateS handleWebSockets(void function(scope WebSocket) @safe on_handshake) { return handleWebSockets(delegate (scope ws) nothrow { try on_handshake(ws); catch (Exception e) logWarn("WebSocket handler failed: %s", e.msg); }); } /// ditto HTTPServerRequestDelegateS handleWebSockets(void delegate(scope WebSocket) @system on_handshake) @system { return handleWebSockets(delegate (scope ws) nothrow { try on_handshake(ws); catch (Exception e) logWarn("WebSocket handler failed: %s", e.msg); }); } /// ditto HTTPServerRequestDelegateS handleWebSockets(void function(scope WebSocket) @system on_handshake) @system { return handleWebSockets(delegate (scope ws) nothrow { try on_handshake(ws); catch (Exception e) logWarn("WebSocket handler failed: %s", e.msg); }); } /** * Provides the reason that a websocket connection has closed. * * Further documentation for the WebSocket and it's codes can be found from: * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent * * --- * * void echoSocket(scope WebSocket sock) * { * import std.datetime : seconds; * * while(sock.waitForData(3.seconds)) * { * string msg = sock.receiveText; * logInfo("Got a message: %s", msg); * sock.send(msg); * } * * if(sock.connected) * sock.close(WebSocketCloseReason.policyViolation, "timeout"); * } */ enum WebSocketCloseReason : short { none = 0, normalClosure = 1000, goingAway = 1001, protocolError = 1002, unsupportedData = 1003, noStatusReceived = 1005, abnormalClosure = 1006, invalidFramePayloadData = 1007, policyViolation = 1008, messageTooBig = 1009, internalError = 1011, serviceRestart = 1012, tryAgainLater = 1013, badGateway = 1014, tlsHandshake = 1015 } string closeReasonString(WebSocketCloseReason reason) @nogc @safe { import std.math : floor; //round down to the nearest thousand to get category switch(cast(short)(cast(float)reason / 1000f).floor) { case 0: return "Reserved and Unused"; case 1: switch(reason) { case 1000: return "Normal Closure"; case 1001: return "Going Away"; case 1002: return "Protocol Error"; case 1003: return "Unsupported Data"; case 1004: return "RESERVED"; case 1005: return "No Status Recvd"; case 1006: return "Abnormal Closure"; case 1007: return "Invalid Frame Payload Data"; case 1008: return "Policy Violation"; case 1009: return "Message Too Big"; case 1010: return "Missing Extension"; case 1011: return "Internal Error"; case 1012: return "Service Restart"; case 1013: return "Try Again Later"; case 1014: return "Bad Gateway"; case 1015: return "TLS Handshake"; default: return "RESERVED"; } case 2: return "Reserved for extensions"; case 3: return "Available for frameworks and libraries"; case 4: return "Available for applications"; default: return "UNDEFINED - Nasal Demons"; } } unittest { assert((cast(WebSocketCloseReason) 0).closeReasonString == "Reserved and Unused"); assert((cast(WebSocketCloseReason) 1).closeReasonString == "Reserved and Unused"); assert(WebSocketCloseReason.normalClosure.closeReasonString == "Normal Closure"); assert(WebSocketCloseReason.abnormalClosure.closeReasonString == "Abnormal Closure"); assert((cast(WebSocketCloseReason)1020).closeReasonString == "RESERVED"); assert((cast(WebSocketCloseReason)2000).closeReasonString == "Reserved for extensions"); assert((cast(WebSocketCloseReason)3000).closeReasonString == "Available for frameworks and libraries"); assert((cast(WebSocketCloseReason)4000).closeReasonString == "Available for applications"); assert((cast(WebSocketCloseReason)5000).closeReasonString == "UNDEFINED - Nasal Demons"); assert((cast(WebSocketCloseReason) -1).closeReasonString == "UNDEFINED - Nasal Demons"); //check the other spec cases for(short i = 1000; i < 1017; i++) { if(i == 1004 || i > 1015) { assert( (cast(WebSocketCloseReason)i).closeReasonString == "RESERVED", "(incorrect) code %d = %s".format(i, closeReasonString(cast(WebSocketCloseReason)i)) ); } else assert( (cast(WebSocketCloseReason)i).closeReasonString != "RESERVED", "(incorrect) code %d = %s".format(i, closeReasonString(cast(WebSocketCloseReason)i)) ); } } /** * Represents a single _WebSocket connection. * * --- * shared static this () * { * runTask(() => connectToWS()); * } * * void connectToWS () * { * auto ws_url = URL("wss://websockets.example.com/websocket/auth_token"); * auto ws = connectWebSocket(ws_url); * logInfo("WebSocket connected"); * * while (ws.waitForData()) * { * auto txt = ws.receiveText; * logInfo("Received: %s", txt); * } * logFatal("Connection lost!"); * } * --- */ final class WebSocket { @safe: private { ConnectionStream m_conn; bool m_sentCloseFrame = false; IncomingWebSocketMessage m_nextMessage = null; const HTTPServerRequest m_request; Task m_reader; InterruptibleTaskMutex m_readMutex, m_writeMutex; InterruptibleTaskCondition m_readCondition; Timer m_pingTimer; uint m_lastPingIndex; bool m_pongReceived; short m_closeCode; const(char)[] m_closeReason; /// The entropy generator to use /// If not null, it means this is a server socket. RandomNumberStream m_rng; } /** * Private constructor, called from `connectWebSocket`. * * Params: * conn = Underlying connection string * request = HTTP request used to establish the connection * rng = Source of entropy to use. If null, assume we're a server socket */ private this(ConnectionStream conn, in HTTPServerRequest request, RandomNumberStream rng) { m_conn = conn; m_request = request; assert(m_conn); m_rng = rng; m_writeMutex = new InterruptibleTaskMutex; m_readMutex = new InterruptibleTaskMutex; m_readCondition = new InterruptibleTaskCondition(m_readMutex); m_readMutex.performLocked!({ m_reader = runTask(&startReader); if (request !is null && request.serverSettings.webSocketPingInterval != Duration.zero) { m_pongReceived = true; m_pingTimer = setTimer(request.serverSettings.webSocketPingInterval, &sendPing, true); } }); } /** Determines if the WebSocket connection is still alive and ready for sending. Note that for determining the ready state for $(EM reading), you need to use $(D waitForData) instead, because both methods can return different values while a disconnect is in proress. See_also: $(D waitForData) */ @property bool connected() { return m_conn.connected && !m_sentCloseFrame; } /** Returns the close code sent by the remote end. Note if the connection was never opened, is still alive, or was closed locally this value will be 0. If no close code was given by the remote end in the close frame, the value will be 1005. If the connection was not closed cleanly by the remote end, this value will be 1006. */ @property short closeCode() { return m_closeCode; } /** Returns the close reason sent by the remote end. Note if the connection was never opened, is still alive, or was closed locally this value will be an empty string. */ @property const(char)[] closeReason() { return m_closeReason; } /** The HTTP request that established the web socket connection. */ @property const(HTTPServerRequest) request() const { return m_request; } /** Checks if data is readily available for read. */ @property bool dataAvailableForRead() { return m_conn.dataAvailableForRead || m_nextMessage !is null; } /** Waits until either a message arrives or until the connection is closed. This function can be used in a read loop to cleanly determine when to stop reading. */ bool waitForData() { if (m_nextMessage) return true; m_readMutex.performLocked!({ while (connected && m_nextMessage is null) m_readCondition.wait(); }); return m_nextMessage !is null; } /// ditto bool waitForData(Duration timeout) { import std.datetime; if (m_nextMessage) return true; immutable limit_time = Clock.currTime(UTC()) + timeout; m_readMutex.performLocked!({ while (connected && m_nextMessage is null && timeout > 0.seconds) { m_readCondition.wait(timeout); timeout = limit_time - Clock.currTime(UTC()); } }); return m_nextMessage !is null; } /** Sends a text message. On the JavaScript side, the text will be available as message.data (type string). Throws: A `WebSocketException` is thrown if the connection gets closed before or during the transfer of the message. */ void send(scope const(char)[] data) { send( (scope message) { message.write(cast(const ubyte[])data); }, FrameOpcode.text); } /** Sends a binary message. On the JavaScript side, the text will be available as message.data (type Blob). Throws: A `WebSocketException` is thrown if the connection gets closed before or during the transfer of the message. */ void send(in ubyte[] data) { send((scope message){ message.write(data); }, FrameOpcode.binary); } /** Sends a message using an output stream. Throws: A `WebSocketException` is thrown if the connection gets closed before or during the transfer of the message. */ void send(scope void delegate(scope OutgoingWebSocketMessage) @safe sender, FrameOpcode frameOpcode) { m_writeMutex.performLocked!({ enforceEx!WebSocketException(!m_sentCloseFrame, "WebSocket connection already actively closed."); /*scope*/auto message = new OutgoingWebSocketMessage(m_conn, frameOpcode, m_rng); scope(exit) message.finalize(); sender(message); }); } /// Compatibility overload - will be removed soon. deprecated("Call the overload which requires an explicit FrameOpcode.") void send(scope void delegate(scope OutgoingWebSocketMessage) @safe sender) { send(sender, FrameOpcode.text); } /** Actively closes the connection. Params: code = Numeric code indicating a termination reason. reason = Message describing why the connection was terminated. */ void close(short code = WebSocketCloseReason.normalClosure, scope const(char)[] reason = "") { import std.algorithm.comparison : min; if(reason !is null && reason.length == 0) reason = (cast(WebSocketCloseReason)code).closeReasonString; //control frame payloads are limited to 125 bytes version(assert) assert(reason.length <= 123); else reason = reason[0 .. min($, 123)]; if (connected) { send((scope msg) { m_sentCloseFrame = true; if (code != 0) msg.write(std.bitmanip.nativeToBigEndian(code)); msg.write(cast(const ubyte[])reason); }, FrameOpcode.close); } if (m_pingTimer) m_pingTimer.stop(); if (Task.getThis() != m_reader) m_reader.join(); } /** Receives a new message and returns its contents as a newly allocated data array. Params: strict = If set, ensures the exact frame type (text/binary) is received and throws an execption otherwise. Throws: WebSocketException if the connection is closed or if $(D strict == true) and the frame received is not the right type */ ubyte[] receiveBinary(bool strict = true) { ubyte[] ret; receive((scope message){ enforceEx!WebSocketException(!strict || message.frameOpcode == FrameOpcode.binary, "Expected a binary message, got "~message.frameOpcode.to!string()); ret = message.readAll(); }); return ret; } /// ditto string receiveText(bool strict = true) { string ret; receive((scope message){ enforceEx!WebSocketException(!strict || message.frameOpcode == FrameOpcode.text, "Expected a text message, got "~message.frameOpcode.to!string()); ret = message.readAllUTF8(); }); return ret; } /** Receives a new message using an InputStream. Throws: WebSocketException if the connection is closed. */ void receive(scope void delegate(scope IncomingWebSocketMessage) @safe receiver) { m_readMutex.performLocked!({ while (!m_nextMessage) { enforceEx!WebSocketException(connected, "Connection closed while reading message."); m_readCondition.wait(); } receiver(m_nextMessage); m_nextMessage = null; m_readCondition.notifyAll(); }); } private void startReader() { m_readMutex.performLocked!({}); //Wait until initialization scope (exit) m_readCondition.notifyAll(); try { while (!m_conn.empty) { assert(!m_nextMessage); /*scope*/auto msg = new IncomingWebSocketMessage(m_conn, m_rng); switch (msg.frameOpcode) { default: throw new WebSocketException("unknown frame opcode"); case FrameOpcode.ping: send((scope pong_msg) { pong_msg.write(msg.peek()); }, FrameOpcode.pong); break; case FrameOpcode.pong: // test if pong matches previous ping if (msg.peek.length != uint.sizeof || m_lastPingIndex != littleEndianToNative!uint(msg.peek()[0..uint.sizeof])) { logDebugV("Received PONG that doesn't match previous ping."); break; } logDebugV("Received matching PONG."); m_pongReceived = true; break; case FrameOpcode.close: logDebug("Got closing frame (%s)", m_sentCloseFrame); // If no close code was passed, we default to 1005 this.m_closeCode = WebSocketCloseReason.noStatusReceived; // If provided in the frame, attempt to parse the close code/reason if (msg.peek().length >= short.sizeof) { this.m_closeCode = bigEndianToNative!short(msg.peek()[0..short.sizeof]); if (msg.peek().length > short.sizeof) { this.m_closeReason = cast(const(char) [])msg.peek()[short.sizeof..$]; } } if(!m_sentCloseFrame) close(); logDebug("Terminating connection (%s)", m_sentCloseFrame); m_conn.close(); return; case FrameOpcode.text: case FrameOpcode.binary: case FrameOpcode.continuation: // FIXME: add proper support for continuation frames! m_readMutex.performLocked!({ m_nextMessage = msg; m_readCondition.notifyAll(); while (m_nextMessage) m_readCondition.wait(); }); break; } } } catch (Exception e) { logDiagnostic("Error while reading websocket message: %s", e.msg); logDiagnostic("Closing connection."); } // If no close code was passed, e.g. this was an unclean termination // of our websocket connection, set the close code to 1006. if (this.m_closeCode == 0) this.m_closeCode = WebSocketCloseReason.abnormalClosure; m_writeMutex.performLocked!({ m_conn.close(); }); } private void sendPing() nothrow { try { if (!m_pongReceived) { logDebug("Pong skipped. Closing connection."); m_writeMutex.performLocked!({ m_conn.close(); }); m_pingTimer.stop(); return; } m_pongReceived = false; send((scope msg) { msg.write(nativeToLittleEndian(++m_lastPingIndex)); }, FrameOpcode.ping); logDebugV("Ping sent"); } catch (Exception e) { logError("Failed to acquire write mutex for sending a WebSocket ping frame: %s", e.msg); } } } /** Represents a single outgoing _WebSocket message as an OutputStream. */ final class OutgoingWebSocketMessage : OutputStream { @safe: private { RandomNumberStream m_rng; Stream m_conn; FrameOpcode m_frameOpcode; Appender!(ubyte[]) m_buffer; bool m_finalized = false; } private this(Stream conn, FrameOpcode frameOpcode, RandomNumberStream rng) { assert(conn !is null); m_conn = conn; m_frameOpcode = frameOpcode; m_rng = rng; } size_t write(in ubyte[] bytes, IOMode mode) { assert(!m_finalized); if (!m_buffer.data.length) { ubyte[Frame.maxHeaderSize] header_padding; m_buffer.put(header_padding[]); } m_buffer.put(bytes); return bytes.length; } void flush() { assert(!m_finalized); if (m_buffer.data.length > 0) sendFrame(false); } void finalize() { if (m_finalized) return; m_finalized = true; sendFrame(true); } private void sendFrame(bool fin) { if (!m_buffer.data.length) write(null, IOMode.once); assert(m_buffer.data.length >= Frame.maxHeaderSize); Frame frame; frame.fin = fin; frame.opcode = m_frameOpcode; frame.payload = m_buffer.data[Frame.maxHeaderSize .. $]; auto hsize = frame.getHeaderSize(m_rng !is null); auto msg = m_buffer.data[Frame.maxHeaderSize-hsize .. $]; frame.writeHeader(msg[0 .. hsize], m_rng); m_conn.write(msg); m_conn.flush(); m_buffer.clear(); } alias write = OutputStream.write; } /** Represents a single incoming _WebSocket message as an InputStream. */ final class IncomingWebSocketMessage : InputStream { @safe: private { RandomNumberStream m_rng; Stream m_conn; Frame m_currentFrame; } private this(Stream conn, RandomNumberStream rng) { assert(conn !is null); m_conn = conn; m_rng = rng; skipFrame(); // reads the first frame } @property bool empty() const { return m_currentFrame.payload.length == 0; } @property ulong leastSize() const { return m_currentFrame.payload.length; } @property bool dataAvailableForRead() { return true; } /// The frame type for this nessage; @property FrameOpcode frameOpcode() const { return m_currentFrame.opcode; } const(ubyte)[] peek() { return m_currentFrame.payload; } /** * Retrieve the next websocket frame of the stream and discard the current * one * * This function is helpful if one wish to process frames by frames, * or minimize memory allocation, as `peek` will only return the current * frame data, and read requires a pre-allocated buffer. * * Returns: * `false` if the current frame is the final one, `true` if a new frame * was read. */ bool skipFrame() { if (m_currentFrame.fin) return false; m_currentFrame = Frame.readFrame(m_conn); return true; } size_t read(scope ubyte[] dst, IOMode mode) { size_t nread = 0; while (dst.length > 0) { enforceEx!WebSocketException(!empty , "cannot read from empty stream"); enforceEx!WebSocketException(leastSize > 0, "no data available" ); import std.algorithm : min; auto sz = cast(size_t)min(leastSize, dst.length); dst[0 .. sz] = m_currentFrame.payload[0 .. sz]; dst = dst[sz .. $]; m_currentFrame.payload = m_currentFrame.payload[sz .. $]; nread += sz; if (leastSize == 0) { if (mode == IOMode.immediate || mode == IOMode.once && nread > 0) break; this.skipFrame(); } } return nread; } alias read = InputStream.read; } /// Magic string defined by the RFC for challenging the server during upgrade private static immutable s_webSocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; /** * The Opcode is 4 bits, as defined in Section 5.2 * * Values are defined in section 11.8 * Currently only 6 values are defined, however the opcode is defined as * taking 4 bits. */ private enum FrameOpcode : ubyte { continuation = 0x0, text = 0x1, binary = 0x2, close = 0x8, ping = 0x9, pong = 0xA } static assert(FrameOpcode.max < 0b1111, "FrameOpcode is only 4 bits"); private struct Frame { @safe: enum maxHeaderSize = 14; bool fin; FrameOpcode opcode; ubyte[] payload; /** * Return the header length encoded with the expected amount of bits * * The WebSocket RFC define a variable-length payload length. * In short, it means that: * - If the length is <= 125, it is stored as the 7 least significant * bits of the second header byte. The first bit is reserved for MASK. * - If the length is <= 65_536 (so it fits in 2 bytes), a magic value of * 126 is stored in the aforementioned 7 bits, and the actual length * is stored in the next two bytes, resulting in a 4 bytes header * ( + masking key, if any). * - If the length is > 65_536, a magic value of 127 will be used for * the 7-bit field, and the next 8 bytes are expected to be the length, * resulting in a 10 bytes header ( + masking key, if any). * * Those functions encapsulate all this logic and allow to just get the * length with the desired size. * * Return: * - For `ubyte`, the value to store in the 7 bits field, either the * length or a magic value (126 or 127). * - For `ushort`, a value in the range [126; 65_536]. * If payload.length is not in this bound, an assertion will be triggered. * - For `ulong`, a value in the range [65_537; size_t.max]. * If payload.length is not in this bound, an assertion will be triggered. */ size_t getHeaderSize(bool mask) { size_t ret = 1; if (payload.length < 126) ret += 1; else if (payload.length < 65536) ret += 3; else ret += 9; if (mask) ret += 4; return ret; } void writeHeader(ubyte[] dst, RandomNumberStream sys_rng) { ubyte[4] buff; ubyte firstByte = cast(ubyte)opcode; if (fin) firstByte |= 0x80; dst[0] = firstByte; dst = dst[1 .. $]; auto b1 = sys_rng ? 0x80 : 0x00; if (payload.length < 126) { dst[0] = cast(ubyte)(b1 | payload.length); dst = dst[1 .. $]; } else if (payload.length < 65536) { dst[0] = cast(ubyte) (b1 | 126); dst[1 .. 3] = std.bitmanip.nativeToBigEndian(cast(ushort)payload.length); dst = dst[3 .. $]; } else { dst[0] = cast(ubyte) (b1 | 127); dst[1 .. 9] = std.bitmanip.nativeToBigEndian(cast(ulong)payload.length); dst = dst[9 .. $]; } if (sys_rng) { sys_rng.read(dst[0 .. 4]); for (size_t i = 0; i < payload.length; i++) payload[i] ^= dst[i % 4]; } } static Frame readFrame(InputStream stream) { Frame frame; ubyte[8] data; stream.read(data[0 .. 2]); frame.fin = (data[0] & 0x80) != 0; frame.opcode = cast(FrameOpcode)(data[0] & 0x0F); bool masked = !!(data[1] & 0b1000_0000); //parsing length ulong length = data[1] & 0b0111_1111; if (length == 126) { stream.read(data[0 .. 2]); length = bigEndianToNative!ushort(data[0 .. 2]); } else if (length == 127) { stream.read(data); length = bigEndianToNative!ulong(data); // RFC 6455, 5.2, 'Payload length': If 127, the following 8 bytes // interpreted as a 64-bit unsigned integer (the most significant // bit MUST be 0) enforceEx!WebSocketException(!(length >> 63), "Received length has a non-zero most significant bit"); } logDebug("Read frame: %s %s %s length=%d", frame.opcode, frame.fin ? "final frame" : "continuation", masked ? "masked" : "not masked", length); // Masking key is 32 bits / uint if (masked) stream.read(data[0 .. 4]); // Read payload // TODO: Provide a way to limit the size read, easy // DOS for server code here (rejectedsoftware/vibe.d#1496). enforceEx!WebSocketException(length <= size_t.max); frame.payload = new ubyte[](cast(size_t)length); stream.read(frame.payload); //de-masking if (masked) foreach (size_t i; 0 .. cast(size_t)length) frame.payload[i] = frame.payload[i] ^ data[i % 4]; return frame; } } unittest { import std.algorithm.searching : all; final class DummyRNG : RandomNumberStream { @safe: @property bool empty() { return false; } @property ulong leastSize() { return ulong.max; } @property bool dataAvailableForRead() { return true; } const(ubyte)[] peek() { return null; } size_t read(scope ubyte[] buffer, IOMode mode) @trusted { buffer[] = 13; return buffer.length; } alias read = RandomNumberStream.read; } ubyte[14] hdrbuf; auto rng = new DummyRNG; Frame f; f.payload = new ubyte[125]; assert(f.getHeaderSize(false) == 2); hdrbuf[] = 0; f.writeHeader(hdrbuf[0 .. 2], null); assert(hdrbuf[0 .. 2] == [0, 125]); assert(f.getHeaderSize(true) == 6); hdrbuf[] = 0; f.writeHeader(hdrbuf[0 .. 6], rng); assert(hdrbuf[0 .. 2] == [0, 128|125]); assert(hdrbuf[2 .. 6].all!(b => b == 13)); f.payload = new ubyte[126]; assert(f.getHeaderSize(false) == 4); hdrbuf[] = 0; f.writeHeader(hdrbuf[0 .. 4], null); assert(hdrbuf[0 .. 4] == [0, 126, 0, 126]); assert(f.getHeaderSize(true) == 8); hdrbuf[] = 0; f.writeHeader(hdrbuf[0 .. 8], rng); assert(hdrbuf[0 .. 4] == [0, 128|126, 0, 126]); assert(hdrbuf[4 .. 8].all!(b => b == 13)); f.payload = new ubyte[65535]; assert(f.getHeaderSize(false) == 4); hdrbuf[] = 0; f.writeHeader(hdrbuf[0 .. 4], null); assert(hdrbuf[0 .. 4] == [0, 126, 255, 255]); assert(f.getHeaderSize(true) == 8); hdrbuf[] = 0; f.writeHeader(hdrbuf[0 .. 8], rng); assert(hdrbuf[0 .. 4] == [0, 128|126, 255, 255]); assert(hdrbuf[4 .. 8].all!(b => b == 13)); f.payload = new ubyte[65536]; assert(f.getHeaderSize(false) == 10); hdrbuf[] = 0; f.writeHeader(hdrbuf[0 .. 10], null); assert(hdrbuf[0 .. 10] == [0, 127, 0, 0, 0, 0, 0, 1, 0, 0]); assert(f.getHeaderSize(true) == 14); hdrbuf[] = 0; f.writeHeader(hdrbuf[0 .. 14], rng); assert(hdrbuf[0 .. 10] == [0, 128|127, 0, 0, 0, 0, 0, 1, 0, 0]); assert(hdrbuf[10 .. 14].all!(b => b == 13)); } /** * Generate a challenge key for the protocol upgrade phase. */ private string generateChallengeKey(scope RandomNumberStream rng) { ubyte[16] buffer; rng.read(buffer); return Base64.encode(buffer); } private string computeAcceptKey(string challengekey) { immutable(ubyte)[] b = challengekey.representation; immutable(ubyte)[] a = s_webSocketGuid.representation; SHA1 hash; hash.start(); hash.put(b); hash.put(a); auto result = Base64.encode(hash.finish()); return to!(string)(result); }