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

800
  if (!args[1]->Uint32Value(ctx).To(&port) ||
244
640
      !args[2]->Uint32Value(ctx).To(&flags))
245
    return;
246
  struct sockaddr_storage addr_storage;
247
160
  int err = sockaddr_for_family(family, address.out(), port, &addr_storage);
248
160
  if (err == 0) {
249
159
    err = uv_udp_bind(&wrap->handle_,
250
                      reinterpret_cast<const sockaddr*>(&addr_storage),
251
159
                      flags);
252
  }
253
254
160
  if (err == 0)
255
135
    wrap->listener()->OnAfterBind();
256
257
320
  args.GetReturnValue().Set(err);
258
}
259
260
261
13
void UDPWrap::DoConnect(const FunctionCallbackInfo<Value>& args, int family) {
262
  UDPWrap* wrap;
263
13
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
264
                          args.Holder(),
265
                          args.GetReturnValue().Set(UV_EBADF));
266
267
13
  CHECK_EQ(args.Length(), 2);
268
269
26
  node::Utf8Value address(args.GetIsolate(), args[0]);
270
13
  Local<Context> ctx = args.GetIsolate()->GetCurrentContext();
271
  uint32_t port;
272
39
  if (!args[1]->Uint32Value(ctx).To(&port))
273
    return;
274
  struct sockaddr_storage addr_storage;
275
13
  int err = sockaddr_for_family(family, address.out(), port, &addr_storage);
276
13
  if (err == 0) {
277
13
    err = uv_udp_connect(&wrap->handle_,
278
13
                         reinterpret_cast<const sockaddr*>(&addr_storage));
279
  }
280
281
26
  args.GetReturnValue().Set(err);
282
}
283
284
285
6
void UDPWrap::Open(const FunctionCallbackInfo<Value>& args) {
286
  UDPWrap* wrap;
287
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
288
                          args.Holder(),
289
                          args.GetReturnValue().Set(UV_EBADF));
290
12
  CHECK(args[0]->IsNumber());
291
18
  int fd = static_cast<int>(args[0].As<Integer>()->Value());
292
6
  int err = uv_udp_open(&wrap->handle_, fd);
293
294
12
  args.GetReturnValue().Set(err);
295
}
296
297
298
147
void UDPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
299
147
  DoBind(args, AF_INET);
300
147
}
301
302
303
13
void UDPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
304
13
  DoBind(args, AF_INET6);
305
13
}
306
307
308
30
void UDPWrap::BufferSize(const FunctionCallbackInfo<Value>& args) {
309
30
  Environment* env = Environment::GetCurrent(args);
310
  UDPWrap* wrap;
311
36
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
312
                          args.Holder(),
313
                          args.GetReturnValue().Set(UV_EBADF));
314
315
60
  CHECK(args[0]->IsUint32());
316
60
  CHECK(args[1]->IsBoolean());
317
90
  bool is_recv = args[1].As<v8::Boolean>()->Value();
318
  const char* uv_func_name = is_recv ? "uv_recv_buffer_size" :
319
30
                                       "uv_send_buffer_size";
320
321
60
  if (!args[0]->IsInt32()) {
322
2
    env->CollectUVExceptionInfo(args[2], UV_EINVAL, uv_func_name);
323
4
    return args.GetReturnValue().SetUndefined();
324
  }
325
326
28
  uv_handle_t* handle = reinterpret_cast<uv_handle_t*>(&wrap->handle_);
327
84
  int size = static_cast<int>(args[0].As<Uint32>()->Value());
328
  int err;
329
330
28
  if (is_recv)
331
15
    err = uv_recv_buffer_size(handle, &size);
332
  else
333
13
    err = uv_send_buffer_size(handle, &size);
334
335
28
  if (err != 0) {
336
4
    env->CollectUVExceptionInfo(args[2], err, uv_func_name);
337
8
    return args.GetReturnValue().SetUndefined();
338
  }
339
340
72
  args.GetReturnValue().Set(size);
