GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: tcp_wrap.cc Lines: 199 209 95.2 %
Date: 2022-06-23 04:15:39 Branches: 58 110 52.7 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "tcp_wrap.h"
23
24
#include "connect_wrap.h"
25
#include "connection_wrap.h"
26
#include "env-inl.h"
27
#include "handle_wrap.h"
28
#include "node_buffer.h"
29
#include "node_external_reference.h"
30
#include "node_internals.h"
31
#include "stream_base-inl.h"
32
#include "stream_wrap.h"
33
#include "util-inl.h"
34
35
#include <cstdlib>
36
37
38
namespace node {
39
40
using v8::Boolean;
41
using v8::Context;
42
using v8::EscapableHandleScope;
43
using v8::Function;
44
using v8::FunctionCallbackInfo;
45
using v8::FunctionTemplate;
46
using v8::Int32;
47
using v8::Integer;
48
using v8::Local;
49
using v8::MaybeLocal;
50
using v8::Object;
51
using v8::String;
52
using v8::Uint32;
53
using v8::Value;
54
55
5177
MaybeLocal<Object> TCPWrap::Instantiate(Environment* env,
56
                                        AsyncWrap* parent,
57
                                        TCPWrap::SocketType type) {
58
5177
  EscapableHandleScope handle_scope(env->isolate());
59
5177
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(parent);
60
10354
  CHECK_EQ(env->tcp_constructor_template().IsEmpty(), false);
61
5177
  Local<Function> constructor = env->tcp_constructor_template()
62
5177
                                    ->GetFunction(env->context())
63
5177
                                    .ToLocalChecked();
64
5177
  CHECK_EQ(constructor.IsEmpty(), false);
65
10354
  Local<Value> type_value = Int32::New(env->isolate(), type);
66
  return handle_scope.EscapeMaybe(
67
10354
      constructor->NewInstance(env->context(), 1, &type_value));
68
}
69
70
71
6390
void TCPWrap::Initialize(Local<Object> target,
72
                         Local<Value> unused,
73
                         Local<Context> context,
74
                         void* priv) {
75
6390
  Environment* env = Environment::GetCurrent(context);
76
77
6390
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
78
12780
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
79
80
  // Init properties
81
25560
  t->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "reading"),
82
                             Boolean::New(env->isolate(), false));
83
25560
  t->InstanceTemplate()->Set(env->owner_symbol(), Null(env->isolate()));
84
25560
  t->InstanceTemplate()->Set(env->onconnection_string(), Null(env->isolate()));
85
86
6390
  t->Inherit(LibuvStreamWrap::GetConstructorTemplate(env));
87
88
6390
  env->SetProtoMethod(t, "open", Open);
89
6390
  env->SetProtoMethod(t, "bind", Bind);
90
6390
  env->SetProtoMethod(t, "listen", Listen);
91
6390
  env->SetProtoMethod(t, "connect", Connect);
92
6390
  env->SetProtoMethod(t, "bind6", Bind6);
93
6390
  env->SetProtoMethod(t, "connect6", Connect6);
94
6390
  env->SetProtoMethod(t, "getsockname",
95
                      GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>);
96
6390
  env->SetProtoMethod(t, "getpeername",
97
                      GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>);
98
6390
  env->SetProtoMethod(t, "setNoDelay", SetNoDelay);
99
6390
  env->SetProtoMethod(t, "setKeepAlive", SetKeepAlive);
100
6390
  env->SetProtoMethod(t, "reset", Reset);
101
102
#ifdef _WIN32
103
  env->SetProtoMethod(t, "setSimultaneousAccepts", SetSimultaneousAccepts);
104
#endif
105
106
6390
  env->SetConstructorFunction(target, "TCP", t);
107
6390
  env->set_tcp_constructor_template(t);
108
109
  // Create FunctionTemplate for TCPConnectWrap.
110
  Local<FunctionTemplate> cwt =
111
6390
      BaseObject::MakeLazilyInitializedJSTemplate(env);
112
6390
  cwt->Inherit(AsyncWrap::GetConstructorTemplate(env));
113
6390
  env->SetConstructorFunction(target, "TCPConnectWrap", cwt);
114
115
  // Define constants
116
6390
  Local<Object> constants = Object::New(env->isolate());
117
19170
  NODE_DEFINE_CONSTANT(constants, SOCKET);
