GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: udp_wrap.cc Lines: 349 369 94.6 %
Date: 2022-02-05 04:14:12 Branches: 126 215 58.6 %

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

486
      !args[2]->Uint32Value(ctx).To(&flags))
248
    return;
249
  struct sockaddr_storage addr_storage;
250
162
  int err = sockaddr_for_family(family, address.out(), port, &addr_storage);
251
162
  if (err == 0) {
252
161
    err = uv_udp_bind(&wrap->handle_,
253
                      reinterpret_cast<const sockaddr*>(&addr_storage),
254
                      flags);
255
  }
256
257
162
  if (err == 0)
258
137
    wrap->listener()->OnAfterBind();
259
260
324
  args.GetReturnValue().Set(err);
261
}
262
263
264
13
void UDPWrap::DoConnect(const FunctionCallbackInfo<Value>& args, int family) {
265
  UDPWrap* wrap;
266
13
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
267
                          args.Holder(),
268
                          args.GetReturnValue().Set(UV_EBADF));
269
270
13
  CHECK_EQ(args.Length(), 2);
271
272
13
  node::Utf8Value address(args.GetIsolate(), args[0]);
273
13
  Local<Context> ctx = args.GetIsolate()->GetCurrentContext();
274
  uint32_t port;
275
26
  if (!args[1]->Uint32Value(ctx).To(&port))
276
    return;
277
  struct sockaddr_storage addr_storage;
278
13
  int err = sockaddr_for_family(family, address.out(), port, &addr_storage);
279
13
  if (err == 0) {
280
13
    err = uv_udp_connect(&wrap->handle_,
281
                         reinterpret_cast<const sockaddr*>(&addr_storage));
282
  }
283
284
26
  args.GetReturnValue().Set(err);
285
}
286
287
288
6
void UDPWrap::Open(const FunctionCallbackInfo<Value>& args) {
289
  UDPWrap* wrap;
290
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
291
                          args.Holder(),
292
                          args.GetReturnValue().Set(UV_EBADF));
293
6
  CHECK(args[0]->IsNumber());
294
12
  int fd = static_cast<int>(args[0].As<Integer>()->Value());
295
6
  int err = uv_udp_open(&wrap->handle_, fd);
296
297
12
  args.GetReturnValue().Set(err);
298
}
299
300
301
149
void UDPWrap::Bind(const FunctionCallbackInfo<Value>& args) {
302
149
  DoBind(args, AF_INET);
303
149
}
304
305
306
13
void UDPWrap::Bind6(const FunctionCallbackInfo<Value>& args) {
307
13
  DoBind(args, AF_INET6);
308
13
}
309
310
311
30
void UDPWrap::BufferSize(const FunctionCallbackInfo<Value>& args) {
312
30
  Environment* env = Environment::GetCurrent(args);
313
  UDPWrap* wrap;
314
36
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
315
                          args.Holder(),
316
                          args.GetReturnValue().Set(UV_EBADF));
317
318
30
  CHECK(args[0]->IsUint32());
319
30
  CHECK(args[1]->IsBoolean());
320
60
  bool is_recv = args[1].As<Boolean>()->Value();
321

30
  const char* uv_func_name = is_recv ? "uv_recv_buffer_size" :
322
                                       "uv_send_buffer_size";
323
324
30
  if (!args[0]->IsInt32()) {
325
2
    env->CollectUVExceptionInfo(args[2], UV_EINVAL, uv_func_name);
326
4
    return args.GetReturnValue().SetUndefined();
327
  }
328
329
28
  uv_handle_t* handle = reinterpret_cast<uv_handle_t*>(&wrap->handle_);
330
56
  int size = static_cast<int>(args[0].As<Uint32>()->Value());
331
  int err;
332
333
28
  if (is_recv)
334
15
    err = uv_recv_buffer_size(handle, &size);
335
  else
336
13
    err = uv_send_buffer_size(handle, &size);
337
338
28
  if (err != 0) {
339
4
    env->CollectUVExceptionInfo(args[2], err, uv_func_name);
340
8
    return args.GetReturnValue().SetUndefined();
341
  }
342
343
48
  args.GetReturnValue().Set(size);
344
}
345
346
347
13
void UDPWrap::Connect(const FunctionCallbackInfo<Value>& args) {
348
13
  DoConnect(args, AF_INET);
349
13
}
350
351
352
void UDPWrap::Connect6(const FunctionCallbackInfo<Value>& args) {
353
  DoConnect(args, AF_INET6);
354
}
355
356
357
1
void UDPWrap::Disconnect(const FunctionCallbackInfo<Value>& args) {
358
  UDPWrap* wrap;
359
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
360
                          args.Holder(),
361
                          args.GetReturnValue().Set(UV_EBADF));