341
}
342
343
344
13
void UDPWrap::Connect(const FunctionCallbackInfo<Value>& args) {
345
13
  DoConnect(args, AF_INET);
346
13
}
347
348
349
void UDPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
350
  DoConnect(args, AF_INET6);
351
}
352
353
354
1
void UDPWrap::Disconnect(const FunctionCallbackInfo<Value>& args) {
355
  UDPWrap* wrap;
356
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
357
                          args.Holder(),
358
                          args.GetReturnValue().Set(UV_EBADF));
359
360
1
  CHECK_EQ(args.Length(), 0);
361
362
1
  int err = uv_udp_connect(&wrap->handle_, nullptr);
363
364
2
  args.GetReturnValue().Set(err);
365
}
366
367
#define X(name, fn)                                                            \
368
  void UDPWrap::name(const FunctionCallbackInfo<Value>& args) {                \
369
    UDPWrap* wrap = Unwrap<UDPWrap>(args.Holder());                            \
370
    Environment* env = wrap->env();                                            \
371
    CHECK_EQ(args.Length(), 1);                                                \
372
    int flag;                                                                  \
373
    if (!args[0]->Int32Value(env->context()).To(&flag)) {                      \
374
      return;                                                                  \
375
    }                                                                          \
376
    int err = wrap == nullptr ? UV_EBADF : fn(&wrap->handle_, flag);           \
377
    args.GetReturnValue().Set(err);                                            \
378
  }
379
380
4
X(SetTTL, uv_udp_set_ttl)
381
10
X(SetBroadcast, uv_udp_set_broadcast)
382
10
X(SetMulticastTTL, uv_udp_set_multicast_ttl)
383

18
X(SetMulticastLoopback, uv_udp_set_multicast_loop)
384

27
385

22
#undef X
386

23
387
18
void UDPWrap::SetMulticastInterface(const FunctionCallbackInfo<Value>& args) {
388
  UDPWrap* wrap;
389
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
390
                          args.Holder(),
391
                          args.GetReturnValue().Set(UV_EBADF));
392
393
6
  CHECK_EQ(args.Length(), 1);
394
18
  CHECK(args[0]->IsString());
395
396
12
  Utf8Value iface(args.GetIsolate(), args[0]);
397
398
6
  const char* iface_cstr = *iface;
399
400
6
  int err = uv_udp_set_multicast_interface(&wrap->handle_, iface_cstr);
401
12
  args.GetReturnValue().Set(err);
402
}
403
404
2
void UDPWrap::SetMembership(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(), 2);
412
413
4
  node::Utf8Value address(args.GetIsolate(), args[0]);
414
4
  node::Utf8Value iface(args.GetIsolate(), args[1]);
415
416
2
  const char* iface_cstr = *iface;
417

6
  if (args[1]->IsUndefined() || args[1]->IsNull()) {
418
2
      iface_cstr = nullptr;
419
  }
420
421
2
  int err = uv_udp_set_membership(&wrap->handle_,
422
2
                                  *address,
423
                                  iface_cstr,
424
2
                                  membership);
425
4
  args.GetReturnValue().Set(err);
426
}
427
428
429
1
void UDPWrap::AddMembership(const FunctionCallbackInfo<Value>& args) {
430
1
  SetMembership(args, UV_JOIN_GROUP);
431
1
}
432
433
434
1
void UDPWrap::DropMembership(const FunctionCallbackInfo<Value>& args) {
435
1
  SetMembership(args, UV_LEAVE_GROUP);
436
1
}
437
438
2
void UDPWrap::SetSourceMembership(const FunctionCallbackInfo<Value>& args,
439
                                  uv_membership membership) {
440
  UDPWrap* wrap;
441
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
442
                          args.Holder(),
443
                          args.GetReturnValue().Set(UV_EBADF));
444
445
2
  CHECK_EQ(args.Length(), 3);
446
447
4
  node::Utf8Value source_address(args.GetIsolate(), args[0]);
448
4
  node::Utf8Value group_address(args.GetIsolate(), args[1]);
449
4
  node::Utf8Value iface(args.GetIsolate(), args[2]);
