GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/inspector_socket.cc Lines: 351 385 91.2 %
Date: 2020-09-06 22:14:11 Branches: 117 165 70.9 %

Line Branch Exec Source
1
#include "inspector_socket.h"
2
#include "llhttp.h"
3
4
#include "base64.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
418
  static TcpHolder* From(void* handle) {
36
836
    return node::ContainerOf(&TcpHolder::tcp_,
37
836
                             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
75
  ~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
11
  InspectorSocket* inspector() {
66
11
    return inspector_;
67
  }
68
  virtual void Shutdown() = 0;
69
70
 protected:
71
110
  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
1361
class WriteRequest {
108
 public:
109
1361
  WriteRequest(ProtocolHandler* handler, const std::vector<char>& buffer)
110
1361
      : handler(handler)
111
      , storage(buffer)
112
      , req(uv_write_t())
113
1361
      , buf(uv_buf_init(storage.data(), storage.size())) {}
114
115
1372
  static WriteRequest* from_write_req(uv_write_t* req) {
116
1372
    return node::ContainerOf(&WriteRequest::req, req);
117
  }
118
119
1352
  static void Cleanup(uv_write_t* req, int status) {
120
1352
    delete WriteRequest::from_write_req(req);
121
1352
  }
122
123
  ProtocolHandler* const handler;
124
  std::vector<char> storage;
125
  uv_write_t req;
126
  uv_buf_t buf;
127
};
128
129
343
void allocate_buffer(uv_handle_t* stream, size_t len, uv_buf_t* buf) {
130
343
  *buf = uv_buf_init(new char[len], len);
131
343
}
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
  SHA1(reinterpret_cast<const unsigned char*>(&input[0]), input.size(),
150
35
       reinterpret_cast<unsigned char*>(hash));
151
35
  node::base64_encode(hash, sizeof(hash), *buffer, sizeof(*buffer));
152
35
}
153
154
77
static std::string TrimPort(const std::string& host) {
155
77
  size_t last_colon_pos = host.rfind(':');
156
77
  if (last_colon_pos == std::string::npos)
157
    return host;
158
77
  size_t bracket = host.rfind(']');
159

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


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

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

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

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

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

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

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

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

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