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 // The HTTP origins that can connect to the server.
37 OriginList allowedorigins;
39 // Whether to trust the X-Real-IP or X-Forwarded-For headers.
42 // Whether to send as UTF-8 text instead of binary data.
46 class WebSocketHookProvider : public IOHookProvider
49 WebSocketConfig config;
50 WebSocketHookProvider(Module* mod)
51 : IOHookProvider(mod, "websocket", IOHookProvider::IOH_UNKNOWN, true)
55 void OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server) CXX11_OVERRIDE;
57 void OnConnect(StreamSocket* sock) CXX11_OVERRIDE
62 class WebSocketHook : public IOHookMiddle
64 class HTTPHeaderFinder
66 std::string::size_type bpos;
67 std::string::size_type len;
70 bool Find(const std::string& req, const char* header, std::string::size_type headerlen, std::string::size_type maxpos)
72 std::string::size_type keybegin = req.find(header);
73 if ((keybegin == std::string::npos) || (keybegin > maxpos) || (keybegin == 0) || (req[keybegin-1] != '\n'))
76 keybegin += headerlen;
78 bpos = req.find_first_not_of(whitespace, keybegin, sizeof(whitespace)-1);
79 if ((bpos == std::string::npos) || (bpos > maxpos))
82 const std::string::size_type epos = req.find_first_of(whitespace, bpos, sizeof(whitespace)-1);
88 std::string ExtractValue(const std::string& req) const
90 return std::string(req, bpos, len);
96 OP_CONTINUATION = 0x00,
110 static const unsigned char WS_MASKBIT = (1 << 7);
111 static const unsigned char WS_FINBIT = (1 << 7);
112 static const unsigned char WS_PAYLOAD_LENGTH_MAGIC_LARGE = 126;
113 static const unsigned char WS_PAYLOAD_LENGTH_MAGIC_HUGE = 127;
114 static const size_t WS_MAX_PAYLOAD_LENGTH_SMALL = 125;
115 static const size_t WS_MAX_PAYLOAD_LENGTH_LARGE = 65535;
116 static const size_t MAXHEADERSIZE = sizeof(uint64_t) + 2;
118 // Clients sending ping or pong frames faster than this are killed
119 static const time_t MINPINGPONGDELAY = 10;
123 WebSocketConfig& config;
125 static size_t FillHeader(unsigned char* outbuf, size_t sendlength, OpCode opcode)
128 outbuf[pos++] = WS_FINBIT | opcode;
130 if (sendlength <= WS_MAX_PAYLOAD_LENGTH_SMALL)
132 outbuf[pos++] = sendlength;
134 else if (sendlength <= WS_MAX_PAYLOAD_LENGTH_LARGE)
136 outbuf[pos++] = WS_PAYLOAD_LENGTH_MAGIC_LARGE;
137 outbuf[pos++] = (sendlength >> 8) & 0xff;
138 outbuf[pos++] = sendlength & 0xff;
142 outbuf[pos++] = WS_PAYLOAD_LENGTH_MAGIC_HUGE;
143 const uint64_t len = sendlength;
144 for (int i = sizeof(uint64_t)-1; i >= 0; i--)
145 outbuf[pos++] = ((len >> i*8) & 0xff);
151 static StreamSocket::SendQueue::Element PrepareSendQElem(size_t size, OpCode opcode)
153 unsigned char header[MAXHEADERSIZE];
154 const size_t n = FillHeader(header, size, opcode);
156 return StreamSocket::SendQueue::Element(reinterpret_cast<const char*>(header), n);
159 int HandleAppData(StreamSocket* sock, std::string& appdataout, bool allowlarge)
161 std::string& myrecvq = GetRecvQ();
162 // Need 1 byte opcode, minimum 1 byte len, 4 bytes masking key
163 if (myrecvq.length() < 6)
166 const std::string& cmyrecvq = myrecvq;
167 unsigned char len1 = (unsigned char)cmyrecvq[1];
168 if (!(len1 & WS_MASKBIT))
170 sock->SetError("WebSocket protocol violation: unmasked client frame");
176 // Assume the length is a single byte, if not, update values later
177 unsigned int len = len1;
178 unsigned int payloadstartoffset = 6;
179 const unsigned char* maskkey = reinterpret_cast<const unsigned char*>(&cmyrecvq[2]);
181 if (len1 == WS_PAYLOAD_LENGTH_MAGIC_LARGE)
183 // allowlarge is false for control frames according to the RFC meaning large pings, etc. are not allowed
186 sock->SetError("WebSocket protocol violation: large control frame");
190 // Large frame, has 2 bytes len after the magic byte indicating the length
191 // Need 1 byte opcode, 3 bytes len, 4 bytes masking key
192 if (myrecvq.length() < 8)
195 unsigned char len2 = (unsigned char)cmyrecvq[2];
196 unsigned char len3 = (unsigned char)cmyrecvq[3];
197 len = (len2 << 8) | len3;
199 if (len <= WS_MAX_PAYLOAD_LENGTH_SMALL)
201 sock->SetError("WebSocket protocol violation: non-minimal length encoding used");
206 payloadstartoffset += 2;
208 else if (len1 == WS_PAYLOAD_LENGTH_MAGIC_HUGE)
210 sock->SetError("WebSocket: Huge frames are not supported");
214 if (myrecvq.length() < payloadstartoffset + len)
217 unsigned int maskkeypos = 0;
218 const std::string::iterator endit = myrecvq.begin() + payloadstartoffset + len;
219 for (std::string::const_iterator i = myrecvq.begin() + payloadstartoffset; i != endit; ++i)
221 const unsigned char c = (unsigned char)*i;
222 appdataout.push_back(c ^ maskkey[maskkeypos++]);
226 myrecvq.erase(myrecvq.begin(), endit);
230 int HandlePingPongFrame(StreamSocket* sock, bool isping)
232 if (lastpingpong + MINPINGPONGDELAY >= ServerInstance->Time())
234 sock->SetError("WebSocket: Ping/pong flood");
238 lastpingpong = ServerInstance->Time();
241 const int result = HandleAppData(sock, appdata, false);
242 // If it's a pong stop here regardless of the result so we won't generate a reply
243 if ((result <= 0) || (!isping))
246 StreamSocket::SendQueue::Element elem = PrepareSendQElem(appdata.length(), OP_PONG);
247 elem.append(appdata);
248 GetSendQ().push_back(elem);
250 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_WRITE);
254 int HandleWS(StreamSocket* sock, std::string& destrecvq)
256 if (GetRecvQ().empty())
259 unsigned char opcode = (unsigned char)GetRecvQ().c_str()[0];
260 switch (opcode & ~WS_FINBIT)
262 case OP_CONTINUATION:
267 const int result = HandleAppData(sock, appdata, true);
271 // Strip out any CR+LF which may have been erroneously sent.
272 for (std::string::const_iterator iter = appdata.begin(); iter != appdata.end(); ++iter)
274 if (*iter != '\r' && *iter != '\n')
275 destrecvq.push_back(*iter);
278 // If we are on the final message of this block append a line terminator.
279 if (opcode & WS_FINBIT)
280 destrecvq.append("\r\n");
287 return HandlePingPongFrame(sock, true);
292 // A pong frame may be sent unsolicited, so we have to handle it.
293 // It may carry application data which we need to remove from the recvq as well.
294 return HandlePingPongFrame(sock, false);
299 sock->SetError("Connection closed");
305 sock->SetError("WebSocket: Invalid opcode");
311 void FailHandshake(StreamSocket* sock, const char* httpreply, const char* sockerror)
313 GetSendQ().push_back(StreamSocket::SendQueue::Element(httpreply));
315 sock->SetError(sockerror);
318 int HandleHTTPReq(StreamSocket* sock)
320 std::string& recvq = GetRecvQ();
321 const std::string::size_type reqend = recvq.find("\r\n\r\n");
322 if (reqend == std::string::npos)
325 bool allowedorigin = false;
326 HTTPHeaderFinder originheader;
327 if (originheader.Find(recvq, "Origin:", 7, reqend))
329 const std::string origin = originheader.ExtractValue(recvq);
330 for (OriginList::const_iterator iter = config.allowedorigins.begin(); iter != config.allowedorigins.end(); ++iter)
332 if (InspIRCd::Match(origin, *iter, ascii_case_insensitive_map))
334 allowedorigin = true;
342 FailHandshake(sock, "HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n", "WebSocket: Received HTTP request from a non-whitelisted origin");
346 if (config.behindproxy && sock->type == StreamSocket::SS_USER)
348 LocalUser* luser = static_cast<UserIOHandler*>(sock)->user;
349 irc::sockets::sockaddrs realsa(luser->client_sa);
351 HTTPHeaderFinder proxyheader;
352 if (proxyheader.Find(recvq, "X-Real-IP:", 10, reqend)
353 && irc::sockets::aptosa(proxyheader.ExtractValue(recvq), realsa.port(), realsa))
355 // Nothing to do here.
357 else if (proxyheader.Find(recvq, "X-Forwarded-For:", 16, reqend)
358 && irc::sockets::aptosa(proxyheader.ExtractValue(recvq), realsa.port(), realsa))
360 // Nothing to do here.
363 // Give the user their real IP address.
364 if (realsa != luser->client_sa)
365 luser->SetClientIP(realsa);
369 HTTPHeaderFinder keyheader;
370 if (!keyheader.Find(recvq, "Sec-WebSocket-Key:", 18, reqend))
372 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");
378 FailHandshake(sock, "HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n", "WebSocket: SHA-1 provider missing");
382 state = STATE_ESTABLISHED;
384 std::string key = keyheader.ExtractValue(recvq);
385 key.append(MagicGUID);
387 std::string reply = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ";
388 reply.append(BinToBase64((*sha1)->GenerateRaw(key), NULL, '=')).append("\r\n\r\n");
389 GetSendQ().push_back(StreamSocket::SendQueue::Element(reply));
391 SocketEngine::ChangeEventMask(sock, FD_ADD_TRIAL_WRITE);
393 recvq.erase(0, reqend + 4);
399 WebSocketHook(IOHookProvider* Prov, StreamSocket* sock, WebSocketConfig& cfg)
401 , state(STATE_HTTPREQ)
405 sock->AddIOHook(this);
408 int OnStreamSocketWrite(StreamSocket* sock, StreamSocket::SendQueue& uppersendq) CXX11_OVERRIDE
410 StreamSocket::SendQueue& mysendq = GetSendQ();
412 // Return 1 to allow sending back an error HTTP response
413 if (state != STATE_ESTABLISHED)
414 return (mysendq.empty() ? 0 : 1);
417 for (StreamSocket::SendQueue::const_iterator elem = uppersendq.begin(); elem != uppersendq.end(); ++elem)
419 for (StreamSocket::SendQueue::Element::const_iterator chr = elem->begin(); chr != elem->end(); ++chr)
423 // We have found an entire message. Send it in its own frame.
424 if (config.sendastext)
426 // If we send messages as text then we need to ensure they are valid UTF-8.
428 utf8::replace_invalid(message.begin(), message.end(), std::back_inserter(encoded));
430 mysendq.push_back(PrepareSendQElem(encoded.length(), OP_TEXT));
431 mysendq.push_back(encoded);
435 // Otherwise, send the raw message as a binary frame.
436 mysendq.push_back(PrepareSendQElem(message.length(), OP_BINARY));
437 mysendq.push_back(message);
441 else if (*chr != '\r')
443 message.push_back(*chr);
448 // Empty the upper send queue and push whatever is left back onto it.
450 if (!message.empty())
452 uppersendq.push_back(message);
459 int OnStreamSocketRead(StreamSocket* sock, std::string& destrecvq) CXX11_OVERRIDE
461 if (state == STATE_HTTPREQ)
463 int httpret = HandleHTTPReq(sock);
471 wsret = HandleWS(sock, destrecvq);
473 while ((!GetRecvQ().empty()) && (wsret > 0));
478 void OnStreamSocketClose(StreamSocket* sock) CXX11_OVERRIDE
483 void WebSocketHookProvider::OnAccept(StreamSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
485 new WebSocketHook(this, sock, config);
488 class ModuleWebSocket : public Module
490 dynamic_reference_nocheck<HashProvider> hash;
491 reference<WebSocketHookProvider> hookprov;
495 : hash(this, "hash/sha1")
496 , hookprov(new WebSocketHookProvider(this))
501 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
503 ConfigTagList tags = ServerInstance->Config->ConfTags("wsorigin");
504 if (tags.first == tags.second)
505 throw ModuleException("You have loaded the websocket module but not configured any allowed origins!");
507 WebSocketConfig config;
508 for (ConfigIter i = tags.first; i != tags.second; ++i)
510 ConfigTag* tag = i->second;
512 // Ensure that we have the <wsorigin:allow> parameter.
513 const std::string allow = tag->getString("allow");
515 throw ModuleException("<wsorigin:allow> is a mandatory field, at " + tag->getTagLocation());
517 config.allowedorigins.push_back(allow);
520 ConfigTag* tag = ServerInstance->Config->ConfValue("websocket");
521 config.behindproxy = tag->getBool("behindproxy");
522 config.sendastext = tag->getBool("sendastext", true);
524 // Everything is okay; apply the new config.
525 hookprov->config = config;
528 void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item) CXX11_OVERRIDE
530 if (type != ExtensionItem::EXT_USER)
533 LocalUser* user = IS_LOCAL(static_cast<User*>(item));
534 if ((user) && (user->eh.GetModHook(this)))
535 ServerInstance->Users.QuitUser(user, "WebSocket module unloading");
538 Version GetVersion() CXX11_OVERRIDE
540 return Version("Provides RFC 6455 WebSocket support", VF_VENDOR);
544 MODULE_INIT(ModuleWebSocket)