118
19170
  NODE_DEFINE_CONSTANT(constants, SERVER);
119
19170
  NODE_DEFINE_CONSTANT(constants, UV_TCP_IPV6ONLY);
120
6390
  target->Set(context,
121
              env->constants_string(),
122
12780
              constants).Check();
123
6390
}
124
125
5143
void TCPWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
126
5143
  registry->Register(New);
127
5143
  registry->Register(Open);
128
5143
  registry->Register(Bind);
129
5143
  registry->Register(Listen);
130
5143
  registry->Register(Connect);
131
5143
  registry->Register(Bind6);
132
5143
  registry->Register(Connect6);
133
134
5143
  registry->Register(GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>);
135
5143
  registry->Register(GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>);
136
5143
  registry->Register(SetNoDelay);
137
5143
  registry->Register(SetKeepAlive);
138
5143
  registry->Register(Reset);
139
#ifdef _WIN32
140
  registry->Register(SetSimultaneousAccepts);
141
#endif
142
5143
}
143
144
13059
void TCPWrap::New(const FunctionCallbackInfo<Value>& args) {
145
  // This constructor should not be exposed to public javascript.
146
  // Therefore we assert that we are not trying to call this as a
147
  // normal function.
148
13059
  CHECK(args.IsConstructCall());
149
13059
  CHECK(args[0]->IsInt32());
150
13059
  Environment* env = Environment::GetCurrent(args);
151
152
26118
  int type_value = args[0].As<Int32>()->Value();
153
13059
  TCPWrap::SocketType type = static_cast<TCPWrap::SocketType>(type_value);
154
155
  ProviderType provider;
156
13059
  switch (type) {
157
11293
    case SOCKET:
158
11293
      provider = PROVIDER_TCPWRAP;
159
11293
      break;
160
1766
    case SERVER:
161
1766
      provider = PROVIDER_TCPSERVERWRAP;
162
1766
      break;
163
    default:
164
      UNREACHABLE();
165
  }
166
167
13059
  new TCPWrap(env, args.This(), provider);
168
13059
}
169
170
171
13059
TCPWrap::TCPWrap(Environment* env, Local<Object> object, ProviderType provider)
172
13059
    : ConnectionWrap(env, object, provider) {
173
13059
  int r = uv_tcp_init(env->event_loop(), &handle_);
174
13059
  CHECK_EQ(r, 0);  // How do we proxy this error up to javascript?
175
                   // Suggestion: uv_tcp_init() returns void.
176
13059
}
177
178
179
5953
void TCPWrap::SetNoDelay(const FunctionCallbackInfo<Value>& args) {
180
  TCPWrap* wrap;
181
5953
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
182
                          args.Holder(),
183
                          args.GetReturnValue().Set(UV_EBADF));
184
5953
  int enable = static_cast<int>(args[0]->IsTrue());
185
5953
  int err = uv_tcp_nodelay(&wrap->handle_, enable);
186
11906
  args.GetReturnValue().Set(err);
187
}
188
189
190
163
void TCPWrap::SetKeepAlive(const FunctionCallbackInfo<Value>& args) {
191
  TCPWrap* wrap;
192
163
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
193
                          args.Holder(),
194
                          args.GetReturnValue().Set(UV_EBADF));
195
163
  Environment* env = wrap->env();
196
  int enable;
197
326
  if (!args[0]->Int32Value(env->context()).To(&enable)) return;
198
326
  unsigned int delay = static_cast<unsigned int>(args[1].As<Uint32>()->Value());
199
163
  int err = uv_tcp_keepalive(&wrap->handle_, enable, delay);
200
326
  args.GetReturnValue().Set(err);
201
}
202
203
204
#ifdef _WIN32
205
void TCPWrap::SetSimultaneousAccepts(const FunctionCallbackInfo<Value>& args) {
206
  TCPWrap* wrap;
207
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
208
                          args.Holder(),
209
                          args.GetReturnValue().Set(UV_EBADF));
210
  bool enable = args[0]->IsTrue();
211
  int err = uv_tcp_simultaneous_accepts(&wrap->handle_, enable);
212
  args.GetReturnValue().Set(err);
213
}
214
#endif
215
216
217
2
void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
218
  TCPWrap* wrap;
219
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
220
                          args.Holder(),
221
                          args.GetReturnValue().Set(UV_EBADF));
222
  int64_t val;
223
4
  if (!args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val))
224
    return;