450
451
2
  if (*iface == nullptr) return;
452
2
  const char* iface_cstr = *iface;
453

6
  if (args[2]->IsUndefined() || args[2]->IsNull()) {
454
2
    iface_cstr = nullptr;
455
  }
456
457
2
  int err = uv_udp_set_source_membership(&wrap->handle_,
458
2
                                         *group_address,
459
                                         iface_cstr,
460
2
                                         *source_address,
461
2
                                         membership);
462
4
  args.GetReturnValue().Set(err);
463
}
464
465
1
void UDPWrap::AddSourceSpecificMembership(
466
  const FunctionCallbackInfo<Value>& args) {
467
1
  SetSourceMembership(args, UV_JOIN_GROUP);
468
1
}
469
470
471
1
void UDPWrap::DropSourceSpecificMembership(
472
  const FunctionCallbackInfo<Value>& args) {
473
1
  SetSourceMembership(args, UV_LEAVE_GROUP);
474
1
}
475
476
477
340
void UDPWrap::DoSend(const FunctionCallbackInfo<Value>& args, int family) {
478
340
  Environment* env = Environment::GetCurrent(args);
479
480
  UDPWrap* wrap;
481
340
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
482
                          args.Holder(),
483
                          args.GetReturnValue().Set(UV_EBADF));
484
485

664
  CHECK(args.Length() == 4 || args.Length() == 6);
486
680
  CHECK(args[0]->IsObject());
487
680
  CHECK(args[1]->IsArray());
488
680
  CHECK(args[2]->IsUint32());
489
490
340
  bool sendto = args.Length() == 6;
491
340
  if (sendto) {
492
    // send(req, list, list.length, port, address, hasCallback)
493
648
    CHECK(args[3]->IsUint32());
494
972
    CHECK(args[4]->IsString());
495
648
    CHECK(args[5]->IsBoolean());
496
  } else {
497
    // send(req, list, list.length, hasCallback)
498
32
    CHECK(args[3]->IsBoolean());
499
  }
500
501
680
  Local<Array> chunks = args[1].As<Array>();
502
  // it is faster to fetch the length of the
503
  // array in js-land
504
1020
  size_t count = args[2].As<Uint32>()->Value();
505
506
680
  MaybeStackBuffer<uv_buf_t, 16> bufs(count);
507
508
  // construct uv_buf_t array
509
689
  for (size_t i = 0; i < count; i++) {
510
    Local<Value> chunk;
511
1047
    if (!chunks->Get(env->context(), i).ToLocal(&chunk)) return;
512
513
349
    size_t length = Buffer::Length(chunk);
514
515
349
    bufs[i] = uv_buf_init(Buffer::Data(chunk), length);
516
  }
517
518
340
  int err = 0;
519
  struct sockaddr_storage addr_storage;
520
340
  sockaddr* addr = nullptr;
521
340
  if (sendto) {
522
972
    const unsigned short port = args[3].As<Uint32>()->Value();
523
648
    node::Utf8Value address(env->isolate(), args[4]);
524
324
    err = sockaddr_for_family(family, address.out(), port, &addr_storage);
525
324
    if (err == 0)
526
324
      addr = reinterpret_cast<sockaddr*>(&addr_storage);
527
  }
528
529
340
  if (err == 0) {
530
1020
    wrap->current_send_req_wrap_ = args[0].As<Object>();
531
680
    wrap->current_send_has_callback_ =
532
1360
        sendto ? args[5]->IsTrue() : args[3]->IsTrue();
533
534
340
    err = static_cast<int>(wrap->Send(*bufs, count, addr));
535
536
340
    wrap->current_send_req_wrap_.Clear();
537
340
    wrap->current_send_has_callback_ = false;
538
  }
539
540
680
  args.GetReturnValue().Set(err);
