GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: tcp_wrap.cc Lines: 187 195 95.9 %
Date: 2021-10-01 04:12:33 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
5320
MaybeLocal<Object> TCPWrap::Instantiate(Environment* env,
56
                                        AsyncWrap* parent,
57
                                        TCPWrap::SocketType type) {
58
5320
  EscapableHandleScope handle_scope(env->isolate());
59
5320
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(parent);
60
10640
  CHECK_EQ(env->tcp_constructor_template().IsEmpty(), false);
61
5320
  Local<Function> constructor = env->tcp_constructor_template()
62
5320
                                    ->GetFunction(env->context())
63
5320
                                    .ToLocalChecked();
64
5320
  CHECK_EQ(constructor.IsEmpty(), false);
65
10640
  Local<Value> type_value = Int32::New(env->isolate(), type);
66
  return handle_scope.EscapeMaybe(
67
10640
      constructor->NewInstance(env->context(), 1, &type_value));
68
}
69
70
71
4712
void TCPWrap::Initialize(Local<Object> target,
72
                         Local<Value> unused,
73
                         Local<Context> context,
74
                         void* priv) {
75
4712
  Environment* env = Environment::GetCurrent(context);
76
77
4712
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
78
9424
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
79
80
  // Init properties
81
18848
  t->InstanceTemplate()->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "reading"),
82
                             Boolean::New(env->isolate(), false));
83
18848
  t->InstanceTemplate()->Set(env->owner_symbol(), Null(env->isolate()));
84
18848
  t->InstanceTemplate()->Set(env->onconnection_string(), Null(env->isolate()));
85
86
4712
  t->Inherit(LibuvStreamWrap::GetConstructorTemplate(env));
87
88
4712
  env->SetProtoMethod(t, "open", Open);
89
4712
  env->SetProtoMethod(t, "bind", Bind);
90
4712
  env->SetProtoMethod(t, "listen", Listen);
91
4712
  env->SetProtoMethod(t, "connect", Connect);
92
4712
  env->SetProtoMethod(t, "bind6", Bind6);
93
4712
  env->SetProtoMethod(t, "connect6", Connect6);
94
4712
  env->SetProtoMethod(t, "getsockname",
95
                      GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>);
96
4712
  env->SetProtoMethod(t, "getpeername",
97
                      GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>);
98
4712
  env->SetProtoMethod(t, "setNoDelay", SetNoDelay);
99
4712
  env->SetProtoMethod(t, "setKeepAlive", SetKeepAlive);
100
101
#ifdef _WIN32
102
  env->SetProtoMethod(t, "setSimultaneousAccepts", SetSimultaneousAccepts);
103
#endif
104
105
4712
  env->SetConstructorFunction(target, "TCP", t);
106
4712
  env->set_tcp_constructor_template(t);
107
108
  // Create FunctionTemplate for TCPConnectWrap.
109
  Local<FunctionTemplate> cwt =
110
4712
      BaseObject::MakeLazilyInitializedJSTemplate(env);
111
4712
  cwt->Inherit(AsyncWrap::GetConstructorTemplate(env));
112
4712
  env->SetConstructorFunction(target, "TCPConnectWrap", cwt);
113
114
  // Define constants
115
4712
  Local<Object> constants = Object::New(env->isolate());
116
14136
  NODE_DEFINE_CONSTANT(constants, SOCKET);
117
14136
  NODE_DEFINE_CONSTANT(constants, SERVER);
118
14136
  NODE_DEFINE_CONSTANT(constants, UV_TCP_IPV6ONLY);
119
4712
  target->Set(context,
120
              env->constants_string(),
121
9424
              constants).Check();
122
4712
}
123
124
4851
void TCPWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
125
4851
  registry->Register(New);
126
4851
  registry->Register(Open);
127
4851
  registry->Register(Bind);
128
4851
  registry->Register(Listen);
129
4851
  registry->Register(Connect);
130
4851
  registry->Register(Bind6);
131
4851
  registry->Register(Connect6);
132
133
4851
  registry->Register(GetSockOrPeerName<TCPWrap, uv_tcp_getsockname>);
134
4851
  registry->Register(GetSockOrPeerName<TCPWrap, uv_tcp_getpeername>);
135
4851
  registry->Register(SetNoDelay);
136
4851
  registry->Register(SetKeepAlive);
137
#ifdef _WIN32
138
  registry->Register(SetSimultaneousAccepts);
139
#endif
140
4851
}
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
11421
    case SOCKET:
156
11421
      provider = PROVIDER_TCPWRAP;
157
11421
      break;
158
1615
    case SERVER:
159
1615
      provider = PROVIDER_TCPSERVERWRAP;
160
1615
      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
3276
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

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

1638
  unsigned int flags = 0;
245

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