225
2
  int fd = static_cast<int>(val);
226
2
  int err = uv_tcp_open(&wrap->handle_, fd);
227
228
2
  if (err == 0)
229
2
    wrap->set_fd(fd);
230
231
4
  args.GetReturnValue().Set(err);
232
}
233
234
template <typename T>
235
3578
void TCPWrap::Bind(
236
    const FunctionCallbackInfo<Value>& args,
237
    int family,
238
    std::function<int(const char* ip_address, int port, T* addr)> uv_ip_addr) {
239
  TCPWrap* wrap;
240

1789
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
241
                          args.Holder(),
242
                          args.GetReturnValue().Set(UV_EBADF));
243
1789
  Environment* env = wrap->env();
244
1789
  node::Utf8Value ip_address(env->isolate(), args[0]);
245
  int port;
246

1789
  unsigned int flags = 0;
247

3578
  if (!args[1]->Int32Value(env->context()).To(&port)) return;
248

3447
  if (family == AF_INET6 &&
249


5105
      !args[2]->Uint32Value(env->context()).To(&flags)) {
250
    return;
251
  }
252
253
  T addr;
254
1789
  int err = uv_ip_addr(*ip_address, port, &addr);
255
256

1789
  if (err == 0) {
257
1787
    err = uv_tcp_bind(&wrap->handle_,
258
                      reinterpret_cast<const sockaddr*>(&addr),
259
                      flags);
260
  }
261
3578
  args.GetReturnValue().Set(err);
262
}
263
264
131
void TCPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
265
131
  Bind<sockaddr_in>(args, AF_INET, uv_ip4_addr);
266
131
}
267
268
269
1658
void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
270
1658
  Bind<sockaddr_in6>(args, AF_INET6, uv_ip6_addr);
271
1658
}
272
273
274
1772
void TCPWrap::Listen(const FunctionCallbackInfo<Value>& args) {
275
  TCPWrap* wrap;
276
1772
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
277
                          args.Holder(),
278
                          args.GetReturnValue().Set(UV_EBADF));
279
1772
  Environment* env = wrap->env();
280
  int backlog;
281
3544
  if (!args[0]->Int32Value(env->context()).To(&backlog)) return;
282
1772
  int err = uv_listen(reinterpret_cast<uv_stream_t*>(&wrap->handle_),
283
                      backlog,
284
                      OnConnection);
285
3544
  args.GetReturnValue().Set(err);
286
}
287
288
289
694
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args) {
290
694
  CHECK(args[2]->IsUint32());
291
  // explicit cast to fit to libuv's type expectation
292
1388
  int port = static_cast<int>(args[2].As<Uint32>()->Value());
293
694
  Connect<sockaddr_in>(args,
294
694
                       [port](const char* ip_address, sockaddr_in* addr) {
295
694
      return uv_ip4_addr(ip_address, port, addr);
296
  });
297
694
}
298
299
300
4922
void TCPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
301
4922
  Environment* env = Environment::GetCurrent(args);
302
4922
  CHECK(args[2]->IsUint32());
303
  int port;
304
9844
  if (!args[2]->Int32Value(env->context()).To(&port)) return;
305
4922
  Connect<sockaddr_in6>(args,
306
4922
                        [port](const char* ip_address, sockaddr_in6* addr) {
307
4922
      return uv_ip6_addr(ip_address, port, addr);
308
  });
309
}
310
311
template <typename T>
312
11232
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args,
313
    std::function<int(const char* ip_address, T* addr)> uv_ip_addr) {
314
11232
  Environment* env = Environment::GetCurrent(args);
315
316
  TCPWrap* wrap;
317
11232
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
318
                          args.Holder(),
319
                          args.GetReturnValue().Set(UV_EBADF));
320
321
11232
  CHECK(args[0]->IsObject());
322
22464
  CHECK(args[1]->IsString());
323
324
22464
  Local<Object> req_wrap_obj = args[0].As<Object>();
325
11232
  node::Utf8Value ip_address(env->isolate(), args[1]);
326
327
  T addr;
328
11232
  int err = uv_ip_addr(*ip_address, &addr);
329
330
11232
  if (err == 0) {
331
22464
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap);
332
22464
    ConnectWrap* req_wrap =
333
11232
        new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_TCPCONNECTWRAP);
