nanoMMO 0.97.8Test coverage / Every file / gateway/websocket.cc

Created: 2026-11-26 01:25

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