3153
  if (family == AF_INET6 &&
247


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

1638
  if (err == 0) {
255
1636
    err = uv_tcp_bind(&wrap->handle_,
256
                      reinterpret_cast<const sockaddr*>(&addr),
257
                      flags);
258
  }
259
3276
  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
1515
void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
268
1515
  Bind<sockaddr_in6>(args, AF_INET6, uv_ip6_addr);
269
1515
}
270
271
272
1621
void TCPWrap::Listen(const FunctionCallbackInfo<Value>& args) {
273
  TCPWrap* wrap;
274
1621
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
275
                          args.Holder(),
276
                          args.GetReturnValue().Set(UV_EBADF));
277
1621
  Environment* env = wrap->env();
278
  int backlog;
279
3242
  if (!args[0]->Int32Value(env->context()).To(&backlog)) return;
280
1621
  int err = uv_listen(reinterpret_cast<uv_stream_t*>(&wrap->handle_),
281
                      backlog,
282
                      OnConnection);
283
3242
  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
5112
void TCPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
299
5112
  Environment* env = Environment::GetCurrent(args);
300
5112
  CHECK(args[2]->IsUint32());
301
  int port;
302
10224
  if (!args[2]->Int32Value(env->context()).To(&port)) return;
303
5112
  Connect<sockaddr_in6>(args,
304
5112
                        [port](const char* ip_address, sockaddr_in6* addr) {
305
5112
      return uv_ip6_addr(ip_address, port, addr);
306
  });
307
}
308
309
template <typename T>
310
11498
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args,
311
    std::function<int(const char* ip_address, T* addr)> uv_ip_addr) {
312
11498
  Environment* env = Environment::GetCurrent(args);
313
314
  TCPWrap* wrap;
315
11498
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
316
                          args.Holder(),
317
                          args.GetReturnValue().Set(UV_EBADF));
318
319
11498
  CHECK(args[0]->IsObject());
320
22996
  CHECK(args[1]->IsString());
321
322
22996
  Local<Object> req_wrap_obj = args[0].As<Object>();
323
11498
  node::Utf8Value ip_address(env->isolate(), args[1]);
324
325
  T addr;
326
11498
  int err = uv_ip_addr(*ip_address, &addr);
327
328
11498
  if (err == 0) {
329
22996
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap);
330
22996
    ConnectWrap* req_wrap =
331
11498
        new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_TCPCONNECTWRAP);
332
22996
    err = req_wrap->Dispatch(uv_tcp_connect,
333
11498
                             &wrap->handle_,
334
                             reinterpret_cast<const sockaddr*>(&addr),
335
                             AfterConnect);
336
11498
    if (err)
337
      delete req_wrap;
338
  }
339
340
22996
  args.GetReturnValue().Set(err);
341
}
342
343
344
// also used by udp_wrap.cc
345
4826
Local<Object> AddressToJS(Environment* env,
346
                          const sockaddr* addr,
347
                          Local<Object> info) {
348
4826
  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
4826
  if (info.IsEmpty())
356
339
    info = Object::New(env->isolate());
357
358
4826
  switch (addr->sa_family) {
359
4236
  case AF_INET6:
360
4236
    a6 = reinterpret_cast<const sockaddr_in6*>(addr);
361
4236
    uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
362
    // Add an interface identifier to a link local address.
363
4236
    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
4236
    port = ntohs(a6->sin6_port);
375
4236
    info->Set(env->context(),
376
              env->address_string(),
377
16944
              OneByteString(env->isolate(), ip)).Check();
378
4236
    info->Set(env->context(),
379
              env->family_string(),
380
16944
              env->ipv6_string()).Check();
381
4236
    info->Set(env->context(),
382
              env->port_string(),
383
12708
              Integer::New(env->isolate(), port)).Check();
384
4236
    break;
385
386
590
  case AF_INET:
387
590
    a4 = reinterpret_cast<const sockaddr_in*>(addr);
388
590
    uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
389
590
    port = ntohs(a4->sin_port);
390
590
    info->Set(env->context(),
391
              env->address_string(),
392
2360
              OneByteString(env->isolate(), ip)).Check();
393
590
    info->Set(env->context(),
394
              env->family_string(),
395
2360
              env->ipv4_string()).Check();
396
590
    info->Set(env->context(),
397
              env->port_string(),
398
1770
              Integer::New(env->isolate(), port)).Check();
399
590
    break;
400
401
  default:
402
    info->Set(env->context(),
403
              env->address_string(),
404
              String::Empty(env->isolate())).Check();
405
  }
406
407
4826
  return scope.Escape(info);
408
}
409
410
411
}  // namespace node
412
413
4924
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tcp_wrap, node::TCPWrap::Initialize)
414
4851
NODE_MODULE_EXTERNAL_REFERENCE(tcp_wrap,
415
                               node::TCPWrap::RegisterExternalReferences)