GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: tcp_wrap.cc Lines: 201 211 95.3 %
Date: 2022-05-31 04:15:47 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
5173
MaybeLocal<Object> TCPWrap::Instantiate(Environment* env,
56
                                        AsyncWrap* parent,
57
                                        TCPWrap::SocketType type) {
58
5173
  EscapableHandleScope handle_scope(env->isolate());
59
5173
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(parent);
60
10346
  CHECK_EQ(env->tcp_constructor_template().IsEmpty(), false);
61
5173
  Local<Function> constructor = env->tcp_constructor_template()
62
5173
                                    ->GetFunction(env->context())
63
5173
                                    .ToLocalChecked();
64
5173
  CHECK_EQ(constructor.IsEmpty(), false);
65
10346
  Local<Value> type_value = Int32::New(env->isolate(), type);
66
  return handle_scope.EscapeMaybe(
67
10346
      constructor->NewInstance(env->context(), 1, &type_value));
68
}
69
70
71
6005
void TCPWrap::Initialize(Local<Object> target,
72
                         Local<Value> unused,
73
                         Local<Context> context,
74
                         void* priv) {
75
6005
  Environment* env = Environment::GetCurrent(context);
76
77
6005
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
78
12010
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
79
80
  // Init properties
81
24020
  t->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "reading"),
82
                             Boolean::New(env->isolate(), false));
83
24020
  t->InstanceTemplate()->Set(env->owner_symbol(), Null(env->isolate()));
84
24020
  t->InstanceTemplate()->Set(env->onconnection_string(), Null(env->isolate()));
85
86
6005
  t->Inherit(LibuvStreamWrap::GetConstructorTemplate(env));
87
88
6005
  env->SetProtoMethod(t, "open", Open);
89
6005
  env->SetProtoMethod(t, "bind", Bind);
90
6005
  env->SetProtoMethod(t, "listen", Listen);
91
6005
  env->SetProtoMethod(t, "connect", Connect);
92
6005
  env->SetProtoMethod(t, "bind6", Bind6);
93
6005
  env->SetProtoMethod(t, "connect6", Connect6);
94
6005
  env->SetProtoMethod(t, "getsockname",
95
                      GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>);
96
6005
  env->SetProtoMethod(t, "getpeername",
97
                      GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>);
98
6005
  env->SetProtoMethod(t, "setNoDelay", SetNoDelay);
99
6005
  env->SetProtoMethod(t, "setKeepAlive", SetKeepAlive);
100
6005
  env->SetProtoMethod(t, "reset", Reset);
101
102
#ifdef _WIN32
103
  env->SetProtoMethod(t, "setSimultaneousAccepts", SetSimultaneousAccepts);
104
#endif
105
106
6005
  env->SetConstructorFunction(target, "TCP", t);
107
6005
  env->set_tcp_constructor_template(t);
108
109
  // Create FunctionTemplate for TCPConnectWrap.
110
  Local<FunctionTemplate> cwt =
111
6005
      BaseObject::MakeLazilyInitializedJSTemplate(env);
112
6005
  cwt->Inherit(AsyncWrap::GetConstructorTemplate(env));
113
6005
  env->SetConstructorFunction(target, "TCPConnectWrap", cwt);
114
115
  // Define constants
116
6005
  Local<Object> constants = Object::New(env->isolate());
117
18015
  NODE_DEFINE_CONSTANT(constants, SOCKET);
118
18015
  NODE_DEFINE_CONSTANT(constants, SERVER);
119
18015
  NODE_DEFINE_CONSTANT(constants, UV_TCP_IPV6ONLY);
120
6005
  target->Set(context,
121
              env->constants_string(),
122
12010
              constants).Check();
123
6005
}
124
125
5201
void TCPWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
126
5201
  registry->Register(New);
127
5201
  registry->Register(Open);
128
5201
  registry->Register(Bind);
129
5201
  registry->Register(Listen);
130
5201
  registry->Register(Connect);
131
5201
  registry->Register(Bind6);
132
5201
  registry->Register(Connect6);
133
134
5201
  registry->Register(GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>);
