GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/udp_wrap.cc Lines: 297 310 95.8 %
Date: 2020-02-27 22:14:15 Branches: 115 197 58.4 %

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 "udp_wrap.h"
23
#include "env-inl.h"
24
#include "node_buffer.h"
25
#include "handle_wrap.h"
26
#include "req_wrap-inl.h"
27
#include "util-inl.h"
28
29
namespace node {
30
31
using v8::Array;
32
using v8::Context;
33
using v8::DontDelete;
34
using v8::FunctionCallbackInfo;
35
using v8::FunctionTemplate;
36
using v8::HandleScope;
37
using v8::Integer;
38
using v8::Local;
39
using v8::MaybeLocal;
40
using v8::Object;
41
using v8::PropertyAttribute;
42
using v8::ReadOnly;
43
using v8::Signature;
44
using v8::String;
45
using v8::Uint32;
46
using v8::Undefined;
47
using v8::Value;
48
49
4
class SendWrap : public ReqWrap<uv_udp_send_t> {
50
 public:
51
  SendWrap(Environment* env, Local<Object> req_wrap_obj, bool have_callback);
52
  inline bool have_callback() const;
53
  size_t msg_size;
54
55
1
  SET_NO_MEMORY_INFO()
56
1
  SET_MEMORY_INFO_NAME(SendWrap)
57
1
  SET_SELF_SIZE(SendWrap)
58
59
 private:
60
  const bool have_callback_;
61
};
62
63
64
2
SendWrap::SendWrap(Environment* env,
65
                   Local<Object> req_wrap_obj,
66
2
                   bool have_callback)
67
    : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_UDPSENDWRAP),