362
363
1
  CHECK_EQ(args.Length(), 0);
364
365
1
  int err = uv_udp_connect(&wrap->handle_, nullptr);
366
367
2
  args.GetReturnValue().Set(err);
368
}
369
370
#define X(name, fn)                                                            \
371
  void UDPWrap::name(const FunctionCallbackInfo<Value>& args) {                \
372
    UDPWrap* wrap = Unwrap<UDPWrap>(args.Holder());                            \
373
    if (wrap == nullptr) {                                                     \
374
      args.GetReturnValue().Set(UV_EBADF);                                     \
375
      return;                                                                  \
376
    }                                                                          \
377
    Environment* env = wrap->env();                                            \
378
    CHECK_EQ(args.Length(), 1);                                                \
379
    int flag;                                                                  \
380
    if (!args[0]->Int32Value(env->context()).To(&flag)) {                      \
381
      return;                                                                  \
382
    }                                                                          \
383
    int err = fn(&wrap->handle_, flag);                                        \
384
    args.GetReturnValue().Set(err);                                            \
385
  }
386
387

14
X(SetTTL, uv_udp_set_ttl)
388

21
X(SetBroadcast, uv_udp_set_broadcast)
389

14
X(SetMulticastTTL, uv_udp_set_multicast_ttl)
390

21
X(SetMulticastLoopback, uv_udp_set_multicast_loop)
391
392
#undef X
393
394
6
void UDPWrap::SetMulticastInterface(const FunctionCallbackInfo<Value>& args) {
395
  UDPWrap* wrap;
396
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
397
                          args.Holder(),
398
                          args.GetReturnValue().Set(UV_EBADF));
399
400
6
  CHECK_EQ(args.Length(), 1);
401
12
  CHECK(args[0]->IsString());
402
403
6
  Utf8Value iface(args.GetIsolate(), args[0]);
404
405
6
  const char* iface_cstr = *iface;
406
407
6
  int err = uv_udp_set_multicast_interface(&wrap->handle_, iface_cstr);
408
12
  args.GetReturnValue().Set(err);
409
}
410
411
2
void UDPWrap::SetMembership(const FunctionCallbackInfo<Value>& args,
412
                            uv_membership membership) {
413
  UDPWrap* wrap;
414
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
415
                          args.Holder(),
416
                          args.GetReturnValue().Set(UV_EBADF));
417
418
2
  CHECK_EQ(args.Length(), 2);
419
420
4
  node::Utf8Value address(args.GetIsolate(), args[0]);
421
2
  node::Utf8Value iface(args.GetIsolate(), args[1]);
422
423
2
  const char* iface_cstr = *iface;
424

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

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

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

382
    if (err == UV_ENOSYS || err == UV_EAGAIN) {
563
      err = 0;
564
382
    } else if (err >= 0) {
565
381
      size_t sent = err;
566

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

520
  if (nread == 0 && addr == nullptr) {
709
143
    return;
710
  }
711
712
377
  HandleScope handle_scope(isolate);
713
377
  Context::Scope context_scope(env->context());
714
715
  Local<Value> argv[] = {
716
      Integer::New(isolate, static_cast<int32_t>(nread)),
717
      object(),
718
      Undefined(isolate),
719
1508
      Undefined(isolate)};
720
721
377
  if (nread < 0) {
722
    MakeCallback(env->onmessage_string(), arraysize(argv), argv);
723
    return;
724
377
  } else if (nread == 0) {
725
6
    bs = ArrayBuffer::NewBackingStore(isolate, 0);
726
  } else {
727
371
    CHECK_LE(static_cast<size_t>(nread), bs->ByteLength());
728
371
    bs = BackingStore::Reallocate(isolate, std::move(bs), nread);
729
  }
730
731
377
  Local<ArrayBuffer> ab = ArrayBuffer::New(isolate, std::move(bs));
732
754
  argv[2] = Buffer::New(env, ab, 0, ab->ByteLength()).ToLocalChecked();
733
377
  argv[3] = AddressToJS(env, addr);
734
377
  MakeCallback(env->onmessage_string(), arraysize(argv), argv);
735
}
736
737
29
MaybeLocal<Object> UDPWrap::Instantiate(Environment* env,
738
                                        AsyncWrap* parent,
739
                                        UDPWrap::SocketType type) {
740
29
  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(parent);
741
742
  // If this assert fires then Initialize hasn't been called yet.
743
58
  CHECK_EQ(env->udp_constructor_function().IsEmpty(), false);
744
58
  return env->udp_constructor_function()->NewInstance(env->context());
745
}
746
747
748
}  // namespace node
749
750
4989
NODE_MODULE_CONTEXT_AWARE_INTERNAL(udp_wrap, node::UDPWrap::Initialize)