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/>.
22 #include "modules/hash.h"
24 typedef std::vector<std::string> OriginList;
26 static const char MagicGUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
27 static const char whitespace[] = " \t\r\n";
28 static dynamic_reference_nocheck<HashProvider>* sha1;
30 class WebSocketHookProvider : public IOHookProvider
33 OriginList allowedorigins;
35 WebSocketHookProvider(Module* mod)
36 : IOHookProvider(mod, "websocket", IOHookProvider::IOH_UNKNOWN, true)
40 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE;
42 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
47 class WebSocketHook : public IOHookMiddle
49 class HTTPHeaderFinder
51 std::string::size_type bpos;
52 std::string::size_type len;
55 bool Find(const std::string& req, const char* header, std::string::size_type headerlen, std::string::size_type maxpos)
57 std::string::size_type keybegin = req.find(header);
58 if ((keybegin == std::string::npos) || (keybegin > maxpos) || (keybegin == 0) || (req[keybegin-1] != '\n'))
61 keybegin += headerlen;
63 bpos = req.find_first_not_of(whitespace, keybegin, sizeof(whitespace)-1);
64 if ((bpos == std::string::npos) || (bpos > maxpos))
67 const std::string::size_type epos = req.find_first_of(whitespace, bpos, sizeof(whitespace)-1);
73 std::string ExtractValue(const std::string& req) const
75 return std::string(req, bpos, len);
81 OP_CONTINUATION = 0x00,
95 static const unsigned char WS_MASKBIT = (1 << 7);
96 static const unsigned char WS_FINBIT = (1 << 7);
97 static const unsigned char WS_PAYLOAD_LENGTH_MAGIC_LARGE = 126;
98 static const unsigned char WS_PAYLOAD_LENGTH_MAGIC_HUGE = 127;
99 static const size_t WS_MAX_PAYLOAD_LENGTH_SMALL = 125;
100 static const size_t WS_MAX_PAYLOAD_LENGTH_LARGE = 65535;
101 static const size_t MAXHEADERSIZE = sizeof(uint64_t) + 2;
103 // Clients sending ping or pong frames faster than this are killed
104 static const time_t MINPINGPONGDELAY = 10;
108 OriginList& allowedorigins;
110 static size_t FillHeader(unsigned char* outbuf, size_t sendlength, OpCode opcode)
113 outbuf[pos++] = WS_FINBIT | opcode;
115 if (sendlength <= WS_MAX_PAYLOAD_LENGTH_SMALL)
117 outbuf[pos++] = sendlength;
119 else if (sendlength <= WS_MAX_PAYLOAD_LENGTH_LARGE)
121 outbuf[pos++] = WS_PAYLOAD_LENGTH_MAGIC_LARGE;
122 outbuf[pos++] = (sendlength >> 8) & 0xff;
123 outbuf[pos++] = sendlength & 0xff;
127 outbuf[pos++] = WS_PAYLOAD_LENGTH_MAGIC_HUGE;
128 const uint64_t len = sendlength;
129 for (int i = sizeof(uint64_t)-1; i >= 0; i--)
130 outbuf[pos++] = ((len >> i*8) & 0xff);
136 static StreamSocket::SendQueue::Element PrepareSendQElem(size_t size, OpCode opcode)
138 unsigned char header[MAXHEADERSIZE];
139 const size_t n = FillHeader(header, size, opcode);
141 return StreamSocket::SendQueue::Element(reinterpret_cast<const char*>(header), n);
144 int HandleAppData(StreamSocket* sock, std::string& appdataout, bool allowlarge)
146 std::string& myrecvq = GetRecvQ();
147 // Need 1 byte opcode, minimum 1 byte len, 4 bytes masking key
148 if (myrecvq.length() < 6)
151 const std::string& cmyrecvq = myrecvq;
152 unsigned char len1 = (unsigned char)cmyrecvq[1];
153 if (!(len1 & WS_MASKBIT))
155 sock->SetError("WebSocket protocol violation: unmasked client frame");
161 // Assume the length is a single byte, if not, update values later
162 unsigned int len = len1;
163 unsigned int payloadstartoffset = 6;
164 const unsigned char* maskkey = reinterpret_cast<const unsigned char*>(&cmyrecvq[2]);
166 if (len1 == WS_PAYLOAD_LENGTH_MAGIC_LARGE)
168 // allowlarge is false for control frames according to the RFC meaning large pings, etc. are not allowed
171 sock->SetError("WebSocket protocol violation: large control frame");
175 // Large frame, has 2 bytes len after the magic byte indicating the length
176 // Need 1 byte opcode, 3 bytes len, 4 bytes masking key
177 if (myrecvq.length() < 8)
180 unsigned char len2 = (unsigned char)cmyrecvq[2];
181 unsigned char len3 = (unsigned char)cmyrecvq[3];
182 len = (len2 << 8) | len3;
184 if (len <= WS_MAX_PAYLOAD_LENGTH_SMALL)
186 sock->SetError("WebSocket protocol violation: non-minimal length encoding used");
191 payloadstartoffset += 2;
193 else if (len1 == WS_PAYLOAD_LENGTH_MAGIC_HUGE)
195 sock->SetError("WebSocket: Huge frames are not supported");
199 if (myrecvq.length() < payloadstartoffset + len)
202 unsigned int maskkeypos = 0;
203 const std::string::iterator endit = myrecvq.begin() + payloadstartoffset + len;
204 for (std::string::const_iterator i = myrecvq.begin() + payloadstartoffset; i != endit; ++i)
206 const unsigned char c = (unsigned char)*i;
207 appdataout.push_back(c ^ maskkey[maskkeypos++]);
211 myrecvq.erase(myrecvq.begin(), endit);
215 int HandlePingPongFrame(StreamSocket* sock, bool isping)
217 if (lastpingpong + MINPINGPONGDELAY >= ServerInstance->Time())
219 sock->SetError("WebSocket: Ping/pong flood");
223 lastpingpong = ServerInstance->Time();
226 const int result = HandleAppData(sock, appdata, false);
227 // If it's a pong stop here regardless of the result so we won't generate a reply
228 if ((result <= 0) || (!isping))
231 StreamSocket::SendQueue::Element elem = PrepareSendQElem(appdata.length(), OP_PONG);
232 elem.append(appdata);
233 GetSendQ().push_back(elem);
235 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_WRITE);
239 int HandleWS(StreamSocket* sock, std::string& destrecvq)
241 if (GetRecvQ().empty())
244 unsigned char opcode = (unsigned char)GetRecvQ().c_str()[0];
245 opcode &= ~WS_FINBIT;
249 case OP_CONTINUATION:
253 return HandleAppData(sock, destrecvq, true);
258 return HandlePingPongFrame(sock, true);
263 // A pong frame may be sent unsolicited, so we have to handle it.
264 // It may carry application data which we need to remove from the recvq as well.
265 return HandlePingPongFrame(sock, false);
270 sock->SetError("Connection closed");
276 sock->SetError("WebSocket: Invalid opcode");
282 void FailHandshake(StreamSocket* sock, const char* httpreply, const char* sockerror)
284 GetSendQ().push_back(StreamSocket::SendQueue::Element(httpreply));
286 sock->SetError(sockerror);
289 int HandleHTTPReq(StreamSocket* sock)
291 std::string& recvq = GetRecvQ();
292 const std::string::size_type reqend = recvq.find("\r\n\r\n");
293 if (reqend == std::string::npos)
296 bool allowedorigin = false;
297 HTTPHeaderFinder originheader;
298 if (originheader.Find(recvq, "Origin:", 7, reqend))
300 const std::string origin = originheader.ExtractValue(recvq);
301 for (OriginList::const_iterator iter = allowedorigins.begin(); iter != allowedorigins.end(); ++iter)
303 if (InspIRCd::Match(origin, *iter, ascii_case_insensitive_map))
305 allowedorigin = true;
313 FailHandshake(sock, "HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n", "WebSocket: Received HTTP request from a non-whitelisted origin");
317 HTTPHeaderFinder keyheader;
318 if (!keyheader.Find(recvq, "Sec-WebSocket-Key:", 18, reqend))
320 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");
326 FailHandshake(sock, "HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n", "WebSocket: SHA-1 provider missing");
330 state = STATE_ESTABLISHED;
332 std::string key = keyheader.ExtractValue(recvq);
333 key.append(MagicGUID);
335 std::string reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ";
336 reply.append(BinToBase64((*sha1)->GenerateRaw(key), NULL, '=')).append("\r\n\r\n");
337 GetSendQ().push_back(StreamSocket::SendQueue::Element(reply));
339 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_WRITE);
341 recvq.erase(0, reqend + 4);
347 WebSocketHook(IOHookProvider* Prov, StreamSocket* sock, OriginList& AllowedOrigins)
349 , state(STATE_HTTPREQ)
351 , allowedorigins(AllowedOrigins)
353 sock->AddIOHook(this);
356 int OnStreamSocketWrite(StreamSocket* sock, StreamSocket::SendQueue& uppersendq) CXX11_OVERRIDE
358 StreamSocket::SendQueue& mysendq = GetSendQ();
360 // Return 1 to allow sending back an error HTTP response
361 if (state != STATE_ESTABLISHED)
362 return (mysendq.empty() ? 0 : 1);
364 if (!uppersendq.empty())
366 StreamSocket::SendQueue::Element elem = PrepareSendQElem(uppersendq.bytes(), OP_BINARY);
367 mysendq.push_back(elem);
368 mysendq.moveall(uppersendq);
374 int OnStreamSocketRead(StreamSocket* sock, std::string& destrecvq) CXX11_OVERRIDE
376 if (state == STATE_HTTPREQ)
378 int httpret = HandleHTTPReq(sock);
386 wsret = HandleWS(sock, destrecvq);
388 while ((!GetRecvQ().empty()) && (wsret > 0));
393 void OnStreamSocketClose(StreamSocket* sock) CXX11_OVERRIDE
398 void WebSocketHookProvider::OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
400 new WebSocketHook(this, sock, allowedorigins);
403 class ModuleWebSocket : public Module
405 dynamic_reference_nocheck<HashProvider> hash;
406 reference<WebSocketHookProvider> hookprov;
410 : hash(this, "hash/sha1")
411 , hookprov(new WebSocketHookProvider(this))
416 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
418 ConfigTagList tags = ServerInstance->Config->ConfTags("wsorigin");
419 if (tags.first == tags.second)
420 throw ModuleException("You have loaded the websocket module but not configured any allowed origins!");
422 OriginList allowedorigins;
423 for (ConfigIter i = tags.first; i != tags.second; ++i)
425 ConfigTag* tag = i->second;
427 // Ensure that we have the <wsorigin:allow> parameter.
428 const std::string allow = tag->getString("allow");
430 throw ModuleException("<wsorigin:allow> is a mandatory field, at " + tag->getTagLocation());
432 allowedorigins.push_back(allow);
434 hookprov->allowedorigins.swap(allowedorigins);
437 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
439 if (type != ExtensionItem::EXT_USER)
442 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
443 if ((user) && (user->eh.GetModHook(this)))
444 ServerInstance->Users.QuitUser(user, "WebSocket module unloading");
447 Version GetVersion() CXX11_OVERRIDE
449 return Version("Provides RFC 6455 WebSocket support", VF_VENDOR);
453 MODULE_INIT(ModuleWebSocket)