68
2
      have_callback_(have_callback) {
69
2
}
70
71
72
2
inline bool SendWrap::have_callback() const {
73
2
  return have_callback_;
74
}
75
76
77
237
UDPWrap::UDPWrap(Environment* env, Local<Object> object)
78
    : HandleWrap(env,
79
                 object,
80
237
                 reinterpret_cast<uv_handle_t*>(&handle_),
81
237
                 AsyncWrap::PROVIDER_UDPWRAP) {
82
237
  int r = uv_udp_init(env->event_loop(), &handle_);
83
237
  CHECK_EQ(r, 0);  // can't fail anyway
84
237
}
85
86
87
3643
void UDPWrap::Initialize(Local<Object> target,
88
                         Local<Value> unused,
89
                         Local<Context> context,
90
                         void* priv) {
91
3643
  Environment* env = Environment::GetCurrent(context);
92
93
3643
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
94
7286
  t->InstanceTemplate()->SetInternalFieldCount(1);
95
  Local<String> udpString =
96
3643
      FIXED_ONE_BYTE_STRING(env->isolate(), "UDP");
97
3643
  t->SetClassName(udpString);
98
99
  enum PropertyAttribute attributes =
100
3643
      static_cast<PropertyAttribute>(ReadOnly | DontDelete);
101
102
3643
  Local<Signature> signature = Signature::New(env->isolate(), t);
103
104
  Local<FunctionTemplate> get_fd_templ =
105
      FunctionTemplate::New(env->isolate(),
106
                            UDPWrap::GetFD,
107
                            env->as_callback_data(),
108
7286
                            signature);
109
110
14572
  t->PrototypeTemplate()->SetAccessorProperty(env->fd_string(),
111
                                              get_fd_templ,
112
                                              Local<FunctionTemplate>(),
113
3643
                                              attributes);
114
115
3643
  env->SetProtoMethod(t, "open", Open);
116
3643
  env->SetProtoMethod(t, "bind", Bind);
117
3643
  env->SetProtoMethod(t, "connect", Connect);
118
3643
  env->SetProtoMethod(t, "send", Send);
119
3643
  env->SetProtoMethod(t, "bind6", Bind6);
120
3643
  env->SetProtoMethod(t, "connect6", Connect6);
121
3643
  env->SetProtoMethod(t, "send6", Send6);
122
3643
  env->SetProtoMethod(t, "disconnect", Disconnect);
123
3643
  env->SetProtoMethod(t, "recvStart", RecvStart);
124
3643
  env->SetProtoMethod(t, "recvStop", RecvStop);
125
  env->SetProtoMethod(t, "getpeername",
126
3643
                      GetSockOrPeerName<UDPWrap, uv_udp_getpeername>);
127
  env->SetProtoMethod(t, "getsockname",
128
3643
                      GetSockOrPeerName<UDPWrap, uv_udp_getsockname>);
129
3643
  env->SetProtoMethod(t, "addMembership", AddMembership);
130
3643
  env->SetProtoMethod(t, "dropMembership", DropMembership);
131
  env->SetProtoMethod(t, "addSourceSpecificMembership",
132
3643
                      AddSourceSpecificMembership);
133
  env->SetProtoMethod(t, "dropSourceSpecificMembership",
134
3643
                      DropSourceSpecificMembership);
135
3643
  env->SetProtoMethod(t, "setMulticastInterface", SetMulticastInterface);
136
3643
  env->SetProtoMethod(t, "setMulticastTTL", SetMulticastTTL);
137
3643
  env->SetProtoMethod(t, "setMulticastLoopback", SetMulticastLoopback);
138
3643
  env->SetProtoMethod(t, "setBroadcast", SetBroadcast);
139
3643
  env->SetProtoMethod(t, "setTTL", SetTTL);
140
3643
  env->SetProtoMethod(t, "bufferSize", BufferSize);
141
142
7286
  t->Inherit(HandleWrap::GetConstructorTemplate(env));
143
144
7286
  target->Set(env->context(),
145
              udpString,
146
18215
              t->GetFunction(env->context()).ToLocalChecked()).Check();
147
  env->set_udp_constructor_function(
148
10929
      t->GetFunction(env->context()).ToLocalChecked());
149
150
  // Create FunctionTemplate for SendWrap
151
  Local<FunctionTemplate> swt =
152
3643
      BaseObject::MakeLazilyInitializedJSTemplate(env);
153
7286
  swt->Inherit(AsyncWrap::GetConstructorTemplate(env));
154
  Local<String> sendWrapString =
155
3643
      FIXED_ONE_BYTE_STRING(env->isolate(), "SendWrap");
156
3643
  swt->SetClassName(sendWrapString);
157
7286
  target->Set(env->context(),
158
              sendWrapString,
159
18215
              swt->GetFunction(env->context()).ToLocalChecked()).Check();
160
161
3643
  Local<Object> constants = Object::New(env->isolate());
162
14572
  NODE_DEFINE_CONSTANT(constants, UV_UDP_IPV6ONLY);
163
7286
  target->Set(context,
164
              env->constants_string(),
165
10929
              constants).Check();
166
3643
}
167
168
169
237
void UDPWrap::New(const FunctionCallbackInfo<Value>& args) {
170
237
  CHECK(args.IsConstructCall());
171
237
  Environment* env = Environment::GetCurrent(args);
172
237
  new UDPWrap(env, args.This());
173
237
}
174
175
176
21
void UDPWrap::GetFD(const FunctionCallbackInfo<Value>& args) {
177
21
  int fd = UV_EBADF;
178
#if !defined(_WIN32)
179
21
  UDPWrap* wrap = Unwrap<UDPWrap>(args.This());
180
21
  if (wrap != nullptr)
181
20
    uv_fileno(reinterpret_cast<uv_handle_t*>(&wrap->handle_), &fd);
182
#endif
183
63
  args.GetReturnValue().Set(fd);
184
21
}
185
186
403
int sockaddr_for_family(int address_family,
187
                        const char* address,
188
                        const unsigned short port,
189
                        struct sockaddr_storage* addr) {
190
403
  switch (address_family) {
191
  case AF_INET:
192
386
    return uv_ip4_addr(address, port, reinterpret_cast<sockaddr_in*>(addr));
193
  case AF_INET6:
194
17
    return uv_ip6_addr(address, port, reinterpret_cast<sockaddr_in6*>(addr));
195
  default:
196
    CHECK(0 && "unexpected address family");
197
  }
198
}
199
200
147
void UDPWrap::DoBind(const FunctionCallbackInfo<Value>& args, int family) {
201
  UDPWrap* wrap;
202
147
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
203
                          args.Holder(),
204
                          args.GetReturnValue().Set(UV_EBADF));
205
206
  // bind(ip, port, flags)
207
147
  CHECK_EQ(args.Length(), 3);
208
209
294
  node::Utf8Value address(args.GetIsolate(), args[0]);
210
147
  Local<Context> ctx = args.GetIsolate()->GetCurrentContext();
211
  uint32_t port, flags;
212

