GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: tcp_wrap.cc Lines: 186 196 94.9 %
Date: 2022-04-03 04:14:58 Branches: 51 96 53.1 %

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
5510
MaybeLocal<Object> TCPWrap::Instantiate(Environment* env,
56
                                        AsyncWrap* parent,
57
                                        TCPWrap::SocketType type) {
58
5510
  EscapableHandleScope handle_scope(env->isolate());
59
5510
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(parent);
60
11020
  CHECK_EQ(env->tcp_constructor_template().IsEmpty(), false);
61
5510
  Local<Function> constructor = env->tcp_constructor_template()
62
5510
                                    ->GetFunction(env->context())
63
5510
                                    .ToLocalChecked();
64
5510
  CHECK_EQ(constructor.IsEmpty(), false);
65
11020
  Local<Value> type_value = Int32::New(env->isolate(), type);
66
  return handle_scope.EscapeMaybe(
67
11020
      constructor->NewInstance(env->context(), 1, &type_value));
68
}
69
70
71
5558
void TCPWrap::Initialize(Local<Object> target,
72
                         Local<Value> unused,
73
                         Local<Context> context,
74
                         void* priv) {
75
5558
  Environment* env = Environment::GetCurrent(context);
76
77
5558
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
78
11116
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
79
80
  // Init properties
81
22232
  t->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "reading"),
82
                             Boolean::New(env->isolate(), false));
83
22232
  t->InstanceTemplate()->Set(env->owner_symbol(), Null(env->isolate()));
84
22232
  t->InstanceTemplate()->Set(env->onconnection_string(), Null(env->isolate()));
85
86
5558
  t->Inherit(LibuvStreamWrap::GetConstructorTemplate(env));
87
88
5558
  env->SetProtoMethod(t, "open", Open);
89
5558
  env->SetProtoMethod(t, "bind", Bind);
90
5558
  env->SetProtoMethod(t, "listen", Listen);
91
5558
  env->SetProtoMethod(t, "connect", Connect);
92
5558
  env->SetProtoMethod(t, "bind6", Bind6);
93
5558
  env->SetProtoMethod(t, "connect6", Connect6);
94
5558
  env->SetProtoMethod(t, "getsockname",
95
                      GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>);
96
5558
  env->SetProtoMethod(t, "getpeername",
97
                      GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>);
98
5558
  env->SetProtoMethod(t, "setNoDelay", SetNoDelay);
99
5558
  env->SetProtoMethod(t, "setKeepAlive", SetKeepAlive);
100
101
#ifdef _WIN32
102
  env->SetProtoMethod(t, "setSimultaneousAccepts", SetSimultaneousAccepts);
103
#endif
104
105
5558
  env->SetConstructorFunction(target, "TCP", t);
106
5558
  env->set_tcp_constructor_template(t);
107
108
  // Create FunctionTemplate for TCPConnectWrap.
109
  Local<FunctionTemplate> cwt =
110
5558
      BaseObject::MakeLazilyInitializedJSTemplate(env);
111
5558
  cwt->Inherit(AsyncWrap::GetConstructorTemplate(env));
112
5558
  env->SetConstructorFunction(target, "TCPConnectWrap", cwt);
113
114
  // Define constants
115
5558
  Local<Object> constants = Object::New(env->isolate());
116
16674
  NODE_DEFINE_CONSTANT(constants, SOCKET);
117
16674
  NODE_DEFINE_CONSTANT(constants, SERVER);
118
16674
  NODE_DEFINE_CONSTANT(constants, UV_TCP_IPV6ONLY);
119
5558
  target->Set(context,
120
              env->constants_string(),
121
11116
              constants).Check();
122
5558
}
123
124
4975
void TCPWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
125
4975
  registry->Register(New);
126
4975
  registry->Register(Open);
127
4975
  registry->Register(Bind);
128
4975
  registry->Register(Listen);
129
4975
  registry->Register(Connect);
130
4975
  registry->Register(Bind6);
131
4975
  registry->Register(Connect6);
132
133
4975
  registry->Register(GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>);
134
4975
  registry->Register(GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>);
135
4975
  registry->Register(SetNoDelay);
136
4975
  registry->Register(SetKeepAlive);
137
#ifdef _WIN32
138
  registry->Register(SetSimultaneousAccepts);