334
22464
    err = req_wrap->Dispatch(uv_tcp_connect,
335
11232
                             &wrap->handle_,
336
                             reinterpret_cast<const sockaddr*>(&addr),
337
                             AfterConnect);
338
11232
    if (err)
339
      delete req_wrap;
340
  }
341
342
22464
  args.GetReturnValue().Set(err);
343
}
344
5
void TCPWrap::Reset(const FunctionCallbackInfo<Value>& args) {
345
  TCPWrap* wrap;
346
5
  ASSIGN_OR_RETURN_UNWRAP(
347
      &wrap, args.Holder(), args.GetReturnValue().Set(UV_EBADF));
348
349
10
  int err = wrap->Reset(args[0]);
350
351
10
  args.GetReturnValue().Set(err);
352
}
353
354
5
int TCPWrap::Reset(Local<Value> close_callback) {
355
5
  if (state_ != kInitialized) return 0;
356
357
5
  int err = uv_tcp_close_reset(&handle_, OnClose);
358
5
  state_ = kClosing;
359

15
  if (!err & !close_callback.IsEmpty() && close_callback->IsFunction() &&
360
5
      !persistent().IsEmpty()) {
361
5
    object()
362
15
        ->Set(env()->context(), env()->handle_onclose_symbol(), close_callback)
363
        .Check();
364
  }
365
5
  return err;
366
}
367
368
// also used by udp_wrap.cc
369
4866
MaybeLocal<Object> AddressToJS(Environment* env,
370
                               const sockaddr* addr,
371
                               Local<Object> info) {
372
4866
  EscapableHandleScope scope(env->isolate());
373
  char ip[INET6_ADDRSTRLEN + UV_IF_NAMESIZE];
374
  const sockaddr_in* a4;
375
  const sockaddr_in6* a6;
376
377
  int port;
378
379
4866
  if (info.IsEmpty())
380
390
    info = Object::New(env->isolate());
381
382
4866
  switch (addr->sa_family) {
383
4217
  case AF_INET6:
384
4217
    a6 = reinterpret_cast<const sockaddr_in6*>(addr);
385
4217
    uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
386
    // Add an interface identifier to a link local address.
387

4217
    if (IN6_IS_ADDR_LINKLOCAL(&a6->sin6_addr) && a6->sin6_scope_id > 0) {
388
2
      const size_t addrlen = strlen(ip);
389
2
      CHECK_LT(addrlen, sizeof(ip));
390
2
      ip[addrlen] = '%';
391
2
      size_t scopeidlen = sizeof(ip) - addrlen - 1;
392
2
      CHECK_GE(scopeidlen, UV_IF_NAMESIZE);
393
2
      const int r = uv_if_indextoiid(a6->sin6_scope_id,
394
2
                                     ip + addrlen + 1,
395
                                     &scopeidlen);
396
2
      if (r) {
397
        env->ThrowUVException(r, "uv_if_indextoiid");
398
        return {};
399
      }
400
    }
401
4217
    port = ntohs(a6->sin6_port);
402
4217
    info->Set(env->context(),
403
              env->address_string(),
404
16868
              OneByteString(env->isolate(), ip)).Check();
405
16868
    info->Set(env->context(), env->family_string(), env->ipv6_string()).Check();
406
4217
    info->Set(env->context(),
407
              env->port_string(),
408
12651
              Integer::New(env->isolate(), port)).Check();
409
4217
    break;
410
411
649
  case AF_INET:
412
649
    a4 = reinterpret_cast<const sockaddr_in*>(addr);
413
649
    uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
414
649
    port = ntohs(a4->sin_port);
415
649
    info->Set(env->context(),
416
              env->address_string(),
417
2596
              OneByteString(env->isolate(), ip)).Check();
418
2596
    info->Set(env->context(), env->family_string(), env->ipv4_string()).Check();
419
649
    info->Set(env->context(),
420
              env->port_string(),
421
1947
              Integer::New(env->isolate(), port)).Check();
422
649
    break;
423
424
  default:
425
    info->Set(env->context(),
426
              env->address_string(),
427
              String::Empty(env->isolate())).Check();
428
  }
429
430
4866
  return scope.Escape(info);
431
}
432
433
434
}  // namespace node
435
436
5201
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tcp_wrap, node::TCPWrap::Initialize)
437
5143
NODE_MODULE_EXTERNAL_REFERENCE(tcp_wrap,
438
                               node::TCPWrap::RegisterExternalReferences)