nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
websocket.cc
Go to the documentation of this file.
1#include "gateway/websocket.h"
2
3#include <openssl/evp.h>
4
5#include <array>
6#include <cstddef>
7#include <cstdint>
8#include <optional>
9#include <string>
10#include <string_view>
11#include <utility>
12#include <vector>
13
14#include "absl/status/status.h"
15#include "absl/status/statusor.h"
16#include "absl/strings/ascii.h"
17#include "absl/strings/escaping.h"
18#include "absl/strings/match.h"
19#include "absl/strings/str_cat.h"
20#include "absl/strings/str_split.h"
21#include "absl/strings/strip.h"
22
23namespace nanommo {
24namespace {
25
26// RFC 6455's, the same for every server.
27constexpr std::string_view kGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
28
29// A control frame's payload fits in its first length byte.
30constexpr std::size_t kMaxControl = 125;
31
32// Whether a comma-separated header value has the token, in any case.
33bool HasToken(std::string_view value, std::string_view token) {
34 for (const std::string_view part : absl::StrSplit(value, ',')) {
35 if (absl::EqualsIgnoreCase(absl::StripAsciiWhitespace(part), token)) {
36 return true;
37 }
38 }
39 return false;
40}
41
42std::string_view Reason(int status) {
43 switch (status) {
44 case 400:
45 return "Bad Request";
46 case 403:
47 return "Forbidden";
48 case 404:
49 return "Not Found";
50 case 502:
51 return "Bad Gateway";
52 default:
53 return "Error";
54 }
55}
56
57// The length, in the shortest of the three ways the protocol has, after the
58// first byte; masked or not in the length byte's top bit.
59void AppendLength(std::string& frame, std::size_t size, bool masked) {
60 const auto mask_bit = static_cast<unsigned char>(masked ? 0x80 : 0);
61 if (size <= kMaxControl) {
62 frame.push_back(static_cast<char>(mask_bit | size));
63 } else if (size <= 0xFFFF) {
64 frame.push_back(static_cast<char>(mask_bit | 126));
65 frame.push_back(static_cast<char>((size >> 8) & 0xFF));
66 frame.push_back(static_cast<char>(size & 0xFF));
67 } else {
68 frame.push_back(static_cast<char>(mask_bit | 127));
69 for (int shift = 56; shift >= 0; shift -= 8) {
70 frame.push_back(static_cast<char>((size >> shift) & 0xFF));
71 }
72 }
73}
74
75} // namespace
76
77absl::StatusOr<Handshake> ParseHandshake(std::string_view request) {
78 std::vector<std::string_view> lines = absl::StrSplit(request, "\r\n");
79 // GET <path> HTTP/1.1, then a header a line.
80 const std::vector<std::string_view> first = absl::StrSplit(lines[0], ' ');
81 if (first.size() != 3 || first[0] != "GET" ||
82 !absl::StartsWith(first[2], "HTTP/1.1") || first[1].empty() ||
83 first[1][0] != '/') {
84 return absl::InvalidArgumentError("not an HTTP/1.1 GET");
85 }
86 bool upgrade = false;
87 bool connection = false;
88 bool version = false;
89 Handshake handshake{.path = std::string(first[1]), .key = ""};
90 for (std::size_t i = 1; i < lines.size(); ++i) {
91 const std::size_t colon = lines[i].find(':');
92 if (colon == std::string_view::npos) {
93 continue;
94 }
95 const std::string_view name =
96 absl::StripAsciiWhitespace(lines[i].substr(0, colon));
97 const std::string_view value =
98 absl::StripAsciiWhitespace(lines[i].substr(colon + 1));
99 if (absl::EqualsIgnoreCase(name, "Upgrade")) {
100 upgrade = HasToken(value, "websocket");
101 } else if (absl::EqualsIgnoreCase(name, "Connection")) {
102 connection = HasToken(value, "upgrade");
103 } else if (absl::EqualsIgnoreCase(name, "Sec-WebSocket-Version")) {
104 version = value == "13";
105 } else if (absl::EqualsIgnoreCase(name, "Sec-WebSocket-Key")) {
106 handshake.key = std::string(value);
107 }
108 }
109 if (!upgrade || !connection) {
110 return absl::InvalidArgumentError("not an upgrade to websocket");
111 }
112 if (!version) {
113 return absl::InvalidArgumentError("not WebSocket version 13");
114 }
115 // The key is 16 random bytes in base 64.
116 std::string bytes;
117 if (!absl::Base64Unescape(handshake.key, &bytes) || bytes.size() != 16) {
118 return absl::InvalidArgumentError("no Sec-WebSocket-Key of 16 bytes");
119 }
120 return handshake;
121}
122
123std::string AcceptKey(std::string_view key) {
124 const std::string input = absl::StrCat(key, kGuid);
125 std::array<unsigned char, EVP_MAX_MD_SIZE> digest{};
126 unsigned int size = 0;
127 EVP_Digest(input.data(), input.size(), digest.data(), &size, EVP_sha1(),
128 nullptr);
129 return absl::Base64Escape(std::string(digest.begin(), digest.begin() + size));
130}
131
132std::string Accept(std::string_view key) {
133 return absl::StrCat(
134 "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
135 "Connection: Upgrade\r\nSec-WebSocket-Accept: ",
136 AcceptKey(key), "\r\n\r\n");
137}
138
139std::string Refuse(int status, std::string_view why) {
140 return absl::StrCat("HTTP/1.1 ", status, " ", Reason(status),
141 "\r\nContent-Type: text/plain\r\nContent-Length: ",
142 why.size(), "\r\nConnection: close\r\n\r\n", why);
143}
144
145std::string ServerFrame(Opcode opcode, std::string_view payload) {
146 std::string frame;
147 frame.reserve(payload.size() + 10);
148 frame.push_back(static_cast<char>(0x80 | static_cast<uint8_t>(opcode)));
149 AppendLength(frame, payload.size(), /*masked=*/false);
150 frame.append(payload);
151 return frame;
152}
153
154std::string ClientFrame(Opcode opcode, std::string_view payload, uint32_t mask,
155 bool fin) {
156 std::string frame;
157 frame.push_back(
158 static_cast<char>((fin ? 0x80 : 0) | static_cast<uint8_t>(opcode)));
159 AppendLength(frame, payload.size(), /*masked=*/true);
160 const std::array<char, 4> key = {
161 static_cast<char>(mask >> 24), static_cast<char>((mask >> 16) & 0xFF),
162 static_cast<char>((mask >> 8) & 0xFF), static_cast<char>(mask & 0xFF)};
163 frame.append(key.data(), key.size());
164 for (std::size_t i = 0; i < payload.size(); ++i) {
165 frame.push_back(static_cast<char>(payload[i] ^ key[i % 4]));
166 }
167 return frame;
168}
169
170void FrameDecoder::Append(std::string_view bytes) {
171 if (status_.ok()) {
172 buffer_.append(bytes);
173 }
174}
175
176std::optional<Message> FrameDecoder::Fail(std::string_view why) {
177 status_ = absl::InvalidArgumentError(why);
178 buffer_.clear();
179 fragments_.clear();
180 return std::nullopt;
181}
182
183std::optional<Message> FrameDecoder::Next() {
184 while (status_.ok()) {
185 if (buffer_.size() < 2) {
186 return std::nullopt;
187 }
188 const auto byte = [&](std::size_t i) {
189 return static_cast<uint8_t>(buffer_[i]);
190 };
191 const bool fin = (byte(0) & 0x80) != 0;
192 if ((byte(0) & 0x70) != 0) {
193 return Fail("a frame uses bits no extension was agreed for");
194 }
195 const auto opcode = static_cast<Opcode>(byte(0) & 0x0F);
196 const bool control = (byte(0) & 0x08) != 0;
197 switch (opcode) {
199 case Opcode::kText:
200 case Opcode::kBinary:
201 case Opcode::kClose:
202 case Opcode::kPing:
203 case Opcode::kPong:
204 break;
205 default:
206 return Fail("a frame with an opcode the protocol doesn't have");
207 }
208 if ((byte(1) & 0x80) == 0) {
209 return Fail("a client's frame has to be masked");
210 }
211 std::size_t header = 2;
212 uint64_t size = byte(1) & 0x7F;
213 if (size == 126) {
214 header = 4;
215 if (buffer_.size() < header) {
216 return std::nullopt;
217 }
218 size = (uint64_t{byte(2)} << 8) | byte(3);
219 } else if (size == 127) {
220 header = 10;
221 if (buffer_.size() < header) {
222 return std::nullopt;
223 }
224 size = 0;
225 for (std::size_t i = 2; i < 10; ++i) {
226 size = (size << 8) | byte(i);
227 }
228 }
229 if (control && (!fin || size > kMaxControl)) {
230 return Fail("a control frame has to be whole, and 125 bytes at most");
231 }
232 // Refused before it's all here, so a client can't make us hold more.
233 if (!control && fragments_.size() + size > max_) {
234 return Fail(absl::StrCat("a message over ", max_, " bytes"));
235 }
236 if (buffer_.size() < header + 4 + size) {
237 return std::nullopt;
238 }
239 const std::string_view mask(buffer_.data() + header, 4);
240 std::string payload(buffer_, header + 4, size);
241 for (std::size_t i = 0; i < payload.size(); ++i) {
242 payload[i] = static_cast<char>(payload[i] ^ mask[i % 4]);
243 }
244 buffer_.erase(0, header + 4 + size);
245 if (control) {
246 return Message{.opcode = opcode, .payload = std::move(payload)};
247 }
248 if (opcode == Opcode::kContinuation) {
249 if (!fragmented_) {
250 return Fail("a continuation of no message");
251 }
252 } else if (fragmented_) {
253 return Fail("a new message before the last one's end");
254 } else {
255 fragmented_ = opcode;
256 }
257 fragments_.append(payload);
258 if (fin) {
259 Message message{.opcode = *fragmented_, .payload = std::move(fragments_)};
260 fragments_.clear();
261 fragmented_.reset();
262 return message;
263 }
264 }
265 return std::nullopt;
266}
267
268} // namespace nanommo
std::optional< Message > Next()
Definition websocket.cc:183
void Append(std::string_view bytes)
Definition websocket.cc:170
Definition chat.cc:9
absl::StatusOr< Handshake > ParseHandshake(std::string_view request)
Definition websocket.cc:77
std::string ClientFrame(Opcode opcode, std::string_view payload, uint32_t mask, bool fin)
Definition websocket.cc:154
std::string Refuse(int status, std::string_view why)
An HTTP answer that turns the connection down, with why in its body.
Definition websocket.cc:139
std::string AcceptKey(std::string_view key)
Definition websocket.cc:123
std::string ServerFrame(Opcode opcode, std::string_view payload)
A frame as the server sends it: whole, and never masked.
Definition websocket.cc:145
std::string Accept(std::string_view key)
The server's answer that switches the connection over to WebSocket.
Definition websocket.cc:132
What a client's opening handshake asks for.
Definition websocket.h:19
std::string key
Definition websocket.h:21
A whole message, or a ping, a pong or a close.
Definition websocket.h:50