GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/src/udp_wrap.cc Lines: 196 212 92.5 %
Date: 2016-07-23 Branches: 52 104 50.0 %

Line Exec Source
1
#include "udp_wrap.h"
2
#include "env.h"
3
#include "env-inl.h"
4
#include "node_buffer.h"
5
#include "handle_wrap.h"
6
#include "req-wrap.h"
7
#include "req-wrap-inl.h"
8
#include "util.h"
9
#include "util-inl.h"
10
11
#include <stdlib.h>
12
13
14
namespace node {
15
16
using v8::Array;
17
using v8::Context;
18
using v8::EscapableHandleScope;
19
using v8::External;
20
using v8::Function;
21
using v8::FunctionCallbackInfo;
22
using v8::FunctionTemplate;
23
using v8::HandleScope;
24
using v8::Integer;
25
using v8::Local;
26
using v8::Object;
27
using v8::PropertyAttribute;
28
using v8::PropertyCallbackInfo;
29
using v8::String;
30
using v8::Uint32;
31
using v8::Undefined;
32
using v8::Value;
33
34
35
457
class SendWrap : public ReqWrap<uv_udp_send_t> {
36
 public:
37
  SendWrap(Environment* env, Local<Object> req_wrap_obj, bool have_callback);
38
  inline bool have_callback() const;
39
  size_t msg_size;
40
  size_t self_size() const override { return sizeof(*this); }
41
 private:
42
  const bool have_callback_;
43
};
44
45
46
SendWrap::SendWrap(Environment* env,
47
                   Local<Object> req_wrap_obj,
48
                   bool have_callback)
49
    : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_UDPSENDWRAP),
50
457
      have_callback_(have_callback) {
51
457
  Wrap(req_wrap_obj, this);
52
}
53
54
55
inline bool SendWrap::have_callback() const {
56
  return have_callback_;
57
}
58
59
60
457
static void NewSendWrap(const FunctionCallbackInfo<Value>& args) {
61
457
  CHECK(args.IsConstructCall());
62
457
}
63
64
65
99
UDPWrap::UDPWrap(Environment* env, Local<Object> object, AsyncWrap* parent)
66
    : HandleWrap(env,
67
                 object,
68
                 reinterpret_cast<uv_handle_t*>(&handle_),
69
99
                 AsyncWrap::PROVIDER_UDPWRAP) {
70
198
  int r = uv_udp_init(env->event_loop(), &handle_);
71
99
  CHECK_EQ(r, 0);  // can't fail anyway
72
99
}
73
74
75
1435
void UDPWrap::Initialize(Local<Object> target,
76
                         Local<Value> unused,
77
                         Local<Context> context) {
78
1435
  Environment* env = Environment::GetCurrent(context);
79
80
2870
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
81
2870
  t->InstanceTemplate()->SetInternalFieldCount(1);
82
1435
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "UDP"));
83
84
  enum PropertyAttribute attributes =
85
1435
      static_cast<PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
86
8610
  t->InstanceTemplate()->SetAccessor(env->fd_string(),
87
                                     UDPWrap::GetFD,
88
                                     nullptr,
89
                                     env->as_external(),
90
                                     v8::DEFAULT,
91
1435
                                     attributes);
92
93
1435
  env->SetProtoMethod(t, "bind", Bind);
94
1435
  env->SetProtoMethod(t, "send", Send);
95
1435
  env->SetProtoMethod(t, "bind6", Bind6);
96
1435
  env->SetProtoMethod(t, "send6", Send6);
97
1435
  env->SetProtoMethod(t, "close", Close);
98
1435
  env->SetProtoMethod(t, "recvStart", RecvStart);
99
1435
  env->SetProtoMethod(t, "recvStop", RecvStop);
100
  env->SetProtoMethod(t, "getsockname",
101
1435
                      GetSockOrPeerName<UDPWrap, uv_udp_getsockname>);
102
1435
  env->SetProtoMethod(t, "addMembership", AddMembership);
103
1435
  env->SetProtoMethod(t, "dropMembership", DropMembership);
104
1435
  env->SetProtoMethod(t, "setMulticastTTL", SetMulticastTTL);
105
1435
  env->SetProtoMethod(t, "setMulticastLoopback", SetMulticastLoopback);
106
1435
  env->SetProtoMethod(t, "setBroadcast", SetBroadcast);
107
1435
  env->SetProtoMethod(t, "setTTL", SetTTL);