735
  if (!args[1]->Uint32Value(ctx).To(&port) ||
213
588
      !args[2]->Uint32Value(ctx).To(&flags))
214
    return;
215
  struct sockaddr_storage addr_storage;
216
147
  int err = sockaddr_for_family(family, address.out(), port, &addr_storage);
217
147
  if (err == 0) {
218
146
    err = uv_udp_bind(&wrap->handle_,
219
                      reinterpret_cast<const sockaddr*>(&addr_storage),
220
146
                      flags);
221
  }
222
223
294
  args.GetReturnValue().Set(err);
224
}
225
226
227
13
void UDPWrap::DoConnect(const FunctionCallbackInfo<Value>& args, int family) {
228
  UDPWrap* wrap;
229
13
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
230
                          args.Holder(),
231
                          args.GetReturnValue().Set(UV_EBADF));
232
233
13
  CHECK_EQ(args.Length(), 2);
234
235
26
  node::Utf8Value address(args.GetIsolate(), args[0]);
236
13
  Local<Context> ctx = args.GetIsolate()->GetCurrentContext();
237
  uint32_t port;
238
39
  if (!args[1]->Uint32Value(ctx).To(&port))
239
    return;
240
  struct sockaddr_storage addr_storage;
241
13
  int err = sockaddr_for_family(family, address.out(), port, &addr_storage);
242
13
  if (err == 0) {
243
13
    err = uv_udp_connect(&wrap->handle_,
244
13
                         reinterpret_cast<const sockaddr*>(&addr_storage));
245
  }
246
247
26
  args.GetReturnValue().Set(err);
248
}
249
250
251
6
void UDPWrap::Open(const FunctionCallbackInfo<Value>& args) {
252
  UDPWrap* wrap;
253
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
254
                          args.Holder(),
255
                          args.GetReturnValue().Set(UV_EBADF));
256
12
  CHECK(args[0]->IsNumber());
257
18
  int fd = static_cast<int>(args[0].As<Integer>()->Value());
258
6
  int err = uv_udp_open(&wrap->handle_, fd);
259
260
12
  args.GetReturnValue().Set(err);
261
}
262
263
264
136
void UDPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
265
136
  DoBind(args, AF_INET);
266
136
}
267
268
269
11
void UDPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
270
11
  DoBind(args, AF_INET6);
271
11
}
272
273
274
30
void UDPWrap::BufferSize(const FunctionCallbackInfo<Value>& args) {
275
30
  Environment* env = Environment::GetCurrent(args);
276
  UDPWrap* wrap;
277
36
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
278
                          args.Holder(),
279
                          args.GetReturnValue().Set(UV_EBADF));
280
281
60
  CHECK(args[0]->IsUint32());
282
60
  CHECK(args[1]->IsBoolean());
283
90
  bool is_recv = args[1].As<v8::Boolean>()->Value();
284
  const char* uv_func_name = is_recv ? "uv_recv_buffer_size" :
285
30
                                       "uv_send_buffer_size";
286
287
60
  if (!args[0]->IsInt32()) {
288
2
    env->CollectUVExceptionInfo(args[2], UV_EINVAL, uv_func_name);
289
4
    return args.GetReturnValue().SetUndefined();
290
  }
291
292
28
  uv_handle_t* handle = reinterpret_cast<uv_handle_t*>(&wrap->handle_);
293
84
  int size = static_cast<int>(args[0].As<Uint32>()->Value());
294
  int err;
295
296
28
  if (is_recv)
297
15
    err = uv_recv_buffer_size(handle, &size);
298
  else
299
13
    err = uv_send_buffer_size(handle, &size);
300
301
28
  if (err != 0) {
302
4
    env->CollectUVExceptionInfo(args[2], err, uv_func_name);
303
8
    return args.GetReturnValue().SetUndefined();
304
  }
305
306
72
  args.GetReturnValue().Set(size);
307
}
308
309
310
13
void UDPWrap::Connect(const FunctionCallbackInfo<Value>& args) {
311
13
  DoConnect(args, AF_INET);
312
13
}
313
314
315
void UDPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
316
  DoConnect(args, AF_INET6);
317
}
318
319
320
1
void UDPWrap::Disconnect(const FunctionCallbackInfo<Value>& args) {
321
  UDPWrap* wrap;
322
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
323
                          args.Holder(),
324
                          args.GetReturnValue().Set(UV_EBADF));
325
326
1
  CHECK_EQ(args.Length(), 0);
