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

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

1776
  unsigned int flags = 0;
245

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

3422
  if (family == AF_INET6 &&
247


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

1776
  if (err == 0) {
255
1774
    err = uv_tcp_bind(&wrap->handle_,
256
                      reinterpret_cast<const sockaddr*>(&addr),
257
                      flags);
258
  }
259
3552
  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
1646
void TCPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
268
1646
  Bind<sockaddr_in6>(args, AF_INET6, uv_ip6_addr);
269
1646
}
270
271
272
1759
void TCPWrap::Listen(const FunctionCallbackInfo<Value>& args) {
273
  TCPWrap* wrap;
274
1759
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
275
                          args.Holder(),
276
                          args.GetReturnValue().Set(UV_EBADF));
277
1759
  Environment* env = wrap->env();
278
  int backlog;
279
3518
  if (!args[0]->Int32Value(env->context()).To(&backlog)) return;
280
1759
  int err = uv_listen(reinterpret_cast<uv_stream_t*>(&wrap->handle_),
281
                      backlog,
282
                      OnConnection);
283
3518
  args.GetReturnValue().Set(err);
284
}
285
286
287
686
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args) {
288
686
  CHECK(args[2]->IsUint32());
289
  // explicit cast to fit to libuv's type expectation
290
1372
  int port = static_cast<int>(args[2].As<Uint32>()->Value());
291
686
  Connect<sockaddr_in>(args,
292
686
                       [port](const char* ip_address, sockaddr_in* addr) {
293
686
      return uv_ip4_addr(ip_address, port, addr);
294
  });
295
686
}
296
297
298
4910
void TCPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
299
4910
  Environment* env = Environment::GetCurrent(args);
300
4910
  CHECK(args[2]->IsUint32());
301
  int port;
302
9820
  if (!args[2]->Int32Value(env->context()).To(&port)) return;
303
4910
  Connect<sockaddr_in6>(args,
304
4910
                        [port](const char* ip_address, sockaddr_in6* addr) {
305
4910
      return uv_ip6_addr(ip_address, port, addr);
306
  });
307
}
308
309
template <typename T>
310
11192
void TCPWrap::Connect(const FunctionCallbackInfo<Value>& args,
311
    std::function<int(const char* ip_address, T* addr)> uv_ip_addr) {
312
11192
  Environment* env = Environment::GetCurrent(args);
313
314
  TCPWrap* wrap;
315
11192
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
316
                          args.Holder(),
317
                          args.GetReturnValue().Set(UV_EBADF));
318
319
11192
  CHECK(args[0]->IsObject());
320
22384
  CHECK(args[1]->IsString());
321
322
22384
  Local<Object> req_wrap_obj = args[0].As<Object>();
323
11192
  node::Utf8Value ip_address(env->isolate(), args[1]);
324
325
  T addr;
326
11192
  int err = uv_ip_addr(*ip_address, &addr);
327
328
11192
  if (err == 0) {
329
22384
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap);
330
22384
    ConnectWrap* req_wrap =
331
11192
        new ConnectWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_TCPCONNECTWRAP);
332
22384
    err = req_wrap->Dispatch(uv_tcp_connect,
333
11192
                             &wrap->handle_,
334
                             reinterpret_cast<const sockaddr*>(&addr),
335
                             AfterConnect);
336
11192
    if (err)
337
      delete req_wrap;
338
  }
339
340
22384
  args.GetReturnValue().Set(err);
341
}
342
343
344
// also used by udp_wrap.cc
345
4826
MaybeLocal<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
369
    info = Object::New(env->isolate());
357
358
4826
  switch (addr->sa_family) {
359
4194
  case AF_INET6:
360
4194
    a6 = reinterpret_cast<const sockaddr_in6*>(addr);
361
4194
    uv_inet_ntop(AF_INET6, &a6->sin6_addr, ip, sizeof ip);
362
    // Add an interface identifier to a link local address.
363

4194
    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
4194
    port = ntohs(a6->sin6_port);
378
4194
    info->Set(env->context(),
379
              env->address_string(),
380
16776
              OneByteString(env->isolate(), ip)).Check();
381
4194
    info->Set(env->context(),
382
              env->family_string(),
383
16776
              Integer::New(env->isolate(), 6)).Check();
384
4194
    info->Set(env->context(),
385
              env->port_string(),
386
12582
              Integer::New(env->isolate(), port)).Check();
387
4194
    break;
388
389
632
  case AF_INET:
390
632
    a4 = reinterpret_cast<const sockaddr_in*>(addr);
391
632
    uv_inet_ntop(AF_INET, &a4->sin_addr, ip, sizeof ip);
392
632
    port = ntohs(a4->sin_port);
393
632
    info->Set(env->context(),
394
              env->address_string(),
395
2528
              OneByteString(env->isolate(), ip)).Check();
396
632
    info->Set(env->context(),
397
              env->family_string(),
398
2528
              Integer::New(env->isolate(), 4)).Check();
399
632
    info->Set(env->context(),
400
              env->port_string(),
401
1896
              Integer::New(env->isolate(), port)).Check();
402
632
    break;
403
404
  default:
405
    info->Set(env->context(),
406
              env->address_string(),
407
              String::Empty(env->isolate())).Check();
408
  }
409
410
4826
  return scope.Escape(info);
411
}
412
413
414
}  // namespace node
415
416
5252
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tcp_wrap, node::TCPWrap::Initialize)
417
5184
NODE_MODULE_EXTERNAL_REFERENCE(tcp_wrap,
418
                               node::TCPWrap::RegisterExternalReferences)