139
#endif
140
4975
}
141
142
13531
void TCPWrap::New(const FunctionCallbackInfo<Value>& args) {
143
  // This constructor should not be exposed to public javascript.
144
  // Therefore we assert that we are not trying to call this as a
145
  // normal function.
146
13531
  CHECK(args.IsConstructCall());
147
13531
  CHECK(args[0]->IsInt32());
148
13531
  Environment* env = Environment::GetCurrent(args);
149
150
27062
  int type_value = args[0].As<Int32>()->Value();
151
13531
  TCPWrap::SocketType type = static_cast<TCPWrap::SocketType>(type_value);
152
153
  ProviderType provider;
154
13531
  switch (type) {
155
11805
    case SOCKET:
156
11805
      provider = PROVIDER_TCPWRAP;
157
11805
      break;
158
1726
    case SERVER:
159
1726
      provider = PROVIDER_TCPSERVERWRAP;
160
1726
      break;
161
    default:
162
      UNREACHABLE();
163
  }
164
165
13531
  new TCPWrap(env, args.This(), provider);
166
13531
}
167
168
169
13531
TCPWrap::TCPWrap(Environment* env, Local<Object> object, ProviderType provider)
170
13531
    : ConnectionWrap(env, object, provider) {
171
13531
  int r = uv_tcp_init(env->event_loop(), &handle_);
172
13531
  CHECK_EQ(r, 0);  // How do we proxy this error up to javascript?
173
                   // Suggestion: uv_tcp_init() returns void.
174
13531
}
175
176
177
5685
void TCPWrap::SetNoDelay(const FunctionCallbackInfo<Value>& args) {
178
  TCPWrap* wrap;
179
5685
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
180
                          args.Holder(),
181
                          args.GetReturnValue().Set(UV_EBADF));
182
5685
  int enable = static_cast<int>(args[0]->IsTrue());
183
5685
  int err = uv_tcp_nodelay(&wrap->handle_, enable);
184
11370
  args.GetReturnValue().Set(err);
185
}
186
187
188
161
void TCPWrap::SetKeepAlive(const FunctionCallbackInfo<Value>& args) {
189
  TCPWrap* wrap;
190
161
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
191
                          args.Holder(),
192
                          args.GetReturnValue().Set(UV_EBADF));
193
161
  Environment* env = wrap->env();
194
  int enable;
195
322
  if (!args[0]->Int32Value(env->context()).To(&enable)) return;
196
322
  unsigned int delay = static_cast<unsigned int>(args[1].As<Uint32>()->Value());
197
161
  int err = uv_tcp_keepalive(&wrap->handle_, enable, delay);
198
322
  args.GetReturnValue().Set(err);
199
}
200
201
202
#ifdef _WIN32
203
void TCPWrap::SetSimultaneousAccepts(const FunctionCallbackInfo<Value>& args) {
204
  TCPWrap* wrap;
205
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
206
                          args.Holder(),
207
                          args.GetReturnValue().Set(UV_EBADF));
208
  bool enable = args[0]->IsTrue();
209
  int err = uv_tcp_simultaneous_accepts(&wrap->handle_, enable);
210
  args.GetReturnValue().Set(err);
211
}
212
#endif
213
214
215
2
void TCPWrap::Open(const FunctionCallbackInfo<Value>& args) {
216
  TCPWrap* wrap;
217
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
218
                          args.Holder(),
219
                          args.GetReturnValue().Set(UV_EBADF));
220
  int64_t val;
221
4
  if (!args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val))
222
    return;
223
2
  int fd = static_cast<int>(val);
224
2
  int err = uv_tcp_open(&wrap->handle_, fd);
225
226
2
  if (err == 0)
227
2
    wrap->set_fd(fd);
228
229
4
  args.GetReturnValue().Set(err);
230
}
231
232
template <typename T>
233
3498
void TCPWrap::Bind(
234
    const FunctionCallbackInfo<Value>& args,
235
    int family,
236
    std::function<int(const char* ip_address, int port, T* addr)> uv_ip_addr) {
237
  TCPWrap* wrap;
238

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

1749
  unsigned int flags = 0;
245

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

3368
  if (family == AF_INET6 &&
247


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

1749
  if (err == 0) {
255
1747
    err = uv_tcp_bind(&wrap->handle_,
256
                      reinterpret_cast<const sockaddr*>(&addr),
257
                      flags);
258
  }
259
3498
  args.GetReturnValue().Set(err);
260
}
261
262
130
void TCPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
263
130
  Bind<sockaddr_in>(args, AF_INET, uv_ip4_addr);
264
130
}
265
266
267
1619
void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
268
1619
  Bind<sockaddr_in6>(args, AF_INET6, uv_ip6_addr);
269
1619
}
270
271
272
1732
void TCPWrap::Listen(const FunctionCallbackInfo<Value>& args) {
273
  TCPWrap* wrap;
274
1732
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
275
                          args.Holder(),
276
                          args.GetReturnValue().Set(UV_EBADF));
277
1732
  Environment* env = wrap->env();
278
  int backlog;
279
3464
  if (!args[0]->Int32Value(env->context()).To(&backlog)) return;
280
1732
  int err = uv_listen(reinterpret_cast<uv_stream_t*>(&wrap->handle_),
281
                      backlog,
282
                      OnConnection);
283
3464
  args.GetReturnValue().Set(err);
284
}
285
286
287
663
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args) {
288
663
  CHECK(args[2]->IsUint32());
289
  // explicit cast to fit to libuv's type expectation
290
1326
  int port = static_cast<int>(args[2].As<Uint32>()->Value());
291
663
  Connect<sockaddr_in>(args,
292
663
                       [port](const char* ip_address, sockaddr_in* addr) {
293
663
      return uv_ip4_addr(ip_address, port, addr);
294
  });
295
663
}
296
297
298
5279
void TCPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
299
5279
  Environment* env = Environment::GetCurrent(args);