135
5201
  registry->Register(GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>);
136
5201
  registry->Register(SetNoDelay);
137
5201
  registry->Register(SetKeepAlive);
138
5201
  registry->Register(Reset);
139
#ifdef _WIN32
140
  registry->Register(SetSimultaneousAccepts);
141
#endif
142
5201
}
143
144
13048
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
13048
  CHECK(args.IsConstructCall());
149
13048
  CHECK(args[0]->IsInt32());
150
13048
  Environment* env = Environment::GetCurrent(args);
151
152
26096
  int type_value = args[0].As<Int32>()->Value();
153
13048
  TCPWrap::SocketType type = static_cast<TCPWrap::SocketType>(type_value);
154
155
  ProviderType provider;
156
13048
  switch (type) {
157
11285
    case SOCKET:
158
11285
      provider = PROVIDER_TCPWRAP;
159
11285
      break;
160
1763
    case SERVER:
161
1763
      provider = PROVIDER_TCPSERVERWRAP;
162
1763
      break;
163
    default:
164
      UNREACHABLE();
165
  }
166
167
13048
  new TCPWrap(env, args.This(), provider);
168
13048
}
169
170
171
13048
TCPWrap::TCPWrap(Environment* env, Local<Object> object, ProviderType provider)
172
13048
    : ConnectionWrap(env, object, provider) {
173
13048
  int r = uv_tcp_init(env->event_loop(), &handle_);
174
13048
  CHECK_EQ(r, 0);  // How do we proxy this error up to javascript?
175
                   // Suggestion: uv_tcp_init() returns void.
176
13048
}
177
178
179
5948
void TCPWrap::SetNoDelay(const FunctionCallbackInfo<Value>& args) {
180
  TCPWrap* wrap;
181
5948
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
182
                          args.Holder(),
183
                          args.GetReturnValue().Set(UV_EBADF));
184
5948
  int enable = static_cast<int>(args[0]->IsTrue());
185
5948
  int err = uv_tcp_nodelay(&wrap->handle_, enable);
186
11896
  args.GetReturnValue().Set(err);
187
}
188
189
190
161
void TCPWrap::SetKeepAlive(const FunctionCallbackInfo<Value>& args) {
191
  TCPWrap* wrap;
192
161
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
193
                          args.Holder(),
194
                          args.GetReturnValue().Set(UV_EBADF));
195
161
  Environment* env = wrap->env();
196
  int enable;
197
322
  if (!args[0]->Int32Value(env->context()).To(&enable)) return;
198
322
  unsigned int delay = static_cast<unsigned int>(args[1].As<Uint32>()->Value());
199
161
  int err = uv_tcp_keepalive(&wrap->handle_, enable, delay);
200
322
  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
3572
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

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

1786
  unsigned int flags = 0;
247

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

3441
  if (family == AF_INET6 &&
249


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

1786
  if (err == 0) {
257
1784
    err = uv_tcp_bind(&wrap->handle_,
258
                      reinterpret_cast<const sockaddr*>(&addr),
259
                      flags);
260
  }
261
3572
  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
1655
void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
270
1655
  Bind<sockaddr_in6>(args, AF_INET6, uv_ip6_addr);
271
1655
}
272
273
274
1769
void TCPWrap::Listen(const FunctionCallbackInfo<Value>& args) {
275
  TCPWrap* wrap;
276
1769
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
277
                          args.Holder(),
278
                          args.GetReturnValue().Set(UV_EBADF));
279
1769
  Environment* env = wrap->env();
280
  int backlog;
281
3538
  if (!args[0]->Int32Value(env->context()).To(&backlog)) return;
282
1769
  int err = uv_listen(reinterpret_cast<uv_stream_t*>(&wrap->handle_),
283
                      backlog,
284
                      OnConnection);
285
3538
  args.GetReturnValue().Set(err);