541
}
542
543
340
ssize_t UDPWrap::Send(uv_buf_t* bufs_ptr,
544
                      size_t count,
545
                      const sockaddr* addr) {
546
340
  if (IsHandleClosing()) return UV_EBADF;
547
548
340
  size_t msg_size = 0;
549
689
  for (size_t i = 0; i < count; i++)
550
349
    msg_size += bufs_ptr[i].len;
551
552
340
  int err = 0;
553
340
  if (!UNLIKELY(env()->options()->test_udp_no_try_send)) {
554
338
    err = uv_udp_try_send(&handle_, bufs_ptr, count, addr);
555

338
    if (err == UV_ENOSYS || err == UV_EAGAIN) {
556
      err = 0;
557
338
    } else if (err >= 0) {
558
337
      size_t sent = err;
559

1029
      while (count > 0 && bufs_ptr->len <= sent) {
560
346
        sent -= bufs_ptr->len;
561
346
        bufs_ptr++;
562
346
        count--;
563
      }
564
337
      if (count > 0) {
565
        CHECK_LT(sent, bufs_ptr->len);
566
        bufs_ptr->base += sent;
567
        bufs_ptr->len -= sent;
568
      } else {
569
337
        CHECK_EQ(static_cast<size_t>(err), msg_size);
570
        // + 1 so that the JS side can distinguish 0-length async sends from
571
        // 0-length sync sends.
572
337
        return msg_size + 1;
573
      }
574
    }
575
  }
576
577
3
  if (err == 0) {
578
4
    AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(this);
579
2
    ReqWrap<uv_udp_send_t>* req_wrap = listener()->CreateSendWrap(msg_size);
580
2
    if (req_wrap == nullptr) return UV_ENOSYS;
581
582
2
    err = req_wrap->Dispatch(
583
        uv_udp_send,
584
        &handle_,
585
        bufs_ptr,
586
        count,
587
        addr,
588
6
        uv_udp_send_cb{[](uv_udp_send_t* req, int status) {
589
2
          UDPWrap* self = ContainerOf(&UDPWrap::handle_, req->handle);
590
4
          self->listener()->OnSendDone(
591
4
              ReqWrap<uv_udp_send_t>::from_req(req), status);
592
8
        }});
593
2
    if (err)
594
      delete req_wrap;
595
  }
596
597
3
  return err;
598
}
599
600
601
2
ReqWrap<uv_udp_send_t>* UDPWrap::CreateSendWrap(size_t msg_size) {
602
2
  SendWrap* req_wrap = new SendWrap(env(),
603
4
                                    current_send_req_wrap_,
604
2
                                    current_send_has_callback_);
605
2
  req_wrap->msg_size = msg_size;
606
2
  return req_wrap;
607
}
608
609
610
303
void UDPWrap::Send(const FunctionCallbackInfo<Value>& args) {
611
303
  DoSend(args, AF_INET);
612
303
}
613
614
615
37
void UDPWrap::Send6(const FunctionCallbackInfo<Value>& args) {
616
37
  DoSend(args, AF_INET6);
617
37
}
618
619
620
AsyncWrap* UDPWrap::GetAsyncWrap() {
621
  return this;
622
}
623
624
SocketAddress UDPWrap::GetPeerName() {
625
  return SocketAddress::FromPeerName(handle_);
626
}
627
628
SocketAddress UDPWrap::GetSockName() {
629
  return SocketAddress::FromSockName(handle_);
630
}
631
632
144
void UDPWrapBase::RecvStart(const FunctionCallbackInfo<Value>& args) {
633
144
  UDPWrapBase* wrap = UDPWrapBase::FromObject(args.Holder());
634
432
  args.GetReturnValue().Set(wrap == nullptr ? UV_EBADF : wrap->RecvStart());
635
144
}
636
637
144
int UDPWrap::RecvStart() {
638
144
  if (IsHandleClosing()) return UV_EBADF;
639
144
  int err = uv_udp_recv_start(&handle_, OnAlloc, OnRecv);
640
  // UV_EALREADY means that the socket is already bound but that's okay
641
144
  if (err == UV_EALREADY)
642
    err = 0;
643
144
  return err;
644
}
645
646
647
132
void UDPWrapBase::RecvStop(const FunctionCallbackInfo<Value>& args) {
648
132
  UDPWrapBase* wrap = UDPWrapBase::FromObject(args.Holder());
649
396
  args.GetReturnValue().Set(wrap == nullptr ? UV_EBADF : wrap->RecvStop());
650
132
}
651
652
132
int UDPWrap::RecvStop() {
653
132
  if (IsHandleClosing()) return UV_EBADF;
654
132
  return uv_udp_recv_stop(&handle_);
655
}
656
657
658
2
void UDPWrap::OnSendDone(ReqWrap<uv_udp_send_t>* req, int status) {
659
4
  std::unique_ptr<SendWrap> req_wrap{static_cast<SendWrap*>(req)};
660
2
  if (req_wrap->have_callback()) {
661
2
    Environment* env = req_wrap->env();
662
4
    HandleScope handle_scope(env->isolate());
663
2
    Context::Scope context_scope(env->context());
664
    Local<Value> arg[] = {
665
      Integer::New(env->isolate(), status),
666
2
      Integer::New(env->isolate(), req_wrap->msg_size),
667
8
    };
668
2
    req_wrap->MakeCallback(env->oncomplete_string(), 2, arg);
669
  }
670
2
}
671
672
673
601
void UDPWrap::OnAlloc(uv_handle_t* handle,
674
                      size_t suggested_size,
675
                      uv_buf_t* buf) {
676
1202
  UDPWrap* wrap = ContainerOf(&UDPWrap::handle_,
677
601
                              reinterpret_cast<uv_udp_t*>(handle));
678
601
  *buf = wrap->listener()->OnAlloc(suggested_size);
679
601
}
680
681
601
uv_buf_t UDPWrap::OnAlloc(size_t suggested_size) {
682
601
  return AllocatedBuffer::AllocateManaged(env(), suggested_size).release();
683
}
684
685
601
void UDPWrap::OnRecv(uv_udp_t* handle,
686
                     ssize_t nread,
687
                     const uv_buf_t* buf,
688
                     const sockaddr* addr,
689
                     unsigned int flags) {
690
601
  UDPWrap* wrap = ContainerOf(&UDPWrap::handle_, handle);
691
601
  wrap->listener()->OnRecv(nread, *buf, addr, flags);
692
601
}
693
694
601
void UDPWrap::OnRecv(ssize_t nread,
695
                     const uv_buf_t& buf_,
696
                     const sockaddr* addr,
697
                     unsigned int flags) {
698
601
  Environment* env = this->env();
699
967
  AllocatedBuffer buf(env, buf_);
700

601
  if (nread == 0 && addr == nullptr) {
701
235
    return;
702
  }
703
704
732
  HandleScope handle_scope(env->isolate());
705
732
  Context::Scope context_scope(env->context());
706
707
  Local<Value> argv[] = {
708
      Integer::New(env->isolate(), static_cast<int32_t>(nread)),
709
      object(),
710
      Undefined(env->isolate()),
711
1830
      Undefined(env->isolate())};
712
713
366
  if (nread < 0) {
714
    MakeCallback(env->onmessage_string(), arraysize(argv), argv);
715
    return;
716
  }
717
718
366
  buf.Resize(nread);
719
732
  argv[2] = buf.ToBuffer().ToLocalChecked();
720
732
  argv[3] = AddressToJS(env, addr);
721
366
  MakeCallback(env->onmessage_string(), arraysize(argv), argv);
722
}
723
724
30
MaybeLocal<Object> UDPWrap::Instantiate(Environment* env,
725
                                        AsyncWrap* parent,
726
                                        UDPWrap::SocketType type) {
727
60
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(parent);
728
729
  // If this assert fires then Initialize hasn't been called yet.
730
60
  CHECK_EQ(env->udp_constructor_function().IsEmpty(), false);
731
90
  return env->udp_constructor_function()->NewInstance(env->context());
732
}
733
734
735
}  // namespace node
736
737

19020
NODE_MODULE_CONTEXT_AWARE_INTERNAL(udp_wrap, node::UDPWrap::Initialize)