GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: tcp_wrap.cc Lines: 187 195 95.9 %
Date: 2021-09-28 04:12:53 Branches: 48 92 52.2 %

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

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

1640
  unsigned int flags = 0;
245

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

3157
  if (family == AF_INET6 &&
247


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

1640
  if (err == 0) {
255
1638
    err = uv_tcp_bind(&wrap->handle_,
256
                      reinterpret_cast<const sockaddr*>(&addr),
257
                      flags);
258
  }
259
3280
  args.GetReturnValue().Set(err);
260
}
261
262
123
void TCPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
263
123
  Bind<sockaddr_in>(args, AF_INET, uv_ip4_addr);
264
123
}
265
266
267
1517
void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
268
1517
  Bind<sockaddr_in6>(args, AF_INET6, uv_ip6_addr);
269
1517
}
270
271
272
1623
void TCPWrap::Listen(const FunctionCallbackInfo<Value>& args) {
273
  TCPWrap* wrap;
274
1623
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
275
                          args.Holder(),
276
                          args.GetReturnValue().Set(UV_EBADF));
277
1623
  Environment* env = wrap->env();
278
  int backlog;
279
3246
  if (!args[0]->Int32Value(env->context()).To(&backlog)) return;
280
1623
  int err = uv_listen(reinterpret_cast<uv_stream_t*>(&wrap->handle_),
281
                      backlog,
282
                      OnConnection);
283
3246
  args.GetReturnValue().Set(err);
284
}
285
286
287
637
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args) {
288
637
  CHECK(args[2]->IsUint32());
289
  // explicit cast to fit to libuv's type expectation
290
1274
  int port = static_cast<int>(args[2].As<Uint32>()->Value());
291
637
  Connect<sockaddr_in>(args,
292
637
                       [port](const char* ip_address, sockaddr_in* addr) {
293
637
      return uv_ip4_addr(ip_address, port, addr);
294
  });
295
637
}
296
297
298
5110
void TCPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
299
5110
  Environment* env = Environment::GetCurrent(args);
300
5110
  CHECK(args[2]->IsUint32());
301
  int port;
302
10220
  if (!args[2]->Int32Value(env->context()).To(&port)) return;
303
5110
  Connect<sockaddr_in6>(args,
304
5110
                        [port](const char* ip_address, sockaddr_in6* addr) {
305
5110
      return uv_ip6_addr(ip_address, port, addr);
306
  });
307
}
308
309
template <typename T>
310
11494
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args,
311
    std::function<int(const char* ip_address, T* addr)> uv_ip_addr) {
312
11494
  Environment* env = Environment::GetCurrent(args);
313
314
  TCPWrap* wrap;
315
11494
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
316
                          args.Holder(),
317
                          args.GetReturnValue().Set(UV_EBADF));
318
319
11494
  CHECK(args[0]->IsObject());
320
22988
  CHECK(args[1]->IsString());
321
322
22988
  Local<Object> req_wrap_obj = args[0].As<Object>();
323
11494
  node::Utf8Value ip_address(env->isolate(), args[1]);
324
325
  T addr;
326
11494
  int err = uv_ip_addr(*ip_address, &addr);
327
328
11494
  if (err == 0) {
329
22988
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap);
330
22988
    ConnectWrap* req_wrap =
331
11494
        new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_TCPCONNECTWRAP);
332
22988
    err = req_wrap->Dispatch(uv_tcp_connect,
333
11494
                             &wrap->handle_,
334
                             reinterpret_cast<const sockaddr*>(&addr),
335
                             AfterConnect);
336
11494
    if (err)
337
      delete req_wrap;
338
  }
339
340
22988
  args.GetReturnValue().Set(err);
341
}
342
343
344
// also used by udp_wrap.cc
345
4870
Local<Object> AddressToJS(Environment* env,
346
                          const sockaddr* addr,
347
                          Local<Object> info) {
348
4870
  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
4870
  if (info.IsEmpty())
356
378
    info = Object::New(env->isolate());
357
358
4870
  switch (addr->sa_family) {
359
4240
  case AF_INET6:
360
4240
    a6 = reinterpret_cast<const sockaddr_in6*>(addr);
361
4240
    uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
362
    // Add an interface identifier to a link local address.
363
4240
    if (IN6_IS_ADDR_LINKLOCAL(&a6->sin6_addr)) {
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
2
                                       &scopeidlen);
372
2
        CHECK_EQ(r, 0);
373
    }
374
4240
    port = ntohs(a6->sin6_port);
375
4240
    info->Set(env->context(),
376
              env->address_string(),
377
16960
              OneByteString(env->isolate(), ip)).Check();
378
4240
    info->Set(env->context(),
379
              env->family_string(),
380
16960
              env->ipv6_string()).Check();
381
4240
    info->Set(env->context(),
382
              env->port_string(),
383
12720
              Integer::New(env->isolate(), port)).Check();
384
4240
    break;
385
386
630
  case AF_INET:
387
630
    a4 = reinterpret_cast<const sockaddr_in*>(addr);
388
630
    uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
389
630
    port = ntohs(a4->sin_port);
390
630
    info->Set(env->context(),
391
              env->address_string(),
392
2520
              OneByteString(env->isolate(), ip)).Check();
393
630
    info->Set(env->context(),
394
              env->family_string(),
395
2520
              env->ipv4_string()).Check();
396
630
    info->Set(env->context(),
397
              env->port_string(),
398
1890
              Integer::New(env->isolate(), port)).Check();
399
630
    break;
400
401
  default:
402
    info->Set(env->context(),
403
              env->address_string(),
404
              String::Empty(env->isolate())).Check();
405
  }
406
407
4870
  return scope.Escape(info);
408
}
409
410
411
}  // namespace node
412
413
4928
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tcp_wrap, node::TCPWrap::Initialize)
414
4855
NODE_MODULE_EXTERNAL_REFERENCE(tcp_wrap,
415
                               node::TCPWrap::RegisterExternalReferences)