327
328
1
  int err = uv_udp_connect(&wrap->handle_, nullptr);
329
330
2
  args.GetReturnValue().Set(err);
331
}
332
333
#define X(name, fn)                                                            \
334
  void UDPWrap::name(const FunctionCallbackInfo<Value>& args) {                \
335
    UDPWrap* wrap = Unwrap<UDPWrap>(args.Holder());                            \
336
    Environment* env = wrap->env();                                            \
337
    CHECK_EQ(args.Length(), 1);                                                \
338
    int flag;                                                                  \
339
    if (!args[0]->Int32Value(env->context()).To(&flag)) {                      \
340
      return;                                                                  \
341
    }                                                                          \
342
    int err = wrap == nullptr ? UV_EBADF : fn(&wrap->handle_, flag);           \
343
    args.GetReturnValue().Set(err);                                            \
344
  }
345
346

16
X(SetTTL, uv_udp_set_ttl)
347

24
X(SetBroadcast, uv_udp_set_broadcast)
348

16
X(SetMulticastTTL, uv_udp_set_multicast_ttl)
349

24
X(SetMulticastLoopback, uv_udp_set_multicast_loop)
350
351
#undef X
352
353
6
void UDPWrap::SetMulticastInterface(const FunctionCallbackInfo<Value>& args) {
354
  UDPWrap* wrap;
355
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
356
                          args.Holder(),
357
                          args.GetReturnValue().Set(UV_EBADF));
358
359
6
  CHECK_EQ(args.Length(), 1);
360
18
  CHECK(args[0]->IsString());
361
362
12
  Utf8Value iface(args.GetIsolate(), args[0]);
363
364
6
  const char* iface_cstr = *iface;
365
366
6
  int err = uv_udp_set_multicast_interface(&wrap->handle_, iface_cstr);
367
12
  args.GetReturnValue().Set(err);
368
}
369
370
2
void UDPWrap::SetMembership(const FunctionCallbackInfo<Value>& args,
371
                            uv_membership membership) {
372
  UDPWrap* wrap;
373
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
374
                          args.Holder(),
375
                          args.GetReturnValue().Set(UV_EBADF));
376
377
2
  CHECK_EQ(args.Length(), 2);
378
379
4
  node::Utf8Value address(args.GetIsolate(), args[0]);
380
4
  node::Utf8Value iface(args.GetIsolate(), args[1]);
381
382
2
  const char* iface_cstr = *iface;
383

6
  if (args[1]->IsUndefined() || args[1]->IsNull()) {
384
2
      iface_cstr = nullptr;
385
  }
386
387
2
  int err = uv_udp_set_membership(&wrap->handle_,
388
2
                                  *address,
389
                                  iface_cstr,
390
2
                                  membership);
391
4
  args.GetReturnValue().Set(err);
392
}
393
394
395
1
void UDPWrap::AddMembership(const FunctionCallbackInfo<Value>& args) {
396
1
  SetMembership(args, UV_JOIN_GROUP);
397
1
}
398
399
400
1
void UDPWrap::DropMembership(const FunctionCallbackInfo<Value>& args) {
401
1
  SetMembership(args, UV_LEAVE_GROUP);
402
1
}
403
404
2
void UDPWrap::SetSourceMembership(const FunctionCallbackInfo<Value>& args,
405
                                  uv_membership membership) {
406
  UDPWrap* wrap;
407
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
408
                          args.Holder(),
409
                          args.GetReturnValue().Set(UV_EBADF));
410
411
2
  CHECK_EQ(args.Length(), 3);
412
413
4
  node::Utf8Value source_address(args.GetIsolate(), args[0]);
414
4
  node::Utf8Value group_address(args.GetIsolate(), args[1]);
415
4
  node::Utf8Value iface(args.GetIsolate(), args[2]);
416
417
2
  if (*iface == nullptr) return;
418
2
  const char* iface_cstr = *iface;
419

6
  if (args[2]->IsUndefined() || args[2]->IsNull()) {
420
2
    iface_cstr = nullptr;
421
  }
422
423
2
  int err = uv_udp_set_source_membership(&wrap->handle_,
424
2
                                         *group_address,
425
                                         iface_cstr,
426
2
                                         *source_address,
427
2
                                         membership);
428
4
  args.GetReturnValue().Set(err);
