GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: inspector_socket.cc Lines: 353 387 91.2 %
Date: 2022-07-25 04:16:17 Branches: 130 181 71.8 %

Line Branch Exec Source
1
#include "inspector_socket.h"
2
#include "llhttp.h"
3
4
#include "base64-inl.h"
5
#include "util-inl.h"
6
7
#include "openssl/sha.h"  // Sha-1 hash
8
9
#include <cstring>
10
#include <map>
11
12
#define ACCEPT_KEY_LENGTH base64_encoded_size(20)
13
14
#define DUMP_READS 0
15
#define DUMP_WRITES 0
16
17
namespace node {
18
namespace inspector {
19
20
class TcpHolder {
21
 public:
22
  static void DisconnectAndDispose(TcpHolder* holder);
23
  using Pointer = DeleteFnPtr<TcpHolder, DisconnectAndDispose>;
24
25
  static Pointer Accept(uv_stream_t* server,
26
                        InspectorSocket::DelegatePointer delegate);
27
  void SetHandler(ProtocolHandler* handler);
28
  int WriteRaw(const std::vector<char>& buffer, uv_write_cb write_cb);
29
  uv_tcp_t* tcp() {
30
    return &tcp_;
31
  }
32
  InspectorSocket::Delegate* delegate();
33
34
 private:
35
523
  static TcpHolder* From(void* handle) {
36
523
    return node::ContainerOf(&TcpHolder::tcp_,
37
523
                             reinterpret_cast<uv_tcp_t*>(handle));
38
  }
39
  static void OnClosed(uv_handle_t* handle);
40
  static void OnDataReceivedCb(uv_stream_t* stream, ssize_t nread,
41
                               const uv_buf_t* buf);
42
  explicit TcpHolder(InspectorSocket::DelegatePointer delegate);
43
84
  ~TcpHolder() = default;
44
  void ReclaimUvBuf(const uv_buf_t* buf, ssize_t read);
45
46
  uv_tcp_t tcp_;
47
  const InspectorSocket::DelegatePointer delegate_;
48
  ProtocolHandler* handler_;
49
  std::vector<char> buffer;
50
};
51
52
53
class ProtocolHandler {
54
 public:
55
  ProtocolHandler(InspectorSocket* inspector, TcpHolder::Pointer tcp);
56
57
  virtual void AcceptUpgrade(const std::string& accept_key) = 0;
58
  virtual void OnData(std::vector<char>* data) = 0;
59
  virtual void OnEof() = 0;
60
  virtual void Write(const std::vector<char> data) = 0;
61
  virtual void CancelHandshake() = 0;
62
63
  std::string GetHost() const;
64
65
20
  InspectorSocket* inspector() {
66
20
    return inspector_;
67
  }
68
  virtual void Shutdown() = 0;
69
70
 protected:
71
238
  virtual ~ProtocolHandler() = default;
72
  int WriteRaw(const std::vector<char>& buffer, uv_write_cb write_cb);
73
  InspectorSocket::Delegate* delegate();
74
75
  InspectorSocket* const inspector_;
76
  TcpHolder::Pointer tcp_;
77
};
78
79
namespace {
80
81
#if DUMP_READS || DUMP_WRITES
82
static void dump_hex(const char* buf, size_t len) {
83
  const char* ptr = buf;
84
  const char* end = ptr + len;
85
  const char* cptr;
86
  char c;
87
  int i;
88
89
  while (ptr < end) {
90
    cptr = ptr;
91
    for (i = 0; i < 16 && ptr < end; i++) {
92
      printf("%2.2X  ", static_cast<unsigned char>(*(ptr++)));
93
    }
94
    for (i = 72 - (i * 4); i > 0; i--) {
95
      printf(" ");
96
    }
97
    for (i = 0; i < 16 && cptr < end; i++) {
98
      c = *(cptr++);
99
      printf("%c", (c > 0x19) ? c : '.');
100
    }
101
    printf("\n");
102
  }
103
  printf("\n\n");
104
}
105
#endif
106
107
class WriteRequest {
108
 public:
109
2230
  WriteRequest(ProtocolHandler* handler, const std::vector<char>& buffer)
110
2230
      : handler(handler)
111
      , storage(buffer)
112
      , req(uv_write_t())
113
2230
      , buf(uv_buf_init(storage.data(), storage.size())) {}
114
115
2250
  static WriteRequest* from_write_req(uv_write_t* req) {
116
2250
    return node::ContainerOf(&WriteRequest::req, req);
117
  }
118
119
2221
  static void Cleanup(uv_write_t* req, int status) {
120
2221
    delete WriteRequest::from_write_req(req);
121
2221
  }
122
123
  ProtocolHandler* const handler;
124
  std::vector<char> storage;
125
  uv_write_t req;
126
  uv_buf_t buf;
127
};
128
129
439
void allocate_buffer(uv_handle_t* stream, size_t len, uv_buf_t* buf) {
130
439
  *buf = uv_buf_init(new char[len], len);
131
439
}
132
133
145
static void remove_from_beginning(std::vector<char>* buffer, size_t count) {
134
145
  buffer->erase(buffer->begin(), buffer->begin() + count);
135
145
}
136
137
static const char CLOSE_FRAME[] = {'\x88', '\x00'};
138
139
enum ws_decode_result {
140
  FRAME_OK, FRAME_INCOMPLETE, FRAME_CLOSE, FRAME_ERROR
141
};
142
143
35
static void generate_accept_string(const std::string& client_key,
144
                                   char (*buffer)[ACCEPT_KEY_LENGTH]) {
145
  // Magic string from websockets spec.
146
  static const char ws_magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
147
70
  std::string input(client_key + ws_magic);
148
  char hash[SHA_DIGEST_LENGTH];
149
35
  USE(SHA1(reinterpret_cast<const unsigned char*>(&input[0]), input.size(),
150
       reinterpret_cast<unsigned char*>(hash)));
151
35
  node::base64_encode(hash, sizeof(hash), *buffer, sizeof(*buffer));
152
35
}
153
154
86
static std::string TrimPort(const std::string& host) {
155
86
  size_t last_colon_pos = host.rfind(':');
156
86
  if (last_colon_pos == std::string::npos)
157
    return host;
158
86
  size_t bracket = host.rfind(']');
159

86
  if (bracket == std::string::npos || last_colon_pos > bracket)
160
86
    return host.substr(0, last_colon_pos);
161
  return host;
162
}
163
164
86
static bool IsIPAddress(const std::string& host) {
165


86
  if (host.length() >= 4 && host.front() == '[' && host.back() == ']')
166
    return true;
167
86
  uint_fast16_t accum = 0;
168
86
  uint_fast8_t quads = 0;
169
86
  bool empty = true;
170
203
  auto endOctet = [&accum, &quads, &empty](bool final = false) {
171

34
    return !empty && accum <= 0xff && ++quads <= 4 && final == (quads == 4) &&
172

71
           (empty = true) && !(accum = 0);
173
86
  };
174
176
  for (char c : host) {
175

171
    if (isdigit(c)) {
176
142
      if ((accum = (accum * 10) + (c - '0')) > 0xff) return false;
177
61
      empty = false;
178

107
    } else if (c != '.' || !endOctet()) {
179
78
      return false;
180
    }
181
  }
182
5
  return endOctet(true);
183
}
184
185
// Constants for hybi-10 frame format.
186
187
typedef int OpCode;
188
189
const OpCode kOpCodeContinuation = 0x0;
190
const OpCode kOpCodeText = 0x1;
191
const OpCode kOpCodeBinary = 0x2;
192
const OpCode kOpCodeClose = 0x8;
193
const OpCode kOpCodePing = 0x9;
194
const OpCode kOpCodePong = 0xA;
195
196
const unsigned char kFinalBit = 0x80;
197
const unsigned char kReserved1Bit = 0x40;
198
const unsigned char kReserved2Bit = 0x20;
199
const unsigned char kReserved3Bit = 0x10;
200
const unsigned char kOpCodeMask = 0xF;
201
const unsigned char kMaskBit = 0x80;
202
const unsigned char kPayloadLengthMask = 0x7F;
203
204
const size_t kMaxSingleBytePayloadLength = 125;
205
const size_t kTwoBytePayloadLengthField = 126;
206
const size_t kEightBytePayloadLengthField = 127;
207
const size_t kMaskingKeyWidthInBytes = 4;
208
209
2103
static std::vector<char> encode_frame_hybi17(const std::vector<char>& message) {
210
2103
  std::vector<char> frame;
211
2103
  OpCode op_code = kOpCodeText;
212
2103
  frame.push_back(kFinalBit | op_code);
213
2103
  const size_t data_length = message.size();
214
2103
  if (data_length <= kMaxSingleBytePayloadLength) {
215
171
    frame.push_back(static_cast<char>(data_length));
216
1932
  } else if (data_length <= 0xFFFF) {
217
1931
    frame.push_back(kTwoBytePayloadLengthField);
218
1931
    frame.push_back((data_length & 0xFF00) >> 8);
219
1931
    frame.push_back(data_length & 0xFF);
220
  } else {
221
1
    frame.push_back(kEightBytePayloadLengthField);
222
    char extended_payload_length[8];
223
1
    size_t remaining = data_length;
224
    // Fill the length into extended_payload_length in the network byte order.
225
9
    for (int i = 0; i < 8; ++i) {
226
8
      extended_payload_length[7 - i] = remaining & 0xFF;
227
8
      remaining >>= 8;
228
    }
229
2
    frame.insert(frame.end(), extended_payload_length,
230
1
                 extended_payload_length + 8);
231
1
    CHECK_EQ(0, remaining);
232
  }
233
2103
  frame.insert(frame.end(), message.begin(), message.end());
234
2103
  return frame;
235
}
236
237
170
static ws_decode_result decode_frame_hybi17(const std::vector<char>& buffer,
238
                                            bool client_frame,
239
                                            int* bytes_consumed,
240
                                            std::vector<char>* output,
241
                                            bool* compressed) {
242
170
  *bytes_consumed = 0;
243
170
  if (buffer.size() < 2)
244
    return FRAME_INCOMPLETE;
245
246
170
  auto it = buffer.begin();
247
248
170
  unsigned char first_byte = *it++;
249
170
  unsigned char second_byte = *it++;
250
251
170
  bool final = (first_byte & kFinalBit) != 0;
252
170
  bool reserved1 = (first_byte & kReserved1Bit) != 0;
253
170
  bool reserved2 = (first_byte & kReserved2Bit) != 0;
254
170
  bool reserved3 = (first_byte & kReserved3Bit) != 0;
255
170
  int op_code = first_byte & kOpCodeMask;
256
170
  bool masked = (second_byte & kMaskBit) != 0;
257
170
  *compressed = reserved1;
258

170
  if (!final || reserved2 || reserved3)
259
2
    return FRAME_ERROR;  // Only compression extension is supported.
260
261
168
  bool closed = false;
262
168
  switch (op_code) {
263
8
    case kOpCodeClose:
264
8
      closed = true;
265
8
      break;
266
160
    case kOpCodeText:
267
160
      break;
268
    case kOpCodeBinary:        // We don't support binary frames yet.
269
    case kOpCodeContinuation:  // We don't support binary frames yet.
270
    case kOpCodePing:          // We don't support binary frames yet.
271
    case kOpCodePong:          // We don't support binary frames yet.
272
    default:
273
      return FRAME_ERROR;
274
  }
275
276
  // In Hybi-17 spec client MUST mask its frame.
277

168
  if (client_frame && !masked) {
278
1
    return FRAME_ERROR;
279
  }
280
281
167
  uint64_t payload_length64 = second_byte & kPayloadLengthMask;
282
167
  if (payload_length64 > kMaxSingleBytePayloadLength) {
283
    int extended_payload_length_size;
284
34
    if (payload_length64 == kTwoBytePayloadLengthField) {
285
18
      extended_payload_length_size = 2;
286
16
    } else if (payload_length64 == kEightBytePayloadLengthField) {
287
16
      extended_payload_length_size = 8;
288
    } else {
289
      return FRAME_ERROR;
290
    }
291
34
    if ((buffer.end() - it) < extended_payload_length_size)
292
      return FRAME_INCOMPLETE;
293
34
    payload_length64 = 0;
294
198
    for (int i = 0; i < extended_payload_length_size; ++i) {
295
164
      payload_length64 <<= 8;
296
164
      payload_length64 |= static_cast<unsigned char>(*it++);
297
    }
298
  }
299
300
  static const uint64_t max_payload_length = 0x7FFFFFFFFFFFFFFFull;
301
  static const size_t max_length = SIZE_MAX;
302

167
  if (payload_length64 > max_payload_length ||
303
      payload_length64 > max_length - kMaskingKeyWidthInBytes) {
304
    // WebSocket frame length too large.
305
    return FRAME_ERROR;
306
  }
307
167
  size_t payload_length = static_cast<size_t>(payload_length64);
308
309
167
  if (buffer.size() - kMaskingKeyWidthInBytes < payload_length)
310
15
    return FRAME_INCOMPLETE;
311
312
152
  std::vector<char>::const_iterator masking_key = it;
313
152
  std::vector<char>::const_iterator payload = it + kMaskingKeyWidthInBytes;
314
1010666
  for (size_t i = 0; i < payload_length; ++i)  // Unmask the payload.
315
2021028
    output->insert(output->end(),
316
1010514
                   payload[i] ^ masking_key[i % kMaskingKeyWidthInBytes]);
317
318
152
  size_t pos = it + kMaskingKeyWidthInBytes + payload_length - buffer.begin();
319
152
  *bytes_consumed = pos;
320
152
  return closed ? FRAME_CLOSE : FRAME_OK;
321
}
322
323
// WS protocol
324
class WsHandler : public ProtocolHandler {
325
 public:
326
35
  WsHandler(InspectorSocket* inspector, TcpHolder::Pointer tcp)
327
70
            : ProtocolHandler(inspector, std::move(tcp)),
328
              OnCloseSent(&WsHandler::WaitForCloseReply),
329
              OnCloseReceived(&WsHandler::CloseFrameReceived),
330
35
              dispose_(false) { }
331
332
  void AcceptUpgrade(const std::string& accept_key) override { }
333
  void CancelHandshake() override {}
334
335
35
  void OnEof() override {
336
35
    tcp_.reset();
337
35
    if (dispose_)
338
6
      delete this;
339
35
  }
340
341
157
  void OnData(std::vector<char>* data) override {
342
    // 1. Parse.
343
157
    int processed = 0;
344
13
    do {
345
170
      processed = ParseWsFrames(*data);
346
      // 2. Fix the data size & length
347
170
      if (processed > 0) {
348
145
        remove_from_beginning(data, processed);
349
      }
350

170
    } while (processed > 0 && !data->empty());
351
157
  }
352
353
2103
  void Write(const std::vector<char> data) override {
354
4206
    std::vector<char> output = encode_frame_hybi17(data);
355
2103
    WriteRaw(output, WriteRequest::Cleanup);
356
2103
  }
357
358
 protected:
359
35
  void Shutdown() override {
360
35
    if (tcp_) {
361
6
      dispose_ = true;
362
6
      SendClose();
363
    } else {
364
29
      delete this;
365
    }
366
35
  }
367
368
 private:
369
  using Callback = void (WsHandler::*)();
370
371
9
  static void OnCloseFrameWritten(uv_write_t* req, int status) {
372
9
    WriteRequest* wr = WriteRequest::from_write_req(req);
373
9
    WsHandler* handler = static_cast<WsHandler*>(wr->handler);
374
9
    delete wr;
375
9
    Callback cb = handler->OnCloseSent;
376
9
    (handler->*cb)();
377
9
  }
378
379
6
  void WaitForCloseReply() {
380
6
    OnCloseReceived = &WsHandler::OnEof;
381
6
  }
382
383
9
  void SendClose() {
384
9
    WriteRaw(std::vector<char>(CLOSE_FRAME, CLOSE_FRAME + sizeof(CLOSE_FRAME)),
385
             OnCloseFrameWritten);
386
9
  }
387
388
3
  void CloseFrameReceived() {
389
3
    OnCloseSent = &WsHandler::OnEof;
390
3
    SendClose();
391
3
  }
392
393
170
  int ParseWsFrames(const std::vector<char>& buffer) {
394
170
    int bytes_consumed = 0;
395
170
    std::vector<char> output;
396
170
    bool compressed = false;
397
398
170
    ws_decode_result r =  decode_frame_hybi17(buffer,
399
                                              true /* client_frame */,
400
                                              &bytes_consumed, &output,
401
                                              &compressed);
402
    // Compressed frame means client is ignoring the headers and misbehaves
403

170
    if (compressed || r == FRAME_ERROR) {
404
3
      OnEof();
405
3
      bytes_consumed = 0;
406
167
    } else if (r == FRAME_CLOSE) {
407
7
      (this->*OnCloseReceived)();
408
7
      bytes_consumed = 0;
409
160
    } else if (r == FRAME_OK) {
410
145
      delegate()->OnWsFrame(output);
411
    }
412
170
    return bytes_consumed;
413
  }
414
415
416
  Callback OnCloseSent;
417
  Callback OnCloseReceived;
418
  bool dispose_;
419
};
420
421
// HTTP protocol
422
class HttpEvent {
423
 public:
424
86
  HttpEvent(const std::string& path, bool upgrade, bool isGET,
425
            const std::string& ws_key, const std::string& host)
426
86
            : path(path), upgrade(upgrade), isGET(isGET), ws_key(ws_key),
427
86
              host(host) { }
428
429
  std::string path;
430
  bool upgrade;
431
  bool isGET;
432
  std::string ws_key;
433
  std::string host;
434
};
435
436
class HttpHandler : public ProtocolHandler {
437
 public:
438
84
  explicit HttpHandler(InspectorSocket* inspector, TcpHolder::Pointer tcp)
439
168
                       : ProtocolHandler(inspector, std::move(tcp)),
440
84
                         parsing_value_(false) {
441
84
    llhttp_init(&parser_, HTTP_REQUEST, &parser_settings);
442
84
    llhttp_settings_init(&parser_settings);
443
84
    parser_settings.on_header_field = OnHeaderField;
444
84
    parser_settings.on_header_value = OnHeaderValue;
445
84
    parser_settings.on_message_complete = OnMessageComplete;
446
84
    parser_settings.on_url = OnPath;
447
84
  }
448
449
35
  void AcceptUpgrade(const std::string& accept_key) override {
450
    char accept_string[ACCEPT_KEY_LENGTH];
451
35
    generate_accept_string(accept_key, &accept_string);
452
35
    const char accept_ws_prefix[] = "HTTP/1.1 101 Switching Protocols\r\n"
453
                                    "Upgrade: websocket\r\n"
454
                                    "Connection: Upgrade\r\n"
455
                                    "Sec-WebSocket-Accept: ";
456
35
    const char accept_ws_suffix[] = "\r\n\r\n";
457
    std::vector<char> reply(accept_ws_prefix,
458
70
                            accept_ws_prefix + sizeof(accept_ws_prefix) - 1);
459
70
    reply.insert(reply.end(), accept_string,
460
35
                 accept_string + sizeof(accept_string));
461
70
    reply.insert(reply.end(), accept_ws_suffix,
462
35
                 accept_ws_suffix + sizeof(accept_ws_suffix) - 1);
463
35
    if (WriteRaw(reply, WriteRequest::Cleanup) >= 0) {
464
35
      inspector_->SwitchProtocol(new WsHandler(inspector_, std::move(tcp_)));
465
    } else {
466
      tcp_.reset();
467
    }
468
35
  }
469
470
20
  void CancelHandshake() override {
471
20
    const char HANDSHAKE_FAILED_RESPONSE[] =
472
        "HTTP/1.0 400 Bad Request\r\n"
473
        "Content-Type: text/html; charset=UTF-8\r\n\r\n"
474
        "WebSockets request was expected\r\n";
475
20
    WriteRaw(std::vector<char>(HANDSHAKE_FAILED_RESPONSE,
476
             HANDSHAKE_FAILED_RESPONSE + sizeof(HANDSHAKE_FAILED_RESPONSE) - 1),
477
             ThenCloseAndReportFailure);
478
20
  }
479
480
481
29
  void OnEof() override {
482
29
    tcp_.reset();
483
29
  }
484
485
228
  void OnData(std::vector<char>* data) override {
486
    llhttp_errno_t err;
487
228
    err = llhttp_execute(&parser_, data->data(), data->size());
488
489
228
    if (err == HPE_PAUSED_UPGRADE) {
490
39
      err = HPE_OK;
491
39
      llhttp_resume_after_upgrade(&parser_);
492
    }
493
228
    data->clear();
494
228
    if (err != HPE_OK) {
495
2
      CancelHandshake();
496
    }
497
    // Event handling may delete *this
498
228
    std::vector<HttpEvent> events;
499
228
    std::swap(events, events_);
500
302
    for (const HttpEvent& event : events) {
501

86
      if (!IsAllowedHost(event.host) || !event.isGET) {
502
11
        CancelHandshake();
503
12
        return;
504
75
      } else if (!event.upgrade) {
505
37
        delegate()->OnHttpGet(event.host, event.path);
506
38
      } else if (event.ws_key.empty()) {
507
1
        CancelHandshake();
508
1
        return;
509
      } else {
510
37
        delegate()->OnSocketUpgrade(event.host, event.path, event.ws_key);
511
      }
512
    }
513
  }
514
515
63
  void Write(const std::vector<char> data) override {
516
63
    WriteRaw(data, WriteRequest::Cleanup);
517
63
  }
518
519
 protected:
520
84
  void Shutdown() override {
521
84
    delete this;
522
84
  }
523
524
 private:
525
20
  static void ThenCloseAndReportFailure(uv_write_t* req, int status) {
526
20
    ProtocolHandler* handler = WriteRequest::from_write_req(req)->handler;
527
20
    WriteRequest::Cleanup(req, status);
528
20
    handler->inspector()->SwitchProtocol(nullptr);
529
20
  }
530
531
322
  static int OnHeaderValue(llhttp_t* parser, const char* at, size_t length) {
532
322
    HttpHandler* handler = From(parser);
533
322
    handler->parsing_value_ = true;
534
322
    handler->headers_[handler->current_header_].append(at, length);
535
322
    return 0;
536
  }
537
538
317
  static int OnHeaderField(llhttp_t* parser, const char* at, size_t length) {
539
317
    HttpHandler* handler = From(parser);
540
317
    if (handler->parsing_value_) {
541
187
      handler->parsing_value_ = false;
542
187
      handler->current_header_.clear();
543
    }
544
317
    handler->current_header_.append(at, length);
545
317
    return 0;
546
  }
547
548
111
  static int OnPath(llhttp_t* parser, const char* at, size_t length) {
549
111
    HttpHandler* handler = From(parser);
550
111
    handler->path_.append(at, length);
551
111
    return 0;
552
  }
553
554
836
  static HttpHandler* From(llhttp_t* parser) {
555
836
    return node::ContainerOf(&HttpHandler::parser_, parser);
556
  }
557
558
86
  static int OnMessageComplete(llhttp_t* parser) {
559
    // Event needs to be fired after the parser is done.
560
86
    HttpHandler* handler = From(parser);
561
86
    handler->events_.emplace_back(handler->path_,
562
86
                                  parser->upgrade,
563
172
                                  parser->method == HTTP_GET,
564
172
                                  handler->HeaderValue("Sec-WebSocket-Key"),
565
258
                                  handler->HeaderValue("Host"));
566
86
    handler->path_ = "";
567
86
    handler->parsing_value_ = false;
568
86
    handler->headers_.clear();
569
86
    handler->current_header_ = "";
570
86
    return 0;
571
  }
572
573
172
  std::string HeaderValue(const std::string& header) const {
574
172
    bool header_found = false;
575
344
    std::string value;
576
718
    for (const auto& header_value : headers_) {
577
546
      if (node::StringEqualNoCaseN(header_value.first.data(), header.data(),
578
                                   header.length())) {
579
127
        if (header_found)
580
          return "";
581
127
        value = header_value.second;
582
127
        header_found = true;
583
      }
584
    }
585
172
    return value;
586
  }
587
588
86
  bool IsAllowedHost(const std::string& host_with_port) const {
589
86
    std::string host = TrimPort(host_with_port);
590
172
    return host.empty() || IsIPAddress(host)
591

172
           || node::StringEqualNoCase(host.data(), "localhost");
592
  }
593
594
  bool parsing_value_;
595
  llhttp_t parser_;
596
  llhttp_settings_t parser_settings;
597
  std::vector<HttpEvent> events_;
598
  std::string current_header_;
599
  std::map<std::string, std::string> headers_;
600
  std::string path_;
601
};
602
603
}  // namespace
604
605
// Any protocol
606
119
ProtocolHandler::ProtocolHandler(InspectorSocket* inspector,
607
119
                                 TcpHolder::Pointer tcp)
608
119
                                 : inspector_(inspector), tcp_(std::move(tcp)) {
609
119
  CHECK_NOT_NULL(tcp_);
610
119
  tcp_->SetHandler(this);
611
119
}
612
613
2230
int ProtocolHandler::WriteRaw(const std::vector<char>& buffer,
614
                              uv_write_cb write_cb) {
615
2230
  return tcp_->WriteRaw(buffer, write_cb);
616
}
617
618
219
InspectorSocket::Delegate* ProtocolHandler::delegate() {
619
219
  return tcp_->delegate();
620
}
621
622
std::string ProtocolHandler::GetHost() const {
623
  char ip[INET6_ADDRSTRLEN];
624
  sockaddr_storage addr;
625
  int len = sizeof(addr);
626
  int err = uv_tcp_getsockname(tcp_->tcp(),
627
                               reinterpret_cast<struct sockaddr*>(&addr),
628
                               &len);
629
  if (err != 0)
630
    return "";
631
  if (addr.ss_family == AF_INET6) {
632
    const sockaddr_in6* v6 = reinterpret_cast<const sockaddr_in6*>(&addr);
633
    err = uv_ip6_name(v6, ip, sizeof(ip));
634
  } else {
635
    const sockaddr_in* v4 = reinterpret_cast<const sockaddr_in*>(&addr);
636
    err = uv_ip4_name(v4, ip, sizeof(ip));
637
  }
638
  if (err != 0)
639
    return "";
640
  return ip;
641
}
642
643
// RAII uv_tcp_t wrapper
644
84
TcpHolder::TcpHolder(InspectorSocket::DelegatePointer delegate)
645
                     : tcp_(),
646
84
                       delegate_(std::move(delegate)),
647
84
                       handler_(nullptr) { }
648
649
// static
650
84
TcpHolder::Pointer TcpHolder::Accept(
651
    uv_stream_t* server,
652
    InspectorSocket::DelegatePointer delegate) {
653
84
  TcpHolder* result = new TcpHolder(std::move(delegate));
654
84
  uv_stream_t* tcp = reinterpret_cast<uv_stream_t*>(&result->tcp_);
655
84
  int err = uv_tcp_init(server->loop, &result->tcp_);
656
84
  if (err == 0) {
657
84
    err = uv_accept(server, tcp);
658
  }
659
84
  if (err == 0) {
660
84
    err = uv_read_start(tcp, allocate_buffer, OnDataReceivedCb);
661
  }
662
84
  if (err == 0) {
663
84
    return TcpHolder::Pointer(result);
664
  } else {
665
    delete result;
666
    return nullptr;
667
  }
668
}
669
670
119
void TcpHolder::SetHandler(ProtocolHandler* handler) {
671
119
  handler_ = handler;
672
119
}
673
674
2230
int TcpHolder::WriteRaw(const std::vector<char>& buffer, uv_write_cb write_cb) {
675
#if DUMP_WRITES
676
  printf("%s (%ld bytes):\n", __FUNCTION__, buffer.size());
677
  dump_hex(buffer.data(), buffer.size());
678
  printf("\n");
679
#endif
680
681
  // Freed in write_request_cleanup
682
2230
  WriteRequest* wr = new WriteRequest(handler_, buffer);
683
2230
  uv_stream_t* stream = reinterpret_cast<uv_stream_t*>(&tcp_);
684
2230
  int err = uv_write(&wr->req, stream, &wr->buf, 1, write_cb);
685
2230
  if (err < 0)
686
    delete wr;
687
2230
  return err < 0;
688
}
689
690
219
InspectorSocket::Delegate* TcpHolder::delegate() {
691
219
  return delegate_.get();
692
}
693
694
// static
695
84
void TcpHolder::OnClosed(uv_handle_t* handle) {
696
84
  delete From(handle);
697
84
}
698
699
439
void TcpHolder::OnDataReceivedCb(uv_stream_t* tcp, ssize_t nread,
700
                                 const uv_buf_t* buf) {
701
#if DUMP_READS
702
  if (nread >= 0) {
703
    printf("%s (%ld bytes)\n", __FUNCTION__, nread);
704
    dump_hex(buf->base, nread);
705
  } else {
706
    printf("[%s:%d] %s\n", __FUNCTION__, __LINE__, uv_err_name(nread));
707
  }
708
#endif
709
439
  TcpHolder* holder = From(tcp);
710
439
  holder->ReclaimUvBuf(buf, nread);
711

439
  if (nread < 0 || nread == UV_EOF) {
712
54
    holder->handler_->OnEof();
713
  } else {
714
385
    holder->handler_->OnData(&holder->buffer);
715
  }
716
439
}
717
718
// static
719
84
void TcpHolder::DisconnectAndDispose(TcpHolder* holder) {
720
84
  uv_handle_t* handle = reinterpret_cast<uv_handle_t*>(&holder->tcp_);
721
84
  uv_close(handle, OnClosed);
722
84
}
723
724
439
void TcpHolder::ReclaimUvBuf(const uv_buf_t* buf, ssize_t read) {
725
439
  if (read > 0) {
726
385
    buffer.insert(buffer.end(), buf->base, buf->base + read);
727
  }
728
439
  delete[] buf->base;
729
439
}
730
731
InspectorSocket::~InspectorSocket() = default;
732
733
// static
734
119
void InspectorSocket::Shutdown(ProtocolHandler* handler) {
735
119
  handler->Shutdown();
736
119
}
737
738
// static
739
84
InspectorSocket::Pointer InspectorSocket::Accept(uv_stream_t* server,
740
                                                 DelegatePointer delegate) {
741
168
  auto tcp = TcpHolder::Accept(server, std::move(delegate));
742
84
  if (tcp) {
743
84
    InspectorSocket* inspector = new InspectorSocket();
744
84
    inspector->SwitchProtocol(new HttpHandler(inspector, std::move(tcp)));
745
84
    return InspectorSocket::Pointer(inspector);
746
  } else {
747
    return InspectorSocket::Pointer(nullptr);
748
  }
749
}
750
751
35
void InspectorSocket::AcceptUpgrade(const std::string& ws_key) {
752
35
  protocol_handler_->AcceptUpgrade(ws_key);
753
35
}
754
755
6
void InspectorSocket::CancelHandshake() {
756
6
  protocol_handler_->CancelHandshake();
757
6
}
758
759
std::string InspectorSocket::GetHost() {
760
  return protocol_handler_->GetHost();
761
}
762
763
139
void InspectorSocket::SwitchProtocol(ProtocolHandler* handler) {
764
139
  protocol_handler_.reset(std::move(handler));
765
139
}
766
767
2166
void InspectorSocket::Write(const char* data, size_t len) {
768
2166
  protocol_handler_->Write(std::vector<char>(data, data + len));
769
2166
}
770
771
}  // namespace inspector
772
}  // namespace node