2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2016 Attila Molnar <attilamolnar@hush.com>
6 * This file is part of InspIRCd. InspIRCd is free software: you can
7 * redistribute it and/or modify it under the terms of the GNU General Public
8 * License as published by the Free Software Foundation, version 2.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 /// $CompilerFlags: -Ivendor_directory("utfcpp")
24 #include "modules/hash.h"
28 typedef std::vector<std::string> OriginList;
30 static const char MagicGUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
31 static const char whitespace[] = " \t\r\n";
32 static dynamic_reference_nocheck<HashProvider>* sha1;
34 struct WebSocketConfig
36 typedef std::vector<std::string> ProxyRanges;
38 // The HTTP origins that can connect to the server.
39 OriginList allowedorigins;
41 // The IP ranges which send trustworthy X-Real-IP or X-Forwarded-For headers.
42 ProxyRanges proxyranges;
44 // Whether to send as UTF-8 text instead of binary data.
48 class WebSocketHookProvider : public IOHookProvider
51 WebSocketConfig config;
52 WebSocketHookProvider(Module* mod)
53 : IOHookProvider(mod, "websocket", IOHookProvider::IOH_UNKNOWN, true)
57 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE;
59 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
64 class WebSocketHook : public IOHookMiddle
66 class HTTPHeaderFinder
68 std::string::size_type bpos;
69 std::string::size_type len;
72 bool Find(const std::string& req, const char* header, std::string::size_type headerlen, std::string::size_type maxpos)
74 std::string::size_type keybegin = req.find(header);
75 if ((keybegin == std::string::npos) || (keybegin > maxpos) || (keybegin == 0) || (req[keybegin-1] != '\n'))
78 keybegin += headerlen;
80 bpos = req.find_first_not_of(whitespace, keybegin, sizeof(whitespace)-1);
81 if ((bpos == std::string::npos) || (bpos > maxpos))
84 const std::string::size_type epos = req.find_first_of(whitespace, bpos, sizeof(whitespace)-1);
90 std::string ExtractValue(const std::string& req) const
92 return std::string(req, bpos, len);
98 OP_CONTINUATION = 0x00,
112 static const unsigned char WS_MASKBIT = (1 << 7);
113 static const unsigned char WS_FINBIT = (1 << 7);
114 static const unsigned char WS_PAYLOAD_LENGTH_MAGIC_LARGE = 126;
115 static const unsigned char WS_PAYLOAD_LENGTH_MAGIC_HUGE = 127;
116 static const size_t WS_MAX_PAYLOAD_LENGTH_SMALL = 125;
117 static const size_t WS_MAX_PAYLOAD_LENGTH_LARGE = 65535;
118 static const size_t MAXHEADERSIZE = sizeof(uint64_t) + 2;
120 // Clients sending ping or pong frames faster than this are killed
121 static const time_t MINPINGPONGDELAY = 10;
125 WebSocketConfig& config;
127 static size_t FillHeader(unsigned char* outbuf, size_t sendlength, OpCode opcode)
130 outbuf[pos++] = WS_FINBIT | opcode;
132 if (sendlength <= WS_MAX_PAYLOAD_LENGTH_SMALL)
134 outbuf[pos++] = sendlength;
136 else if (sendlength <= WS_MAX_PAYLOAD_LENGTH_LARGE)
138 outbuf[pos++] = WS_PAYLOAD_LENGTH_MAGIC_LARGE;
139 outbuf[pos++] = (sendlength >> 8) & 0xff;
140 outbuf[pos++] = sendlength & 0xff;
144 outbuf[pos++] = WS_PAYLOAD_LENGTH_MAGIC_HUGE;
145 const uint64_t len = sendlength;
146 for (int i = sizeof(uint64_t)-1; i >= 0; i--)
147 outbuf[pos++] = ((len >> i*8) & 0xff);
153 static StreamSocket::SendQueue::Element PrepareSendQElem(size_t size, OpCode opcode)
155 unsigned char header[MAXHEADERSIZE];
156 const size_t n = FillHeader(header, size, opcode);
158 return StreamSocket::SendQueue::Element(reinterpret_cast<const char*>(header), n);
161 int HandleAppData(StreamSocket* sock, std::string& appdataout, bool allowlarge)
163 std::string& myrecvq = GetRecvQ();
164 // Need 1 byte opcode, minimum 1 byte len, 4 bytes masking key
165 if (myrecvq.length() < 6)
168 const std::string& cmyrecvq = myrecvq;
169 unsigned char len1 = (unsigned char)cmyrecvq[1];
170 if (!(len1 & WS_MASKBIT))
172 sock->SetError("WebSocket protocol violation: unmasked client frame");
178 // Assume the length is a single byte, if not, update values later
179 unsigned int len = len1;
180 unsigned int payloadstartoffset = 6;
181 const unsigned char* maskkey = reinterpret_cast<const unsigned char*>(&cmyrecvq[2]);
183 if (len1 == WS_PAYLOAD_LENGTH_MAGIC_LARGE)
185 // allowlarge is false for control frames according to the RFC meaning large pings, etc. are not allowed
188 sock->SetError("WebSocket protocol violation: large control frame");
192 // Large frame, has 2 bytes len after the magic byte indicating the length
193 // Need 1 byte opcode, 3 bytes len, 4 bytes masking key
194 if (myrecvq.length() < 8)
197 unsigned char len2 = (unsigned char)cmyrecvq[2];
198 unsigned char len3 = (unsigned char)cmyrecvq[3];
199 len = (len2 << 8) | len3;
201 if (len <= WS_MAX_PAYLOAD_LENGTH_SMALL)
203 sock->SetError("WebSocket protocol violation: non-minimal length encoding used");
208 payloadstartoffset += 2;
210 else if (len1 == WS_PAYLOAD_LENGTH_MAGIC_HUGE)
212 sock->SetError("WebSocket: Huge frames are not supported");
216 if (myrecvq.length() < payloadstartoffset + len)
219 unsigned int maskkeypos = 0;
220 const std::string::iterator endit = myrecvq.begin() + payloadstartoffset + len;
221 for (std::string::const_iterator i = myrecvq.begin() + payloadstartoffset; i != endit; ++i)
223 const unsigned char c = (unsigned char)*i;
224 appdataout.push_back(c ^ maskkey[maskkeypos++]);
228 myrecvq.erase(myrecvq.begin(), endit);
232 int HandlePingPongFrame(StreamSocket* sock, bool isping)
234 if (lastpingpong + MINPINGPONGDELAY >= ServerInstance->Time())
236 sock->SetError("WebSocket: Ping/pong flood");
240 lastpingpong = ServerInstance->Time();
243 const int result = HandleAppData(sock, appdata, false);
244 // If it's a pong stop here regardless of the result so we won't generate a reply
245 if ((result <= 0) || (!isping))
248 StreamSocket::SendQueue::Element elem = PrepareSendQElem(appdata.length(), OP_PONG);
249 elem.append(appdata);
250 GetSendQ().push_back(elem);
252 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_WRITE);
256 int HandleWS(StreamSocket* sock, std::string& destrecvq)
258 if (GetRecvQ().empty())
261 unsigned char opcode = (unsigned char)GetRecvQ().c_str()[0];
262 switch (opcode & ~WS_FINBIT)
264 case OP_CONTINUATION:
269 const int result = HandleAppData(sock, appdata, true);
273 // Strip out any CR+LF which may have been erroneously sent.
274 for (std::string::const_iterator iter = appdata.begin(); iter != appdata.end(); ++iter)
276 if (*iter != '\r' && *iter != '\n')
277 destrecvq.push_back(*iter);
280 // If we are on the final message of this block append a line terminator.
281 if (opcode & WS_FINBIT)
282 destrecvq.append("\r\n");
289 return HandlePingPongFrame(sock, true);
294 // A pong frame may be sent unsolicited, so we have to handle it.
295 // It may carry application data which we need to remove from the recvq as well.
296 return HandlePingPongFrame(sock, false);
301 sock->SetError("Connection closed");
307 sock->SetError("WebSocket: Invalid opcode");
313 void FailHandshake(StreamSocket* sock, const char* httpreply, const char* sockerror)
315 GetSendQ().push_back(StreamSocket::SendQueue::Element(httpreply));
317 sock->SetError(sockerror);
320 int HandleHTTPReq(StreamSocket* sock)
322 std::string& recvq = GetRecvQ();
323 const std::string::size_type reqend = recvq.find("\r\n\r\n");
324 if (reqend == std::string::npos)
327 bool allowedorigin = false;
328 HTTPHeaderFinder originheader;
329 if (originheader.Find(recvq, "Origin:", 7, reqend))
331 const std::string origin = originheader.ExtractValue(recvq);
332 for (OriginList::const_iterator iter = config.allowedorigins.begin(); iter != config.allowedorigins.end(); ++iter)
334 if (InspIRCd::Match(origin, *iter, ascii_case_insensitive_map))
336 allowedorigin = true;
344 FailHandshake(sock, "HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n", "WebSocket: Received HTTP request from a non-whitelisted origin");
348 if (!config.proxyranges.empty() && sock->type == StreamSocket::SS_USER)
350 LocalUser* luser = static_cast<UserIOHandler*>(sock)->user;
351 irc::sockets::sockaddrs realsa(luser->client_sa);
353 HTTPHeaderFinder proxyheader;
354 if (proxyheader.Find(recvq, "X-Real-IP:", 10, reqend)
355 && irc::sockets::aptosa(proxyheader.ExtractValue(recvq), realsa.port(), realsa))
357 // Nothing to do here.
359 else if (proxyheader.Find(recvq, "X-Forwarded-For:", 16, reqend)
360 && irc::sockets::aptosa(proxyheader.ExtractValue(recvq), realsa.port(), realsa))
362 // Nothing to do here.
365 for (WebSocketConfig::ProxyRanges::const_iterator iter = config.proxyranges.begin(); iter != config.proxyranges.end(); ++iter)
367 if (InspIRCd::MatchCIDR(*iter, luser->GetIPString(), ascii_case_insensitive_map))
369 // Give the user their real IP address.
370 if (realsa == luser->client_sa)
371 luser->SetClientIP(realsa);
378 HTTPHeaderFinder keyheader;
379 if (!keyheader.Find(recvq, "Sec-WebSocket-Key:", 18, reqend))
381 FailHandshake(sock, "HTTP/1.1 501 Not Implemented\r\nConnection: close\r\n\r\n", "WebSocket: Received HTTP request which is not a websocket upgrade");
387 FailHandshake(sock, "HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n", "WebSocket: SHA-1 provider missing");
391 state = STATE_ESTABLISHED;
393 std::string key = keyheader.ExtractValue(recvq);
394 key.append(MagicGUID);
396 std::string reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ";
397 reply.append(BinToBase64((*sha1)->GenerateRaw(key), NULL, '=')).append("\r\n\r\n");
398 GetSendQ().push_back(StreamSocket::SendQueue::Element(reply));
400 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_WRITE);
402 recvq.erase(0, reqend + 4);
408 WebSocketHook(IOHookProvider* Prov, StreamSocket* sock, WebSocketConfig& cfg)
410 , state(STATE_HTTPREQ)
414 sock->AddIOHook(this);
417 int OnStreamSocketWrite(StreamSocket* sock, StreamSocket::SendQueue& uppersendq) CXX11_OVERRIDE
419 StreamSocket::SendQueue& mysendq = GetSendQ();
421 // Return 1 to allow sending back an error HTTP response
422 if (state != STATE_ESTABLISHED)
423 return (mysendq.empty() ? 0 : 1);
426 for (StreamSocket::SendQueue::const_iterator elem = uppersendq.begin(); elem != uppersendq.end(); ++elem)
428 for (StreamSocket::SendQueue::Element::const_iterator chr = elem->begin(); chr != elem->end(); ++chr)
432 // We have found an entire message. Send it in its own frame.
433 if (config.sendastext)
435 // If we send messages as text then we need to ensure they are valid UTF-8.
437 utf8::replace_invalid(message.begin(), message.end(), std::back_inserter(encoded));
439 mysendq.push_back(PrepareSendQElem(encoded.length(), OP_TEXT));
440 mysendq.push_back(encoded);
444 // Otherwise, send the raw message as a binary frame.
445 mysendq.push_back(PrepareSendQElem(message.length(), OP_BINARY));
446 mysendq.push_back(message);
450 else if (*chr != '\r')
452 message.push_back(*chr);
457 // Empty the upper send queue and push whatever is left back onto it.
459 if (!message.empty())
461 uppersendq.push_back(message);
468 int OnStreamSocketRead(StreamSocket* sock, std::string& destrecvq) CXX11_OVERRIDE
470 if (state == STATE_HTTPREQ)
472 int httpret = HandleHTTPReq(sock);
480 wsret = HandleWS(sock, destrecvq);
482 while ((!GetRecvQ().empty()) && (wsret > 0));
487 void OnStreamSocketClose(StreamSocket* sock) CXX11_OVERRIDE
492 void WebSocketHookProvider::OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
494 new WebSocketHook(this, sock, config);
497 class ModuleWebSocket : public Module
499 dynamic_reference_nocheck<HashProvider> hash;
500 reference<WebSocketHookProvider> hookprov;
504 : hash(this, "hash/sha1")
505 , hookprov(new WebSocketHookProvider(this))
510 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
512 ConfigTagList tags = ServerInstance->Config->ConfTags("wsorigin");
513 if (tags.first == tags.second)
514 throw ModuleException("You have loaded the websocket module but not configured any allowed origins!");
516 WebSocketConfig config;
517 for (ConfigIter i = tags.first; i != tags.second; ++i)
519 ConfigTag* tag = i->second;
521 // Ensure that we have the <wsorigin:allow> parameter.
522 const std::string allow = tag->getString("allow");
524 throw ModuleException("<wsorigin:allow> is a mandatory field, at " + tag->getTagLocation());
526 config.allowedorigins.push_back(allow);
529 ConfigTag* tag = ServerInstance->Config->ConfValue("websocket");
530 config.sendastext = tag->getBool("sendastext", true);
532 irc::spacesepstream proxyranges(tag->getString("proxyranges"));
533 for (std::string proxyrange; proxyranges.GetToken(proxyrange); )
534 config.proxyranges.push_back(proxyrange);
536 // Everything is okay; apply the new config.
537 hookprov->config = config;
540 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
542 if (type != ExtensionItem::EXT_USER)
545 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
546 if ((user) && (user->eh.GetModHook(this)))
547 ServerInstance->Users.QuitUser(user, "WebSocket module unloading");
550 Version GetVersion() CXX11_OVERRIDE
552 return Version("Provides RFC 6455 WebSocket support", VF_VENDOR);
556 MODULE_INIT(ModuleWebSocket)