429
}
430
431
1
void UDPWrap::AddSourceSpecificMembership(
432
  const FunctionCallbackInfo<Value>& args) {
433
1
  SetSourceMembership(args, UV_JOIN_GROUP);
434
1
}
435
436
437
1
void UDPWrap::DropSourceSpecificMembership(
438
  const FunctionCallbackInfo<Value>& args) {
439
1
  SetSourceMembership(args, UV_LEAVE_GROUP);
440
1
}
441
442
443
259
void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
444
259
  Environment* env = Environment::GetCurrent(args);
445
446
  UDPWrap* wrap;
447
515
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
448
                          args.Holder(),
449
                          args.GetReturnValue().Set(UV_EBADF));
450
451

502
  CHECK(args.Length() == 4 || args.Length() == 6);
452
518
  CHECK(args[0]->IsObject());
453
518
  CHECK(args[1]->IsArray());
454
518
  CHECK(args[2]->IsUint32());
455
456
259
  bool sendto = args.Length() == 6;
457
259
  if (sendto) {
458
    // send(req, list, list.length, port, address, hasCallback)
459
486
    CHECK(args[3]->IsUint32());
460
729
    CHECK(args[4]->IsString());
461
486
    CHECK(args[5]->IsBoolean());
462
  } else {
463
    // send(req, list, list.length, hasCallback)
464
32
    CHECK(args[3]->IsBoolean());
465
  }
466
467
518
  Local<Object> req_wrap_obj = args[0].As<Object>();
468
518
  Local<Array> chunks = args[1].As<Array>();
469
  // it is faster to fetch the length of the
470
  // array in js-land
471
777
  size_t count = args[2].As<Uint32>()->Value();
472
777
  const bool have_callback = sendto ? args[5]->IsTrue() : args[3]->IsTrue();
473
474
259
  size_t msg_size = 0;
475
476
262
  MaybeStackBuffer<uv_buf_t, 16> bufs(count);
477
478
  // construct uv_buf_t array
479
527
  for (size_t i = 0; i < count; i++) {
480
804
    Local<Value> chunk = chunks->Get(env->context(), i).ToLocalChecked();
481
482
268
    size_t length = Buffer::Length(chunk);
483
484
268
    bufs[i] = uv_buf_init(Buffer::Data(chunk), length);
485
268
    msg_size += length;
486
  }
487
488
259
  int err = 0;
489
  struct sockaddr_storage addr_storage;
490
259
  sockaddr* addr = nullptr;
491
259
  if (sendto) {
492
729
    const unsigned short port = args[3].As<Uint32>()->Value();
493
486
    node::Utf8Value address(env->isolate(), args[4]);
494
243
    err = sockaddr_for_family(family, address.out(), port, &addr_storage);
495
243
    if (err == 0) {
496
243
      addr = reinterpret_cast<sockaddr*>(&addr_storage);
497
    }
498
  }
499
500
259
  uv_buf_t* bufs_ptr = *bufs;
501


259
  if (err == 0 && !UNLIKELY(env->options()->test_udp_no_try_send)) {
502
257
    err = uv_udp_try_send(&wrap->handle_, bufs_ptr, count, addr);
503

257
    if (err == UV_ENOSYS || err == UV_EAGAIN) {
504
      err = 0;
505
257
    } else if (err >= 0) {
506
256
      size_t sent = err;
507

786
      while (count > 0 && bufs_ptr->len <= sent) {
508
265
        sent -= bufs_ptr->len;
509
265
        bufs_ptr++;
510
265
        count--;
511
      }
512
256
      if (count > 0) {
513
        CHECK_LT(sent, bufs_ptr->len);
514
        bufs_ptr->base += sent;
515
        bufs_ptr->len -= sent;
516
      } else {
517
256
        CHECK_EQ(static_cast<size_t>(err), msg_size);
518
        // + 1 so that the JS side can distinguish 0-length async sends from
519
        // 0-length sync sends.
520
768
        args.GetReturnValue().Set(static_cast<uint32_t>(msg_size) + 1);
521
256
        return;
522
      }
523
    }
524
  }
525
526
3
  if (err == 0) {
527
4
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(wrap);
528
2
    SendWrap* req_wrap = new SendWrap(env, req_wrap_obj, have_callback);
529
2
    req_wrap->msg_size = msg_size;
530
531
2
    err = req_wrap->Dispatch(uv_udp_send,
532
2
                             &wrap->handle_,
533
                             bufs_ptr,
534
                             count,
535
                             addr,
536
2
                             OnSend);
537
2
    if (err)
538
      delete req_wrap;
539
  }