286
}
287
288
289
693
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args) {
290
693
  CHECK(args[2]->IsUint32());
291
  // explicit cast to fit to libuv's type expectation
292
1386
  int port = static_cast<int>(args[2].As<Uint32>()->Value());
293
693
  Connect<sockaddr_in>(args,
294
693
                       [port](const char* ip_address, sockaddr_in* addr) {
295
693
      return uv_ip4_addr(ip_address, port, addr);
296
  });
297
693
}
298
299
300
4919
void TCPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
301
4919
  Environment* env = Environment::GetCurrent(args);
302
4919
  CHECK(args[2]->IsUint32());
303
  int port;
304
9838
  if (!args[2]->Int32Value(env->context()).To(&port)) return;
305
4919
  Connect<sockaddr_in6>(args,
306
4919
                        [port](const char* ip_address, sockaddr_in6* addr) {
307
4919
      return uv_ip6_addr(ip_address, port, addr);
308
  });
309
}
310
311
template <typename T>
312
11224
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args,
313
    std::function<int(const char* ip_address, T* addr)> uv_ip_addr) {
314
11224
  Environment* env = Environment::GetCurrent(args);
315
316
  TCPWrap* wrap;
317
11224
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
318
                          args.Holder(),
319
                          args.GetReturnValue().Set(UV_EBADF));
320
321
11224
  CHECK(args[0]->IsObject());
322
22448
  CHECK(args[1]->IsString());
323
324
22448
  Local<Object> req_wrap_obj = args[0].As<Object>();
325
11224
  node::Utf8Value ip_address(env->isolate(), args[1]);
326
327
  T addr;
328
11224
  int err = uv_ip_addr(*ip_address, &addr);
329
330
11224
  if (err == 0) {
331
22448
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap);
332
22448
    ConnectWrap* req_wrap =
333
11224
        new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_TCPCONNECTWRAP);
334
22448
    err = req_wrap->Dispatch(uv_tcp_connect,
335
11224
                             &wrap->handle_,
336
                             reinterpret_cast<const sockaddr*>(&addr),
337
                             AfterConnect);
338
11224
    if (err)
339
      delete req_wrap;
340
  }
341
342
22448
  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
4889
MaybeLocal<Object> AddressToJS(Environment* env,
370
                               const sockaddr* addr,
371
                               Local<Object> info) {
372
4889
  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
4889
  if (info.IsEmpty())
380
416
    info = Object::New(env->isolate());
381
382
4889
  switch (addr->sa_family) {
383
4208
  case AF_INET6:
384
4208
    a6 = reinterpret_cast<const sockaddr_in6*>(addr);
385
4208
    uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
386
    // Add an interface identifier to a link local address.
387

4208
    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
4208
    port = ntohs(a6->sin6_port);
402
4208
    info->Set(env->context(),
403
              env->address_string(),
404
16832
              OneByteString(env->isolate(), ip)).Check();
405
4208
    info->Set(env->context(),
406
              env->family_string(),
407
16832
              Integer::New(env->isolate(), 6)).Check();
408
4208
    info->Set(env->context(),
409
              env->port_string(),
410
12624
              Integer::New(env->isolate(), port)).Check();
411
4208
    break;
412
413
681
  case AF_INET:
414
681
    a4 = reinterpret_cast<const sockaddr_in*>(addr);
415
681
    uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
416
681
    port = ntohs(a4->sin_port);
417
681
    info->Set(env->context(),
418
              env->address_string(),
419
2724
              OneByteString(env->isolate(), ip)).Check();
420
681
    info->Set(env->context(),
421
              env->family_string(),
422
2724
              Integer::New(env->isolate(), 4)).Check();
423
681
    info->Set(env->context(),
424
              env->port_string(),
425
2043
              Integer::New(env->isolate(), port)).Check();
426
681
    break;
427
428
  default:
429
    info->Set(env->context(),
430
              env->address_string(),
431
              String::Empty(env->isolate())).Check();
432
  }
433
434
4889
  return scope.Escape(info);
435
}
436
437
438
}  // namespace node
439
440
5269
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tcp_wrap, node::TCPWrap::Initialize)
441
5201
NODE_MODULE_EXTERNAL_REFERENCE(tcp_wrap,
442
                               node::TCPWrap::RegisterExternalReferences)