300
5279
  CHECK(args[2]->IsUint32());
301
  int port;
302
10558
  if (!args[2]->Int32Value(env->context()).To(&port)) return;
303
5279
  Connect<sockaddr_in6>(args,
304
5279
                        [port](const char* ip_address, sockaddr_in6* addr) {
305
5279
      return uv_ip6_addr(ip_address, port, addr);
306
  });
307
}
308
309
template <typename T>
310
11884
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args,
311
    std::function<int(const char* ip_address, T* addr)> uv_ip_addr) {
312
11884
  Environment* env = Environment::GetCurrent(args);
313
314
  TCPWrap* wrap;
315
11884
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
316
                          args.Holder(),
317
                          args.GetReturnValue().Set(UV_EBADF));
318
319
11884
  CHECK(args[0]->IsObject());
320
23768
  CHECK(args[1]->IsString());
321
322
23768
  Local<Object> req_wrap_obj = args[0].As<Object>();
323
11884
  node::Utf8Value ip_address(env->isolate(), args[1]);
324
325
  T addr;
326
11884
  int err = uv_ip_addr(*ip_address, &addr);
327
328
11884
  if (err == 0) {
329
23768
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap);
330
23768
    ConnectWrap* req_wrap =
331
11884
        new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_TCPCONNECTWRAP);
332
23768
    err = req_wrap->Dispatch(uv_tcp_connect,
333
11884
                             &wrap->handle_,
334
                             reinterpret_cast<const sockaddr*>(&addr),
335
                             AfterConnect);
336
11884
    if (err)
337
      delete req_wrap;
338
  }
339
340
23768
  args.GetReturnValue().Set(err);
341
}
342
343
344
// also used by udp_wrap.cc
345
4994
MaybeLocal<Object> AddressToJS(Environment* env,
346
                               const sockaddr* addr,
347
                               Local<Object> info) {
348
4994
  EscapableHandleScope scope(env->isolate());
349
  char ip[INET6_ADDRSTRLEN + UV_IF_NAMESIZE];
350
  const sockaddr_in* a4;
351
  const sockaddr_in6* a6;
352
353
  int port;
354
355
4994
  if (info.IsEmpty())
356
334
    info = Object::New(env->isolate());
357
358
4994
  switch (addr->sa_family) {
359
4400
  case AF_INET6:
360
4400
    a6 = reinterpret_cast<const sockaddr_in6*>(addr);
361
4400
    uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
362
    // Add an interface identifier to a link local address.
363

4400
    if (IN6_IS_ADDR_LINKLOCAL(&a6->sin6_addr) && a6->sin6_scope_id > 0) {
364
2
      const size_t addrlen = strlen(ip);
365
2
      CHECK_LT(addrlen, sizeof(ip));
366
2
      ip[addrlen] = '%';
367
2
      size_t scopeidlen = sizeof(ip) - addrlen - 1;
368
2
      CHECK_GE(scopeidlen, UV_IF_NAMESIZE);
369
2
      const int r = uv_if_indextoiid(a6->sin6_scope_id,
370
2
                                     ip + addrlen + 1,
371
                                     &scopeidlen);
372
2
      if (r) {
373
        env->ThrowUVException(r, "uv_if_indextoiid");
374
        return {};
375
      }
376
    }
377
4400
    port = ntohs(a6->sin6_port);
378
4400
    info->Set(env->context(),
379
              env->address_string(),
380
17600
              OneByteString(env->isolate(), ip)).Check();
381
4400
    info->Set(env->context(),
382
              env->family_string(),
383
17600
              env->ipv6_string()).Check();
384
4400
    info->Set(env->context(),
385
              env->port_string(),
386
13200
              Integer::New(env->isolate(), port)).Check();
387
4400
    break;
388
389
594
  case AF_INET:
390
594
    a4 = reinterpret_cast<const sockaddr_in*>(addr);
391
594
    uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
392
594
    port = ntohs(a4->sin_port);
393
594
    info->Set(env->context(),
394
              env->address_string(),
395
2376
              OneByteString(env->isolate(), ip)).Check();
396
594
    info->Set(env->context(),
397
              env->family_string(),
398
2376
              env->ipv4_string()).Check();
399
594
    info->Set(env->context(),
400
              env->port_string(),
401
1782
              Integer::New(env->isolate(), port)).Check();
402
594
    break;
403
404
  default:
405
    info->Set(env->context(),
406
              env->address_string(),
407
              String::Empty(env->isolate())).Check();
408
  }
409
410
4994
  return scope.Escape(info);
411
}
412
413
414
}  // namespace node
415
416
5036
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tcp_wrap, node::TCPWrap::Initialize)
417
4975
NODE_MODULE_EXTERNAL_REFERENCE(tcp_wrap,
418
                               node::TCPWrap::RegisterExternalReferences)