540
541
6
  args.GetReturnValue().Set(err);
542
}
543
544
545
253
void UDPWrap::Send(const FunctionCallbackInfo<Value>& args) {
546
253
  DoSend(args, AF_INET);
547
253
}
548
549
550
6
void UDPWrap::Send6(const FunctionCallbackInfo<Value>& args) {
551
6
  DoSend(args, AF_INET6);
552
6
}
553
554
555
129
void UDPWrap::RecvStart(const FunctionCallbackInfo<Value>& args) {
556
  UDPWrap* wrap;
557
129
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
558
                          args.Holder(),
559
                          args.GetReturnValue().Set(UV_EBADF));
560
129
  int err = uv_udp_recv_start(&wrap->handle_, OnAlloc, OnRecv);
561
  // UV_EALREADY means that the socket is already bound but that's okay
562
129
  if (err == UV_EALREADY)
563
    err = 0;
564
258
  args.GetReturnValue().Set(err);
565
}
566
567
568
118
void UDPWrap::RecvStop(const FunctionCallbackInfo<Value>& args) {
569
  UDPWrap* wrap;
570
118
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
571
                          args.Holder(),
572
                          args.GetReturnValue().Set(UV_EBADF));
573
118
  int r = uv_udp_recv_stop(&wrap->handle_);
574
236
  args.GetReturnValue().Set(r);
575
}
576
577
578
2
void UDPWrap::OnSend(uv_udp_send_t* req, int status) {
579
4
  std::unique_ptr<SendWrap> req_wrap{static_cast<SendWrap*>(req->data)};
580
2
  if (req_wrap->have_callback()) {
581
2
    Environment* env = req_wrap->env();
582
4
    HandleScope handle_scope(env->isolate());
583
2
    Context::Scope context_scope(env->context());
584
    Local<Value> arg[] = {
585
      Integer::New(env->isolate(), status),
586
2
      Integer::New(env->isolate(), req_wrap->msg_size),
587
8
    };
588
2
    req_wrap->MakeCallback(env->oncomplete_string(), 2, arg);
589
  }
590
2
}
591
592
593
425
void UDPWrap::OnAlloc(uv_handle_t* handle,
594
                      size_t suggested_size,
595
                      uv_buf_t* buf) {
596
425
  UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
597
425
  *buf = wrap->env()->AllocateManaged(suggested_size).release();
598
425
}
599
600
425
void UDPWrap::OnRecv(uv_udp_t* handle,
601
                     ssize_t nread,
602
                     const uv_buf_t* buf_,
603
                     const struct sockaddr* addr,
604
                     unsigned int flags) {
605
425
  UDPWrap* wrap = static_cast<UDPWrap*>(handle->data);
606
425
  Environment* env = wrap->env();
607
608
668
  AllocatedBuffer buf(env, *buf_);
609

425
  if (nread == 0 && addr == nullptr) {
610
182
    return;
611
  }
612
613
486
  HandleScope handle_scope(env->isolate());
614
486
  Context::Scope context_scope(env->context());
615
616
243
  Local<Object> wrap_obj = wrap->object();
617
  Local<Value> argv[] = {
618
    Integer::New(env->isolate(), nread),
619
    wrap_obj,
620
    Undefined(env->isolate()),
621
    Undefined(env->isolate())
622
1215
  };
623
624
243
  if (nread < 0) {
625
    wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
626
    return;
627
  }
628
629
243
  buf.Resize(nread);
630
486
  argv[2] = buf.ToBuffer().ToLocalChecked();
631
486
  argv[3] = AddressToJS(env, addr);
632
243
  wrap->MakeCallback(env->onmessage_string(), arraysize(argv), argv);
633
}
634
635
24
MaybeLocal<Object> UDPWrap::Instantiate(Environment* env,
636
                                        AsyncWrap* parent,
637
                                        UDPWrap::SocketType type) {
638
48
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(parent);
639
640
  // If this assert fires then Initialize hasn't been called yet.
641
48
  CHECK_EQ(env->udp_constructor_function().IsEmpty(), false);
642
72
  return env->udp_constructor_function()->NewInstance(env->context());
643
}
644
645
646
}  // namespace node
647
648
4201
NODE_MODULE_CONTEXT_AWARE_INTERNAL(udp_wrap, node::UDPWrap::Initialize)