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 switch (opcode & ~WS_FINBIT)
247 case OP_CONTINUATION:
252 const int result = HandleAppData(sock, appdata, true);
256 // Strip out any CR+LF which may have been erroneously sent.
257 for (std::string::const_iterator iter = appdata.begin(); iter != appdata.end(); ++iter)
259 if (*iter != '\r' && *iter != '\n')
260 destrecvq.push_back(*iter);
263 // If we are on the final message of this block append a line terminator.
264 if (opcode & WS_FINBIT)
265 destrecvq.append("\r\n");
272 return HandlePingPongFrame(sock, true);
277 // A pong frame may be sent unsolicited, so we have to handle it.
278 // It may carry application data which we need to remove from the recvq as well.
279 return HandlePingPongFrame(sock, false);
284 sock->SetError("Connection closed");
290 sock->SetError("WebSocket: Invalid opcode");
296 void FailHandshake(StreamSocket* sock, const char* httpreply, const char* sockerror)
298 GetSendQ().push_back(StreamSocket::SendQueue::Element(httpreply));
300 sock->SetError(sockerror);
303 int HandleHTTPReq(StreamSocket* sock)
305 std::string& recvq = GetRecvQ();
306 const std::string::size_type reqend = recvq.find("\r\n\r\n");
307 if (reqend == std::string::npos)
310 bool allowedorigin = false;
311 HTTPHeaderFinder originheader;
312 if (originheader.Find(recvq, "Origin:", 7, reqend))
314 const std::string origin = originheader.ExtractValue(recvq);
315 for (OriginList::const_iterator iter = allowedorigins.begin(); iter != allowedorigins.end(); ++iter)
317 if (InspIRCd::Match(origin, *iter, ascii_case_insensitive_map))
319 allowedorigin = true;
327 FailHandshake(sock, "HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n", "WebSocket: Received HTTP request from a non-whitelisted origin");
331 HTTPHeaderFinder keyheader;
332 if (!keyheader.Find(recvq, "Sec-WebSocket-Key:", 18, reqend))
334 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");
340 FailHandshake(sock, "HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n", "WebSocket: SHA-1 provider missing");
344 state = STATE_ESTABLISHED;
346 std::string key = keyheader.ExtractValue(recvq);
347 key.append(MagicGUID);
349 std::string reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ";
350 reply.append(BinToBase64((*sha1)->GenerateRaw(key), NULL, '=')).append("\r\n\r\n");
351 GetSendQ().push_back(StreamSocket::SendQueue::Element(reply));
353 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_WRITE);
355 recvq.erase(0, reqend + 4);
361 WebSocketHook(IOHookProvider* Prov, StreamSocket* sock, OriginList& AllowedOrigins)
363 , state(STATE_HTTPREQ)
365 , allowedorigins(AllowedOrigins)
367 sock->AddIOHook(this);
370 int OnStreamSocketWrite(StreamSocket* sock, StreamSocket::SendQueue& uppersendq) CXX11_OVERRIDE
372 StreamSocket::SendQueue& mysendq = GetSendQ();
374 // Return 1 to allow sending back an error HTTP response
375 if (state != STATE_ESTABLISHED)
376 return (mysendq.empty() ? 0 : 1);
379 for (StreamSocket::SendQueue::const_iterator elem = uppersendq.begin(); elem != uppersendq.end(); ++elem)
381 for (StreamSocket::SendQueue::Element::const_iterator chr = elem->begin(); chr != elem->end(); ++chr)
385 // We have found an entire message. Send it in its own frame.
386 mysendq.push_back(PrepareSendQElem(message.length(), OP_BINARY));
387 mysendq.push_back(message);
390 else if (*chr != '\r')
392 message.push_back(*chr);
397 // Empty the upper send queue and push whatever is left back onto it.
399 if (!message.empty())
401 uppersendq.push_back(message);
408 int OnStreamSocketRead(StreamSocket* sock, std::string& destrecvq) CXX11_OVERRIDE
410 if (state == STATE_HTTPREQ)
412 int httpret = HandleHTTPReq(sock);
420 wsret = HandleWS(sock, destrecvq);
422 while ((!GetRecvQ().empty()) && (wsret > 0));
427 void OnStreamSocketClose(StreamSocket* sock) CXX11_OVERRIDE
432 void WebSocketHookProvider::OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
434 new WebSocketHook(this, sock, allowedorigins);
437 class ModuleWebSocket : public Module
439 dynamic_reference_nocheck<HashProvider> hash;
440 reference<WebSocketHookProvider> hookprov;
444 : hash(this, "hash/sha1")
445 , hookprov(new WebSocketHookProvider(this))
450 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
452 ConfigTagList tags = ServerInstance->Config->ConfTags("wsorigin");
453 if (tags.first == tags.second)
454 throw ModuleException("You have loaded the websocket module but not configured any allowed origins!");
456 OriginList allowedorigins;
457 for (ConfigIter i = tags.first; i != tags.second; ++i)
459 ConfigTag* tag = i->second;
461 // Ensure that we have the <wsorigin:allow> parameter.
462 const std::string allow = tag->getString("allow");
464 throw ModuleException("<wsorigin:allow> is a mandatory field, at " + tag->getTagLocation());
466 allowedorigins.push_back(allow);
468 hookprov->allowedorigins.swap(allowedorigins);
471 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
473 if (type != ExtensionItem::EXT_USER)
476 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
477 if ((user) && (user->eh.GetModHook(this)))
478 ServerInstance->Users.QuitUser(user, "WebSocket module unloading");
481 Version GetVersion() CXX11_OVERRIDE
483 return Version("Provides RFC 6455 WebSocket support", VF_VENDOR);
487 MODULE_INIT(ModuleWebSocket)