108
109
1435
  env->SetProtoMethod(t, "ref", HandleWrap::Ref);
110
1435
  env->SetProtoMethod(t, "unref", HandleWrap::Unref);
111
1435
  env->SetProtoMethod(t, "hasRef", HandleWrap::HasRef);
112
113
4305
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "UDP"), t->GetFunction());
114
1435
  env->set_udp_constructor_function(t->GetFunction());
115
116
  // Create FunctionTemplate for SendWrap
117
  Local<FunctionTemplate> swt =
118
2870
      FunctionTemplate::New(env->isolate(), NewSendWrap);
119
2870
  swt->InstanceTemplate()->SetInternalFieldCount(1);
120
1435
  swt->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SendWrap"));
121
5740
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "SendWrap"),
122
1435
              swt->GetFunction());
123
1435
}
124
125
126
99
void UDPWrap::New(const FunctionCallbackInfo<Value>& args) {
127
99
  CHECK(args.IsConstructCall());
128
99
  Environment* env = Environment::GetCurrent(args);
129
99
  if (args.Length() == 0) {
130
85
    new UDPWrap(env, args.This(), nullptr);
131
14
  } else if (args[0]->IsExternal()) {
132
    new UDPWrap(env,
133
28
                args.This(),
134
28
                static_cast<AsyncWrap*>(args[0].As<External>()->Value()));
135
  } else {
136
    UNREACHABLE();
137
  }
138
99
}
139
140
141
2
void UDPWrap::GetFD(Local<String>, const PropertyCallbackInfo<Value>& args) {
142
2
  int fd = UV_EBADF;
143
#if !defined(_WIN32)
144
4
  HandleScope scope(args.GetIsolate());
145
2
  UDPWrap* wrap = Unwrap<UDPWrap>(args.Holder());
146
2
  if (wrap != nullptr)
147
    uv_fileno(reinterpret_cast<uv_handle_t*>(&wrap->handle_), &fd);
148
#endif
149
6
  args.GetReturnValue().Set(fd);
150
2
}
151
152
153
50
void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) {
154
  UDPWrap* wrap;
155
50
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
156
                          args.Holder(),
157
                          args.GetReturnValue().Set(UV_EBADF));
158
159
  // bind(ip, port, flags)
160
50
  CHECK_EQ(args.Length(), 3);
161
162
150
  node::Utf8Value address(args.GetIsolate(), args[0]);
163
50
  const int port = args[1]->Uint32Value();
164
50
  const int flags = args[2]->Uint32Value();
165
  char addr[sizeof(sockaddr_in6)];
166
  int err;
167
168
50
  switch (family) {
169
  case AF_INET:
170
46
    err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
171
46
    break;
172
  case AF_INET6:
173
4
    err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
174
4
    break;
175
  default:
176
    CHECK(0 && "unexpected address family");
177
    ABORT();
178
  }
179
180
50
  if (err == 0) {
181
50
    err = uv_udp_bind(&wrap->handle_,
182
                      reinterpret_cast<const sockaddr*>(&addr),
183
50
                      flags);
184
  }
185
186
100
  args.GetReturnValue().Set(err);
187
}
188
189
190
46
void UDPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
191
46
  DoBind(args, AF_INET);
192
46
}
193
194
195
4
void UDPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
196
4
  DoBind(args, AF_INET6);
197
4
}
198
199
200
#define X(name, fn)                                                           \
201
  void UDPWrap::name(const FunctionCallbackInfo<Value>& args) {               \
202
    UDPWrap* wrap = Unwrap<UDPWrap>(args.Holder());                           \
203
    CHECK_EQ(args.Length(), 1);                                               \
204
    int flag = args[0]->Int32Value();                                         \
205
    int err = wrap == nullptr ? UV_EBADF : fn(&wrap->handle_, flag);          \
206
    args.GetReturnValue().Set(err);                                           \
207
  }
208
209
6
X(SetTTL, uv_udp_set_ttl)
210
6
X(SetBroadcast, uv_udp_set_broadcast)
211
12
X(SetMulticastTTL, uv_udp_set_multicast_ttl)
212
X(SetMulticastLoopback, uv_udp_set_multicast_loop)
213
214
#undef X
215
216
217
6
void UDPWrap::SetMembership(const FunctionCallbackInfo<Value>& args,
218
                            uv_membership membership) {
219
  UDPWrap* wrap;
220
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
221
                          args.Holder(),
222
                          args.GetReturnValue().Set(UV_EBADF));
