GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: udp_wrap.cc Lines: 348 368 94.6 %
Date: 2021-09-29 04:12:34 Branches: 125 213 58.7 %

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

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

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

12
X(SetTTL, uv_udp_set_ttl)
385

18
X(SetBroadcast, uv_udp_set_broadcast)
386

12
X(SetMulticastTTL, uv_udp_set_multicast_ttl)
387

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

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

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

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

385
    if (err == UV_ENOSYS || err == UV_EAGAIN) {
560
      err = 0;
561
385
    } else if (err >= 0) {
562
384
      size_t sent = err;
563

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

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