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_server.cc Lines: 284 317 89.6 %
Date: 2019-09-13 22:28:55 Branches: 94 134 70.1 %

Line Branch Exec Source
1
#include "inspector_socket_server.h"
2
3
#include "node.h"
4
#include "util-inl.h"
5
#include "uv.h"
6
#include "zlib.h"
7
8
#include <algorithm>
9
#include <map>
10
#include <set>
11
#include <sstream>
12
13
namespace node {
14
namespace inspector {
15
16
// Function is declared in inspector_io.h so the rest of the node does not
17
// depend on inspector_socket_server.h
18
std::string FormatWsAddress(const std::string& host, int port,
19
                            const std::string& target_id,
20
                            bool include_protocol);
21
namespace {
22
23
static const uint8_t PROTOCOL_JSON[] = {
24
  #include "v8_inspector_protocol_json.h"  // NOLINT(build/include_order)
25
};
26
27
42
void Escape(std::string* string) {
28
3255
  for (char& c : *string) {
29

3213
    c = (c == '\"' || c == '\\') ? '_' : c;
30
  }
31
42
}
32
33
87
std::string FormatHostPort(const std::string& host, int port) {
34
  // Host is valid (socket was bound) so colon means it's a v6 IP address
35
87
  bool v6 = host.find(':') != std::string::npos;
36
87
  std::ostringstream url;
37
87
  if (v6) {
38
4
    url << '[';
39
  }
40
87
  url << host;
41
87
  if (v6) {
42
4
    url << ']';
43
  }
44
87
  url << ':' << port;
45
87
  return url.str();
46
}
47
48
129
std::string FormatAddress(const std::string& host,
49
                          const std::string& target_id,
50
                          bool include_protocol) {
51
129
  std::ostringstream url;
52
129
  if (include_protocol)
53
108
    url << "ws://";
54
129
  url << host << '/' << target_id;
55
129
  return url.str();
56
}
57
58
22
std::string MapToString(const std::map<std::string, std::string>& object) {
59
22
  bool first = true;
60
22
  std::ostringstream json;
61
22
  json << "{\n";
62
213
  for (const auto& name_value : object) {
63
191
    if (!first)
64
169
      json << ",\n";
65
191
    first = false;
66
191
    json << "  \"" << name_value.first << "\": \"";
67
191
    json << name_value.second << "\"";
68
  }
69
22
  json << "\n} ";
70
22
  return json.str();
71
}
72
73
21
std::string MapsToString(
74
    const std::vector<std::map<std::string, std::string>>& array) {
75
21
  bool first = true;
76
21
  std::ostringstream json;
77
21
  json << "[ ";
78
42
  for (const auto& object : array) {
79
21
    if (!first)
80
      json << ", ";
81
21
    first = false;
82
21
    json << MapToString(object);
83
  }
84
21
  json << "]\n\n";
85
21
  return json.str();
86
}
87
88
58
const char* MatchPathSegment(const char* path, const char* expected) {
89
58
  size_t len = strlen(expected);
90
58
  if (StringEqualNoCaseN(path, expected, len)) {
91
46
    if (path[len] == '/') return path + len + 1;
92
22
    if (path[len] == '\0') return path + len;
93
  }
94
12
  return nullptr;
95
}
96
97
23
void SendHttpResponse(InspectorSocket* socket,
98
                      const std::string& response,
99
                      int code) {
100
  const char HEADERS[] = "HTTP/1.0 %d OK\r\n"
101
                         "Content-Type: application/json; charset=UTF-8\r\n"
102
                         "Cache-Control: no-cache\r\n"
103
                         "Content-Length: %zu\r\n"
104
23
                         "\r\n";
105
  char header[sizeof(HEADERS) + 20];
106
  int header_len = snprintf(header,
107
                            sizeof(header),
108
                            HEADERS,
109
                            code,
110
23
                            response.size());
111
23
  socket->Write(header, header_len);
112
23
  socket->Write(response.data(), response.size());
113
23
}
114
115
1
void SendVersionResponse(InspectorSocket* socket) {
116
1
  std::map<std::string, std::string> response;
117
1
  response["Browser"] = "node.js/" NODE_VERSION;
118
1
  response["Protocol-Version"] = "1.1";
119
1
  SendHttpResponse(socket, MapToString(response), 200);
120
1
}
121
122
1
void SendHttpNotFound(InspectorSocket* socket) {
123
1
  SendHttpResponse(socket, "", 404);
124
1
}
125
126
void SendProtocolJson(InspectorSocket* socket) {
127
  z_stream strm;
128
  strm.zalloc = Z_NULL;
129
  strm.zfree = Z_NULL;
130
  strm.opaque = Z_NULL;
131
  CHECK_EQ(Z_OK, inflateInit(&strm));
132
  static const size_t kDecompressedSize =
133
      PROTOCOL_JSON[0] * 0x10000u +
134
      PROTOCOL_JSON[1] * 0x100u +
135
      PROTOCOL_JSON[2];
136
  strm.next_in = const_cast<uint8_t*>(PROTOCOL_JSON + 3);
137
  strm.avail_in = sizeof(PROTOCOL_JSON) - 3;
138
  std::string data(kDecompressedSize, '\0');
139
  strm.next_out = reinterpret_cast<Byte*>(&data[0]);
140
  strm.avail_out = data.size();
141
  CHECK_EQ(Z_STREAM_END, inflate(&strm, Z_FINISH));
142
  CHECK_EQ(0, strm.avail_out);
143
  CHECK_EQ(Z_OK, inflateEnd(&strm));
144
  SendHttpResponse(socket, data, 200);
145
}
146
}  // namespace
147
148
87
std::string FormatWsAddress(const std::string& host, int port,
149
                            const std::string& target_id,
150
                            bool include_protocol) {
151
87
  return FormatAddress(FormatHostPort(host, port), target_id, include_protocol);
152
}
153
154
46
class SocketSession {
155
 public:
156
  SocketSession(InspectorSocketServer* server, int id, int server_port);
157
1
  void Close() {
158
1
    ws_socket_.reset();
159
1
  }
160
  void Send(const std::string& message);
161
46
  void Own(InspectorSocket::Pointer ws_socket) {
162
46
    ws_socket_ = std::move(ws_socket);
163
46
  }
164
92
  int id() const { return id_; }
165
  int server_port() {
166
    return server_port_;
167
  }
168
29
  InspectorSocket* ws_socket() {
169
29
    return ws_socket_.get();
170
  }
171
17
  void Accept(const std::string& ws_key) {
172
17
    ws_socket_->AcceptUpgrade(ws_key);
173
17
  }
174
  void Decline() {
175
    ws_socket_->CancelHandshake();
176
  }
177
178
  class Delegate : public InspectorSocket::Delegate {
179
   public:
180
46
    Delegate(InspectorSocketServer* server, int session_id)
181
46
             : server_(server), session_id_(session_id) { }
182
138
    ~Delegate() override {
183
46
      server_->SessionTerminated(session_id_);
184
92
    }
185
    void OnHttpGet(const std::string& host, const std::string& path) override;
186
    void OnSocketUpgrade(const std::string& host, const std::string& path,
187
                         const std::string& ws_key) override;
188
    void OnWsFrame(const std::vector<char>& data) override;
189
190
   private:
191
3
    SocketSession* Session() {
192
3
      return server_->Session(session_id_);
193
    }
194
195
    InspectorSocketServer* server_;
196
    int session_id_;
197
  };
198
199
 private:
200
  const int id_;
201
  InspectorSocket::Pointer ws_socket_;
202
  const int server_port_;
203
};
204
205
class ServerSocket {
206
 public:
207
81
  explicit ServerSocket(InspectorSocketServer* server)
208
81
                        : tcp_socket_(uv_tcp_t()), server_(server) {}
209
  int Listen(sockaddr* addr, uv_loop_t* loop);
210
80
  void Close() {
211
80
    uv_close(reinterpret_cast<uv_handle_t*>(&tcp_socket_), FreeOnCloseCallback);
212
80
  }
213
158
  int port() const { return port_; }
214
215
 private:
216
  template <typename UvHandle>
217
126
  static ServerSocket* FromTcpSocket(UvHandle* socket) {
218
    return node::ContainerOf(&ServerSocket::tcp_socket_,
219
126
                             reinterpret_cast<uv_tcp_t*>(socket));
220
  }
221
  static void SocketConnectedCallback(uv_stream_t* tcp_socket, int status);
222
80
  static void FreeOnCloseCallback(uv_handle_t* tcp_socket_) {
223
80
    delete FromTcpSocket(tcp_socket_);
224
80
  }
225
  int DetectPort();
226
  ~ServerSocket() = default;
227
228
  uv_tcp_t tcp_socket_;
229
  InspectorSocketServer* server_;
230
  int port_ = -1;
231
};
232
233
79
void PrintDebuggerReadyMessage(
234
    const std::string& host,
235
    const std::vector<InspectorSocketServer::ServerSocketPtr>& server_sockets,
236
    const std::vector<std::string>& ids,
237
    bool publish_uid_stderr,
238
    FILE* out) {
239

79
  if (!publish_uid_stderr || out == nullptr) {
240
80
    return;
241
  }
242
158
  for (const auto& server_socket : server_sockets) {
243
160
    for (const std::string& id : ids) {
244
      fprintf(out, "Debugger listening on %s\n",
245
80
              FormatWsAddress(host, server_socket->port(), id, true).c_str());
246
    }
247
  }
248
  fprintf(out, "For help, see: %s\n",
249
78
          "https://nodejs.org/en/docs/inspector");
250
78
  fflush(out);
251
}
252
253
79
InspectorSocketServer::InspectorSocketServer(
254
    std::unique_ptr<SocketServerDelegate> delegate, uv_loop_t* loop,
255
    const std::string& host, int port,
256
    const InspectPublishUid& inspect_publish_uid, FILE* out)
257
    : loop_(loop),
258
79
      delegate_(std::move(delegate)),
259
      host_(host),
260
      port_(port),
261
      inspect_publish_uid_(inspect_publish_uid),
262
      next_session_id_(0),
263
158
      out_(out) {
264
79
  delegate_->AssignServer(this);
265
79
  state_ = ServerState::kNew;
266
79
}
267
268
InspectorSocketServer::~InspectorSocketServer() = default;
269
270
923
SocketSession* InspectorSocketServer::Session(int session_id) {
271
923
  auto it = connected_sessions_.find(session_id);
272
923
  return it == connected_sessions_.end() ? nullptr : it->second.second.get();
273
}
274
275
17
void InspectorSocketServer::SessionStarted(int session_id,
276
                                           const std::string& id,
277
                                           const std::string& ws_key) {
278
17
  SocketSession* session = Session(session_id);
279
17
  if (!TargetExists(id)) {
280
    session->Decline();
281
17
    return;
282
  }
283
17
  connected_sessions_[session_id].first = id;
284
17
  session->Accept(ws_key);
285
17
  delegate_->StartSession(session_id, id);
286
}
287
288
46
void InspectorSocketServer::SessionTerminated(int session_id) {
289
46
  if (Session(session_id) == nullptr) {
290
46
    return;
291
  }
292
46
  bool was_attached = connected_sessions_[session_id].first != "";
293
46
  if (was_attached) {
294
17
    delegate_->EndSession(session_id);
295
  }
296
46
  connected_sessions_.erase(session_id);
297
46
  if (connected_sessions_.empty()) {
298

53
    if (was_attached && state_ == ServerState::kRunning
299

40
        && !server_sockets_.empty()) {
300
      PrintDebuggerReadyMessage(host_,
301
                                server_sockets_,
302
1
                                delegate_->GetTargetIds(),
303
                                inspect_publish_uid_.console,
304
2
                                out_);
305
    }
306
39
    if (state_ == ServerState::kStopped) {
307
13
      delegate_.reset();
308
    }
309
  }
310
}
311
312
26
bool InspectorSocketServer::HandleGetRequest(int session_id,
313
                                             const std::string& host,
314
                                             const std::string& path) {
315
26
  SocketSession* session = Session(session_id);
316
26
  InspectorSocket* socket = session->ws_socket();
317
26
  if (!inspect_publish_uid_.http) {
318
1
    SendHttpNotFound(socket);
319
1
    return true;
320
  }
321
25
  const char* command = MatchPathSegment(path.c_str(), "/json");
322
25
  if (command == nullptr)
323
    return false;
324
325

25
  if (MatchPathSegment(command, "list") || command[0] == '\0') {
326
21
    SendListResponse(socket, host, session);
327
21
    return true;
328
4
  } else if (MatchPathSegment(command, "protocol")) {
329
    SendProtocolJson(socket);
330
    return true;
331
4
  } else if (MatchPathSegment(command, "version")) {
332
1
    SendVersionResponse(socket);
333
1
    return true;
334
  }
335
3
  return false;
336
}
337
338
21
void InspectorSocketServer::SendListResponse(InspectorSocket* socket,
339
                                             const std::string& host,
340
                                             SocketSession* session) {
341
21
  std::vector<std::map<std::string, std::string>> response;
342
42
  for (const std::string& id : delegate_->GetTargetIds()) {
343
21
    response.push_back(std::map<std::string, std::string>());
344
21
    std::map<std::string, std::string>& target_map = response.back();
345
21
    target_map["description"] = "node.js instance";
346
21
    target_map["faviconUrl"] = "https://nodejs.org/static/favicon.ico";
347
21
    target_map["id"] = id;
348
21
    target_map["title"] = delegate_->GetTargetTitle(id);
349
21
    Escape(&target_map["title"]);
350
21
    target_map["type"] = "node";
351
    // This attribute value is a "best effort" URL that is passed as a JSON
352
    // string. It is not guaranteed to resolve to a valid resource.
353
21
    target_map["url"] = delegate_->GetTargetUrl(id);
354
21
    Escape(&target_map["url"]);
355
356
21
    std::string detected_host = host;
357
21
    if (detected_host.empty()) {
358
      detected_host = FormatHostPort(socket->GetHost(),
359
                                     session->server_port());
360
    }
361
42
    std::string formatted_address = FormatAddress(detected_host, id, false);
362
42
    target_map["devtoolsFrontendUrl"] = GetFrontendURL(false,
363
21
                                                       formatted_address);
364
    // The compat URL is for Chrome browsers older than 66.0.3345.0
365
42
    target_map["devtoolsFrontendUrlCompat"] = GetFrontendURL(true,
366
21
                                                             formatted_address);
367
21
    target_map["webSocketDebuggerUrl"] = FormatAddress(detected_host, id, true);
368
42
  }
369
21
  SendHttpResponse(socket, MapsToString(response), 200);
370
21
}
371
372
42
std::string InspectorSocketServer::GetFrontendURL(bool is_compat,
373
    const std::string &formatted_address) {
374
42
  std::ostringstream frontend_url;
375
42
  frontend_url << "chrome-devtools://devtools/bundled/";
376
42
  frontend_url << (is_compat ? "inspector" : "js_app");
377
42
  frontend_url << ".html?experiments=true&v8only=true&ws=";
378
42
  frontend_url << formatted_address;
379
42
  return frontend_url.str();
380
}
381
382
79
bool InspectorSocketServer::Start() {
383
79
  CHECK_NOT_NULL(delegate_);
384
79
  CHECK_EQ(state_, ServerState::kNew);
385
79
  std::unique_ptr<SocketServerDelegate> delegate_holder;
386
  // We will return it if startup is successful
387
79
  delegate_.swap(delegate_holder);
388
  struct addrinfo hints;
389
79
  memset(&hints, 0, sizeof(hints));
390
79
  hints.ai_flags = AI_NUMERICSERV;
391
79
  hints.ai_socktype = SOCK_STREAM;
392
  uv_getaddrinfo_t req;
393
158
  const std::string port_string = std::to_string(port_);
394
  int err = uv_getaddrinfo(loop_, &req, nullptr, host_.c_str(),
395
79
                           port_string.c_str(), &hints);
396
79
  if (err < 0) {
397
    if (out_ != nullptr) {
398
      fprintf(out_, "Unable to resolve \"%s\": %s\n", host_.c_str(),
399
              uv_strerror(err));
400
    }
401
    return false;
402
  }
403
160
  for (addrinfo* address = req.addrinfo; address != nullptr;
404
       address = address->ai_next) {
405
81
    auto server_socket = ServerSocketPtr(new ServerSocket(this));
406
81
    err = server_socket->Listen(address->ai_addr, loop_);
407
81
    if (err == 0)
408
80
      server_sockets_.push_back(std::move(server_socket));
409
81
  }
410
79
  uv_freeaddrinfo(req.addrinfo);
411
412
  // We only show error if we failed to start server on all addresses. We only
413
  // show one error, for the last address.
414
79
  if (server_sockets_.empty()) {
415
1
    if (out_ != nullptr) {
416
      fprintf(out_, "Starting inspector on %s:%d failed: %s\n",
417
1
              host_.c_str(), port_, uv_strerror(err));
418
1
      fflush(out_);
419
    }
420
1
    return false;
421
  }
422
78
  delegate_.swap(delegate_holder);
423
78
  state_ = ServerState::kRunning;
424
  PrintDebuggerReadyMessage(host_,
425
                            server_sockets_,
426
78
                            delegate_->GetTargetIds(),
427
                            inspect_publish_uid_.console,
428
156
                            out_);
429
157
  return true;
430
}
431
432
87
void InspectorSocketServer::Stop() {
433
87
  if (state_ == ServerState::kStopped)
434
97
    return;
435
77
  CHECK_EQ(state_, ServerState::kRunning);
436
77
  state_ = ServerState::kStopped;
437
77
  server_sockets_.clear();
438
77
  if (done())
439
64
    delegate_.reset();
440
}
441
442
14
void InspectorSocketServer::TerminateConnections() {
443
15
  for (const auto& key_value : connected_sessions_)
444
1
    key_value.second.second->Close();
445
14
}
446
447
17
bool InspectorSocketServer::TargetExists(const std::string& id) {
448
17
  const std::vector<std::string>& target_ids = delegate_->GetTargetIds();
449
17
  const auto& found = std::find(target_ids.begin(), target_ids.end(), id);
450
17
  return found != target_ids.end();
451
}
452
453
78
int InspectorSocketServer::Port() const {
454
78
  if (!server_sockets_.empty()) {
455
78
    return server_sockets_[0]->port();
456
  }
457
  return port_;
458
}
459
460
46
void InspectorSocketServer::Accept(int server_port,
461
                                   uv_stream_t* server_socket) {
462
  std::unique_ptr<SocketSession> session(
463
46
      new SocketSession(this, next_session_id_++, server_port));
464
465
  InspectorSocket::DelegatePointer delegate =
466
      InspectorSocket::DelegatePointer(
467
92
          new SocketSession::Delegate(this, session->id()));
468
469
  InspectorSocket::Pointer inspector =
470
92
      InspectorSocket::Accept(server_socket, std::move(delegate));
471
46
  if (inspector) {
472
46
    session->Own(std::move(inspector));
473
46
    connected_sessions_[session->id()].second = std::move(session);
474
46
  }
475
46
}
476
477
831
void InspectorSocketServer::Send(int session_id, const std::string& message) {
478
831
  SocketSession* session = Session(session_id);
479
831
  if (session != nullptr) {
480
831
    session->Send(message);
481
  }
482
831
}
483
484
80
void InspectorSocketServer::CloseServerSocket(ServerSocket* server) {
485
80
  server->Close();
486
80
}
487
488
// InspectorSession tracking
489
46
SocketSession::SocketSession(InspectorSocketServer* server, int id,
490
                             int server_port)
491
46
    : id_(id), server_port_(server_port) {}
492
493
831
void SocketSession::Send(const std::string& message) {
494
831
  ws_socket_->Write(message.data(), message.length());
495
831
}
496
497
26
void SocketSession::Delegate::OnHttpGet(const std::string& host,
498
                                        const std::string& path) {
499
26
  if (!server_->HandleGetRequest(session_id_, host, path))
500
3
    Session()->ws_socket()->CancelHandshake();
501
26
}
502
503
17
void SocketSession::Delegate::OnSocketUpgrade(const std::string& host,
504
                                              const std::string& path,
505
                                              const std::string& ws_key) {
506
17
  std::string id = path.empty() ? path : path.substr(1);
507
17
  server_->SessionStarted(session_id_, id, ws_key);
508
17
}
509
510
122
void SocketSession::Delegate::OnWsFrame(const std::vector<char>& data) {
511
  server_->MessageReceived(session_id_,
512
122
                           std::string(data.data(), data.size()));
513
122
}
514
515
// ServerSocket implementation
516
80
int ServerSocket::DetectPort() {
517
  sockaddr_storage addr;
518
80
  int len = sizeof(addr);
519
  int err = uv_tcp_getsockname(&tcp_socket_,
520
80
                               reinterpret_cast<struct sockaddr*>(&addr), &len);
521
80
  if (err != 0)
522
    return err;
523
  int port;
524
80
  if (addr.ss_family == AF_INET6)
525
6
    port = reinterpret_cast<const sockaddr_in6*>(&addr)->sin6_port;
526
  else
527
74
    port = reinterpret_cast<const sockaddr_in*>(&addr)->sin_port;
528
80
  port_ = ntohs(port);
529
80
  return err;
530
}
531
532
81
int ServerSocket::Listen(sockaddr* addr, uv_loop_t* loop) {
533
81
  uv_tcp_t* server = &tcp_socket_;
534
81
  CHECK_EQ(0, uv_tcp_init(loop, server));
535
81
  int err = uv_tcp_bind(server, addr, 0);
536
81
  if (err == 0) {
537
    // 511 is the value used by a 'net' module by default
538
    err = uv_listen(reinterpret_cast<uv_stream_t*>(server), 511,
539
81
                    ServerSocket::SocketConnectedCallback);
540
  }
541
81
  if (err == 0) {
542
80
    err = DetectPort();
543
  }
544
81
  return err;
545
}
546
547
// static
548
46
void ServerSocket::SocketConnectedCallback(uv_stream_t* tcp_socket,
549
                                           int status) {
550
46
  if (status == 0) {
551
46
    ServerSocket* server_socket = ServerSocket::FromTcpSocket(tcp_socket);
552
    // Memory is freed when the socket closes.
553
46
    server_socket->server_->Accept(server_socket->port_, tcp_socket);
554
  }
555
46
}
556
}  // namespace inspector
557
}  // namespace node