223
224
6
  CHECK_EQ(args.Length(), 2);
225
226
18
  node::Utf8Value address(args.GetIsolate(), args[0]);
227
18
  node::Utf8Value iface(args.GetIsolate(), args[1]);
228
229
6
  const char* iface_cstr = *iface;
230
18
  if (args[1]->IsUndefined() || args[1]->IsNull()) {
231
6
      iface_cstr = nullptr;
232
  }
233
234
6
  int err = uv_udp_set_membership(&wrap->handle_,
235
6
                                  *address,
236
                                  iface_cstr,
237
6
                                  membership);
238
12
  args.GetReturnValue().Set(err);
239
}
240
241
242
3
void UDPWrap::AddMembership(const FunctionCallbackInfo<Value>& args) {
243
3
  SetMembership(args, UV_JOIN_GROUP);
244
3
}
245
246
247
3
void UDPWrap::DropMembership(const FunctionCallbackInfo<Value>& args) {
248
3
  SetMembership(args, UV_LEAVE_GROUP);
249
3
}
250
251
252
457
void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
253
457
  Environment* env = Environment::GetCurrent(args);
254
255
  UDPWrap* wrap;
256
457
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
257
                          args.Holder(),
258
                          args.GetReturnValue().Set(UV_EBADF));
259
260
  // send(req, list, port, address, hasCallback)
261
457
  CHECK(args[0]->IsObject());
262
457
  CHECK(args[1]->IsArray());
263
457
  CHECK(args[2]->IsUint32());
264
457
  CHECK(args[3]->IsUint32());
265
914
  CHECK(args[4]->IsString());
266
457
  CHECK(args[5]->IsBoolean());
267
268
914
  Local<Object> req_wrap_obj = args[0].As<Object>();
269
914
  Local<Array> chunks = args[1].As<Array>();
270
  // it is faster to fetch the length of the
271
  // array in js-land
272
457
  size_t count = args[2]->Uint32Value();
273
457
  const unsigned short port = args[3]->Uint32Value();
274
914
  node::Utf8Value address(env->isolate(), args[4]);
275
457
  const bool have_callback = args[5]->IsTrue();
276
277
914
  SendWrap* req_wrap = new SendWrap(env, req_wrap_obj, have_callback);
278
457
  size_t msg_size = 0;
279
280
  // allocate uv_buf_t of the correct size
281
  // if bigger than 16 elements
282
  uv_buf_t bufs_[16];
283
457
  uv_buf_t* bufs = bufs_;
284
285
457
  if (arraysize(bufs_) < count)
286
    bufs = new uv_buf_t[count];
287
288
  // construct uv_buf_t array
289
916
  for (size_t i = 0; i < count; i++) {
290
459
    Local<Value> chunk = chunks->Get(i);
291
292
459
    size_t length = Buffer::Length(chunk);
293
294
459
    bufs[i] = uv_buf_init(Buffer::Data(chunk), length);
295
459
    msg_size += length;
296
  }
297
298
457
  req_wrap->msg_size = msg_size;
299
300
  char addr[sizeof(sockaddr_in6)];
301
  int err;
302
303
457
  switch (family) {
304
  case AF_INET:
305
453
    err = uv_ip4_addr(*address, port, reinterpret_cast<sockaddr_in*>(&addr));
306
453
    break;
307
  case AF_INET6:
308
4
    err = uv_ip6_addr(*address, port, reinterpret_cast<sockaddr_in6*>(&addr));
309
4
    break;
310
  default:
311
    CHECK(0 && "unexpected address family");
312
    ABORT();
313
  }
314
315
457
  if (err == 0) {
316
456
    err = uv_udp_send(&req_wrap->req_,
317
                      &wrap->handle_,
318
                      bufs,
319
                      count,
320
                      reinterpret_cast<const sockaddr*>(&addr),
321
456
                      OnSend);
322
  }
323
324
  // Deallocate space
325
457
  if (bufs != bufs_)
326
    delete[] bufs;
327
328
914
  req_wrap->Dispatched();
329
457
  if (err)
330
1
    delete req_wrap;
331
332
914
  args.GetReturnValue().Set(err);
333
}
334
335
336
453
void UDPWrap::Send(const FunctionCallbackInfo<Value>& args) {
337
453
  DoSend(args, AF_INET);
338
453
}
339
340
341
4
void UDPWrap::Send6(const FunctionCallbackInfo<Value>& args) {
342
4
  DoSend(args, AF_INET6);
343
4
}
344
345
346
55
void UDPWrap::RecvStart(const FunctionCallbackInfo<Value>& args) {
347
  UDPWrap* wrap;
348
55
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
349
                          args.Holder(),
350
                          args.GetReturnValue().Set(UV_EBADF));
351
55
  int err = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
352
  // UV_EALREADY means that the socket is already bound but that's okay
353
55
  if (err == UV_EALREADY)
354
    err = 0;
355
110
  args.GetReturnValue().Set(err);
356
}
357
358
359
48
void UDPWrap::RecvStop(const FunctionCallbackInfo<Value>& args) {
360
  UDPWrap* wrap;
361
48
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
362
                          args.Holder(),
363
                          args.GetReturnValue().Set(UV_EBADF));
364
48
  int r = uv_udp_recv_stop(&wrap->handle_);
365
96
  args.GetReturnValue().Set(r);
366
}
367
368
369
// TODO(bnoordhuis) share with StreamWrap::AfterWrite() in stream_wrap.cc
370
456
void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
371
456
  SendWrap* req_wrap = static_cast<SendWrap*>(req->data);
372
456
  if (req_wrap->have_callback()) {
373
395
    Environment* env = req_wrap->env();
374
790
    HandleScope handle_scope(env->isolate());
375
1185
    Context::Scope context_scope(env->context());
376
    Local<Value> arg[] = {
377
      Integer::New(env->isolate(), status),
378
395
      Integer::New(env->isolate(), req_wrap->msg_size),
379
1580
    };
380
395
    req_wrap->MakeCallback(env->oncomplete_string(), 2, arg);
381
  }
382
456
  delete req_wrap;
383
456
}
384
385
386
857
void UDPWrap::OnAlloc(uv_handle_t* handle,
387
                      size_t suggested_size,
388
                      uv_buf_t* buf) {
389
857
  buf->base = static_cast<char*>(malloc(suggested_size));
390
857
  buf->len = suggested_size;
391
392
857
  if (buf->base == nullptr && suggested_size > 0) {
393
    FatalError("node::UDPWrap::OnAlloc(uv_handle_t*, size_t, uv_buf_t*)",
394
               "Out Of Memory");
395
  }
396
857
}
397
398
399
857
void UDPWrap::OnRecv(uv_udp_t* handle,
400
                     ssize_t nread,
401
                     const uv_buf_t* buf,
402
                     const struct sockaddr* addr,
403
                     unsigned int flags) {
404
857
  if (nread == 0 && addr == nullptr) {
405
405
    if (buf->base != nullptr)
406
405
      free(buf->base);
407
405
    return;
408
  }
409
410
452
  UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
411
452
  Environment* env = wrap->env();
412
413
900
  HandleScope handle_scope(env->isolate());
414
1352
  Context::Scope context_scope(env->context());
415
416
904
  Local<Object> wrap_obj = wrap->object();
417
  Local<Value> argv[] = {
418
    Integer::New(env->isolate(), nread),
419
    wrap_obj,
420
    Undefined(env->isolate()),
421
    Undefined(env->isolate())
422
3164
  };
423
424
452
  if (nread < 0) {
425
    if (buf->base != nullptr)
426
      free(buf->base);
427
    wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
428
    return;
429
  }
430
431
452
  char* base = static_cast<char*>(realloc(buf->base, nread));
432
1356
  argv[2] = Buffer::New(env, base, nread).ToLocalChecked();
433
904
  argv[3] = AddressToJS(env, addr);
434
904
  wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
435
}
436
437
438
14
Local<Object> UDPWrap::Instantiate(Environment* env, AsyncWrap* parent) {
439
28
  EscapableHandleScope scope(env->isolate());
440
  // If this assert fires then Initialize hasn't been called yet.
441
28
  CHECK_EQ(env->udp_constructor_function().IsEmpty(), false);
442
28
  Local<Value> ptr = External::New(env->isolate(), parent);
443
28
  return scope.Escape(env->udp_constructor_function()
444
70
      ->NewInstance(env->context(), 1, &ptr).ToLocalChecked());
445
}
446
447
448
14
uv_udp_t* UDPWrap::UVHandle() {
449
14
  return &handle_;
450
}
451
452
453
}  // namespace node
454
455
1569
NODE_MODULE_CONTEXT_AWARE_BUILTIN(udp_wrap, node::UDPWrap::Initialize)