/
dgram.ts
1540 lines (1317 loc) · 43.2 KB
/
dgram.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
import { Buffer } from "./buffer.ts";
import { EventEmitter } from "./events.ts";
import { lookup as defaultLookup } from "./dns.ts";
import type { ErrnoException, NodeSystemErrorCtx } from "./internal/errors.ts";
import {
ERR_BUFFER_OUT_OF_BOUNDS,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_FD_TYPE,
ERR_MISSING_ARGS,
ERR_SOCKET_ALREADY_BOUND,
ERR_SOCKET_BAD_BUFFER_SIZE,
ERR_SOCKET_BUFFER_SIZE,
ERR_SOCKET_DGRAM_IS_CONNECTED,
ERR_SOCKET_DGRAM_NOT_CONNECTED,
ERR_SOCKET_DGRAM_NOT_RUNNING,
errnoException,
exceptionWithHostPort,
} from "./internal/errors.ts";
import type { Abortable } from "./_events.d.ts";
import { kStateSymbol, newHandle } from "./internal/dgram.ts";
import type { SocketType } from "./internal/dgram.ts";
import {
asyncIdSymbol,
defaultTriggerAsyncIdScope,
ownerSymbol,
} from "./internal/async_hooks.ts";
import { SendWrap, UDP } from "./internal_binding/udp_wrap.ts";
import {
isInt32,
validateAbortSignal,
validateNumber,
validatePort,
validateString,
} from "./internal/validators.mjs";
import { guessHandleType } from "./internal_binding/util.ts";
import { os } from "./internal_binding/constants.ts";
import { nextTick } from "./process.ts";
import { isArrayBufferView } from "./internal/util/types.ts";
const { UV_UDP_REUSEADDR, UV_UDP_IPV6ONLY } = os;
const BIND_STATE_UNBOUND = 0;
const BIND_STATE_BINDING = 1;
const BIND_STATE_BOUND = 2;
const CONNECT_STATE_DISCONNECTED = 0;
const CONNECT_STATE_CONNECTING = 1;
const CONNECT_STATE_CONNECTED = 2;
const RECV_BUFFER = true;
const SEND_BUFFER = false;
export interface AddressInfo {
address: string;
family: number;
port: number;
}
export type MessageType = string | Uint8Array | Buffer | DataView;
export type RemoteInfo = {
address: string;
family: "IPv4" | "IPv6";
port: number;
size?: number;
};
export interface BindOptions {
port?: number;
address?: string;
exclusive?: boolean;
fd?: number;
}
export interface SocketOptions extends Abortable {
type: SocketType;
reuseAddr?: boolean;
/**
* @default false
*/
ipv6Only?: boolean;
recvBufferSize?: number;
sendBufferSize?: number;
lookup?: typeof defaultLookup;
}
interface SocketInternalState {
handle: UDP | null;
receiving: boolean;
bindState:
| typeof BIND_STATE_UNBOUND
| typeof BIND_STATE_BINDING
| typeof BIND_STATE_BOUND;
connectState:
| typeof CONNECT_STATE_DISCONNECTED
| typeof CONNECT_STATE_CONNECTING
| typeof CONNECT_STATE_CONNECTED;
queue?: Array<() => void>;
reuseAddr?: boolean;
ipv6Only?: boolean;
recvBufferSize?: number;
sendBufferSize?: number;
}
const isSocketOptions = (
socketOption: unknown,
): socketOption is SocketOptions =>
socketOption !== null && typeof socketOption === "object";
const isUdpHandle = (handle: unknown): handle is UDP =>
handle !== null &&
typeof handle === "object" &&
typeof (handle as UDP).recvStart === "function";
const isBindOptions = (options: unknown): options is BindOptions =>
options !== null && typeof options === "object";
/**
* Encapsulates the datagram functionality.
*
* New instances of `dgram.Socket` are created using `createSocket`.
* The `new` keyword is not to be used to create `dgram.Socket` instances.
*/
export class Socket extends EventEmitter {
[asyncIdSymbol]!: number;
[kStateSymbol]!: SocketInternalState;
type!: SocketType;
constructor(
type: SocketType | SocketOptions,
listener?: (msg: Buffer, rinfo: RemoteInfo) => void,
) {
super();
let lookup;
let recvBufferSize;
let sendBufferSize;
let options: SocketOptions | undefined;
if (isSocketOptions(type)) {
options = type;
type = options.type;
lookup = options.lookup;
recvBufferSize = options.recvBufferSize;
sendBufferSize = options.sendBufferSize;
}
const handle = newHandle(type, lookup);
handle[ownerSymbol] = this;
this[asyncIdSymbol] = handle.getAsyncId();
this.type = type;
if (typeof listener === "function") {
this.on("message", listener);
}
this[kStateSymbol] = {
handle,
receiving: false,
bindState: BIND_STATE_UNBOUND,
connectState: CONNECT_STATE_DISCONNECTED,
queue: undefined,
reuseAddr: options && options.reuseAddr, // Use UV_UDP_REUSEADDR if true.
ipv6Only: options && options.ipv6Only,
recvBufferSize,
sendBufferSize,
};
if (options?.signal !== undefined) {
const { signal } = options;
validateAbortSignal(signal, "options.signal");
const onAborted = () => {
this.close();
};
if (signal.aborted) {
onAborted();
} else {
signal.addEventListener("abort", onAborted);
this.once(
"close",
() => signal.removeEventListener("abort", onAborted),
);
}
}
}
/**
* Tells the kernel to join a multicast group at the given `multicastAddress`
* and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If
* the`multicastInterface` argument is not specified, the operating system
* will choose one interface and will add membership to it. To add membership
* to every available interface, call `addMembership` multiple times, once
* per interface.
*
* When called on an unbound socket, this method will implicitly bind to a
* random port, listening on all interfaces.
*
* When sharing a UDP socket across multiple `cluster` workers, the
* `socket.addMembership()` function must be called only once or an
* `EADDRINUSE` error will occur:
*
* ```js
* import cluster from 'cluster';
* import dgram from 'dgram';
*
* if (cluster.isPrimary) {
* cluster.fork(); // Works ok.
* cluster.fork(); // Fails with EADDRINUSE.
* } else {
* const s = dgram.createSocket('udp4');
* s.bind(1234, () => {
* s.addMembership('224.0.0.114');
* });
* }
* ```
*/
addMembership(multicastAddress: string, interfaceAddress?: string): void {
healthCheck(this);
if (!multicastAddress) {
throw new ERR_MISSING_ARGS("multicastAddress");
}
const { handle } = this[kStateSymbol];
const err = handle!.addMembership(multicastAddress, interfaceAddress);
if (err) {
throw errnoException(err, "addMembership");
}
}
/**
* Tells the kernel to join a source-specific multicast channel at the given
* `sourceAddress` and `groupAddress`, using the `multicastInterface` with
* the `IP_ADD_SOURCE_MEMBERSHIP` socket option. If the `multicastInterface`
* argument is not specified, the operating system will choose one interface
* and will add membership to it. To add membership to every available
* interface, call `socket.addSourceSpecificMembership()` multiple times,
* once per interface.
*
* When called on an unbound socket, this method will implicitly bind to a
* random port, listening on all interfaces.
*/
addSourceSpecificMembership(
sourceAddress: string,
groupAddress: string,
interfaceAddress?: string,
): void {
healthCheck(this);
validateString(sourceAddress, "sourceAddress");
validateString(groupAddress, "groupAddress");
const err = this[kStateSymbol].handle!.addSourceSpecificMembership(
sourceAddress,
groupAddress,
interfaceAddress,
);
if (err) {
throw errnoException(err, "addSourceSpecificMembership");
}
}
/**
* Returns an object containing the address information for a socket.
* For UDP sockets, this object will contain `address`, `family` and `port`properties.
*
* This method throws `EBADF` if called on an unbound socket.
*/
address(): AddressInfo {
healthCheck(this);
const out = {};
const err = this[kStateSymbol].handle!.getsockname(out);
if (err) {
throw errnoException(err, "getsockname");
}
return out as AddressInfo;
}
/**
* For UDP sockets, causes the `dgram.Socket` to listen for datagram
* messages on a named `port` and optional `address`. If `port` is not
* specified or is `0`, the operating system will attempt to bind to a
* random port. If `address` is not specified, the operating system will
* attempt to listen on all addresses. Once binding is complete, a
* `'listening'` event is emitted and the optional `callback` function is
* called.
*
* Specifying both a `'listening'` event listener and passing a `callback` to
* the `socket.bind()` method is not harmful but not very useful.
*
* A bound datagram socket keeps the Node.js process running to receive
* datagram messages.
*
* If binding fails, an `'error'` event is generated. In rare case (e.g.
* attempting to bind with a closed socket), an `Error` may be thrown.
*
* Example of a UDP server listening on port 41234:
*
* ```js
* import dgram from 'dgram';
*
* const server = dgram.createSocket('udp4');
*
* server.on('error', (err) => {
* console.log(`server error:\n${err.stack}`);
* server.close();
* });
*
* server.on('message', (msg, rinfo) => {
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
* });
*
* server.on('listening', () => {
* const address = server.address();
* console.log(`server listening ${address.address}:${address.port}`);
* });
*
* server.bind(41234);
* // Prints: server listening 0.0.0.0:41234
* ```
*
* @param callback with no parameters. Called when binding is complete.
*/
bind(port?: number, address?: string, callback?: () => void): this;
bind(port: number, callback?: () => void): this;
bind(callback: () => void): this;
bind(options: BindOptions, callback?: () => void): this;
bind(port_?: unknown, address_?: unknown /* callback */): this {
let port = typeof port_ === "function" ? null : port_;
healthCheck(this);
const state = this[kStateSymbol];
if (state.bindState !== BIND_STATE_UNBOUND) {
throw new ERR_SOCKET_ALREADY_BOUND();
}
state.bindState = BIND_STATE_BINDING;
const cb = arguments.length && arguments[arguments.length - 1];
if (typeof cb === "function") {
// deno-lint-ignore no-inner-declarations
function removeListeners(this: Socket) {
this.removeListener("error", removeListeners);
this.removeListener("listening", onListening);
}
// deno-lint-ignore no-inner-declarations
function onListening(this: Socket) {
removeListeners.call(this);
cb.call(this);
}
this.on("error", removeListeners);
this.on("listening", onListening);
}
if (isUdpHandle(port)) {
replaceHandle(this, port);
startListening(this);
return this;
}
// Open an existing fd instead of creating a new one.
if (isBindOptions(port) && isInt32(port.fd!) && port.fd! > 0) {
const fd = port.fd!;
const state = this[kStateSymbol];
// TODO(cmorten): here we deviate somewhat from the Node implementation which
// makes use of the https://nodejs.org/api/cluster.html module to run servers
// across a "cluster" of Node processes to take advantage of multi-core
// systems.
//
// Though Deno has has a Worker capability from which we could simulate this,
// for now we assert that we are _always_ on the primary process.
const type = guessHandleType(fd);
if (type !== "UDP") {
throw new ERR_INVALID_FD_TYPE(type);
}
const err = state.handle!.open(fd);
if (err) {
throw errnoException(err, "open");
}
startListening(this);
return this;
}
let address: string;
if (isBindOptions(port)) {
address = port.address || "";
port = port.port;
} else {
address = typeof address_ === "function" ? "" : (address_ as string);
}
// Defaulting address for bind to all interfaces
if (!address) {
if (this.type === "udp4") {
address = "0.0.0.0";
} else {
address = "::";
}
}
// Resolve address first
state.handle!.lookup(address, (lookupError, ip) => {
if (lookupError) {
state.bindState = BIND_STATE_UNBOUND;
this.emit("error", lookupError);
return;
}
let flags = 0;
if (state.reuseAddr) {
flags |= UV_UDP_REUSEADDR;
}
if (state.ipv6Only) {
flags |= UV_UDP_IPV6ONLY;
}
// TODO(cmorten): here we deviate somewhat from the Node implementation which
// makes use of the https://nodejs.org/api/cluster.html module to run servers
// across a "cluster" of Node processes to take advantage of multi-core
// systems.
//
// Though Deno has has a Worker capability from which we could simulate this,
// for now we assert that we are _always_ on the primary process.
if (!state.handle) {
return; // Handle has been closed in the mean time
}
const err = state.handle.bind(ip, port as number || 0, flags);
if (err) {
const ex = exceptionWithHostPort(err, "bind", ip, port as number);
state.bindState = BIND_STATE_UNBOUND;
this.emit("error", ex);
// Todo: close?
return;
}
startListening(this);
});
return this;
}
/**
* Close the underlying socket and stop listening for data on it. If a
* callback is provided, it is added as a listener for the `'close'` event.
*
* @param callback Called when the socket has been closed.
*/
close(callback?: () => void): this {
const state = this[kStateSymbol];
const queue = state.queue;
if (typeof callback === "function") {
this.on("close", callback);
}
if (queue !== undefined) {
queue.push(this.close.bind(this));
return this;
}
healthCheck(this);
stopReceiving(this);
state.handle!.close();
state.handle = null;
defaultTriggerAsyncIdScope(
this[asyncIdSymbol],
nextTick,
socketCloseNT,
this,
);
return this;
}
/**
* Associates the `dgram.Socket` to a remote address and port. Every
* message sent by this handle is automatically sent to that destination.
* Also, the socket will only receive messages from that remote peer.
* Trying to call `connect()` on an already connected socket will result
* in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not
* provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets)
* will be used by default. Once the connection is complete, a `'connect'` event
* is emitted and the optional `callback` function is called. In case of failure,
* the `callback` is called or, failing this, an `'error'` event is emitted.
*
* @param callback Called when the connection is completed or on error.
*/
connect(
port: number,
address?: string,
callback?: (err?: ErrnoException) => void,
): void;
connect(port: number, callback: (err?: ErrnoException) => void): void;
connect(port: number, address?: unknown, callback?: unknown): void {
port = validatePort(port, "Port", false);
if (typeof address === "function") {
callback = address;
address = "";
} else if (address === undefined) {
address = "";
}
validateString(address, "address");
const state = this[kStateSymbol];
if (state.connectState !== CONNECT_STATE_DISCONNECTED) {
throw new ERR_SOCKET_DGRAM_IS_CONNECTED();
}
state.connectState = CONNECT_STATE_CONNECTING;
if (state.bindState === BIND_STATE_UNBOUND) {
this.bind({ port: 0, exclusive: true });
}
if (state.bindState !== BIND_STATE_BOUND) {
enqueue(
this,
_connect.bind(
this,
port,
address as string,
callback as (err?: ErrnoException) => void,
),
);
return;
}
Reflect.apply(_connect, this, [port, address, callback]);
}
/**
* A synchronous function that disassociates a connected `dgram.Socket` from
* its remote address. Trying to call `disconnect()` on an unbound or already
* disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED`
* exception.
*/
disconnect(): void {
const state = this[kStateSymbol];
if (state.connectState !== CONNECT_STATE_CONNECTED) {
throw new ERR_SOCKET_DGRAM_NOT_CONNECTED();
}
const err = state.handle!.disconnect();
if (err) {
throw errnoException(err, "connect");
} else {
state.connectState = CONNECT_STATE_DISCONNECTED;
}
}
/**
* Instructs the kernel to leave a multicast group at `multicastAddress`
* using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically
* called by the kernel when the socket is closed or the process terminates,
* so most apps will never have reason to call this.
*
* If `multicastInterface` is not specified, the operating system will
* attempt to drop membership on all valid interfaces.
*/
dropMembership(multicastAddress: string, interfaceAddress?: string): void {
healthCheck(this);
if (!multicastAddress) {
throw new ERR_MISSING_ARGS("multicastAddress");
}
const err = this[kStateSymbol].handle!.dropMembership(
multicastAddress,
interfaceAddress,
);
if (err) {
throw errnoException(err, "dropMembership");
}
}
/**
* Instructs the kernel to leave a source-specific multicast channel at the
* given `sourceAddress` and `groupAddress` using the
* `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is automatically
* called by the kernel when the socket is closed or the process terminates,
* so most apps will never have reason to call this.
*
* If `multicastInterface` is not specified, the operating system will
* attempt to drop membership on all valid interfaces.
*/
dropSourceSpecificMembership(
sourceAddress: string,
groupAddress: string,
interfaceAddress?: string,
): void {
healthCheck(this);
validateString(sourceAddress, "sourceAddress");
validateString(groupAddress, "groupAddress");
const err = this[kStateSymbol].handle!.dropSourceSpecificMembership(
sourceAddress,
groupAddress,
interfaceAddress,
);
if (err) {
throw errnoException(err, "dropSourceSpecificMembership");
}
}
/**
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound
* socket.
*
* @return the `SO_RCVBUF` socket receive buffer size in bytes.
*/
getRecvBufferSize(): number {
return bufferSize(this, 0, RECV_BUFFER);
}
/**
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound
* socket.
*
* @return the `SO_SNDBUF` socket send buffer size in bytes.
*/
getSendBufferSize(): number {
return bufferSize(this, 0, SEND_BUFFER);
}
/**
* By default, binding a socket will cause it to block the Node.js process
* from exiting as long as the socket is open. The `socket.unref()` method
* can be used to exclude the socket from the reference counting that keeps
* the Node.js process active. The `socket.ref()` method adds the socket back
* to the reference counting and restores the default behavior.
*
* Calling `socket.ref()` multiples times will have no additional effect.
*
* The `socket.ref()` method returns a reference to the socket so calls can
* be chained.
*/
ref(): this {
const handle = this[kStateSymbol].handle;
if (handle) {
handle.ref();
}
return this;
}
/**
* Returns an object containing the `address`, `family`, and `port` of the
* remote endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED`
* exception if the socket is not connected.
*/
remoteAddress(): AddressInfo {
healthCheck(this);
const state = this[kStateSymbol];
if (state.connectState !== CONNECT_STATE_CONNECTED) {
throw new ERR_SOCKET_DGRAM_NOT_CONNECTED();
}
const out = {};
const err = state.handle!.getpeername(out);
if (err) {
throw errnoException(err, "getpeername");
}
return out as AddressInfo;
}
/**
* Broadcasts a datagram on the socket.
* For connectionless sockets, the destination `port` and `address` must be
* specified. Connected sockets, on the other hand, will use their associated
* remote endpoint, so the `port` and `address` arguments must not be set.
*
* The `msg` argument contains the message to be sent.
* Depending on its type, different behavior can apply. If `msg` is a
* `Buffer`, any `TypedArray` or a `DataView`,
* the `offset` and `length` specify the offset within the `Buffer` where the
* message begins and the number of bytes in the message, respectively.
* If `msg` is a `String`, then it is automatically converted to a `Buffer`
* with `'utf8'` encoding. With messages that contain multi-byte characters,
* `offset` and `length` will be calculated with respect to `byte length` and
* not the character position. If `msg` is an array, `offset` and `length`
* must not be specified.
*
* The `address` argument is a string. If the value of `address` is a host
* name, DNS will be used to resolve the address of the host. If `address`
* is not provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets)
* or `'::1'`(for `udp6` sockets) will be used by default.
*
* If the socket has not been previously bound with a call to `bind`, the
* socket is assigned a random port number and is bound to the "all
* interfaces" address (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6`
* sockets.)
*
* An optional `callback` function may be specified to as a way of
* reporting DNS errors or for determining when it is safe to reuse the `buf`
* object. DNS lookups delay the time to send for at least one tick of the
* Node.js event loop.
*
* The only way to know for sure that the datagram has been sent is by using
* a `callback`. If an error occurs and a `callback` is given, the error will
* be passed as the first argument to the `callback`. If a `callback` is not
* given, the error is emitted as an `'error'` event on the `socket` object.
*
* Offset and length are optional but both _must_ be set if either are used.
* They are supported only when the first argument is a `Buffer`, a
* `TypedArray`, or a `DataView`.
*
* This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket.
*
* Example of sending a UDP packet to a port on `localhost`;
*
* ```js
* import dgram from 'dgram';
* import { Buffer } from 'buffer';
*
* const message = Buffer.from('Some bytes');
* const client = dgram.createSocket('udp4');
* client.send(message, 41234, 'localhost', (err) => {
* client.close();
* });
* ```
*
* Example of sending a UDP packet composed of multiple buffers to a port on
* `127.0.0.1`;
*
* ```js
* import dgram from 'dgram';
* import { Buffer } from 'buffer';
*
* const buf1 = Buffer.from('Some ');
* const buf2 = Buffer.from('bytes');
* const client = dgram.createSocket('udp4');
* client.send([buf1, buf2], 41234, (err) => {
* client.close();
* });
* ```
*
* Sending multiple buffers might be faster or slower depending on the
* application and operating system. Run benchmarks to
* determine the optimal strategy on a case-by-case basis. Generally
* speaking, however, sending multiple buffers is faster.
*
* Example of sending a UDP packet using a socket connected to a port on
* `localhost`:
*
* ```js
* import dgram from 'dgram';
* import { Buffer } from 'buffer';
*
* const message = Buffer.from('Some bytes');
* const client = dgram.createSocket('udp4');
* client.connect(41234, 'localhost', (err) => {
* client.send(message, (err) => {
* client.close();
* });
* });
* ```
*
* @param msg Message to be sent.
* @param offset Offset in the buffer where the message starts.
* @param length Number of bytes in the message.
* @param port Destination port.
* @param address Destination host name or IP address.
* @param callback Called when the message has been sent.
*/
send(
msg: MessageType | ReadonlyArray<MessageType>,
port?: number,
address?: string,
callback?: (error: ErrnoException | null, bytes?: number) => void,
): void;
send(
msg: MessageType | ReadonlyArray<MessageType>,
port?: number,
callback?: (error: ErrnoException | null, bytes?: number) => void,
): void;
send(
msg: MessageType | ReadonlyArray<MessageType>,
callback?: (error: ErrnoException | null, bytes?: number) => void,
): void;
send(
msg: MessageType,
offset: number,
length: number,
port?: number,
address?: string,
callback?: (error: ErrnoException | null, bytes?: number) => void,
): void;
send(
msg: MessageType,
offset: number,
length: number,
port?: number,
callback?: (error: ErrnoException | null, bytes?: number) => void,
): void;
send(
msg: MessageType,
offset: number,
length: number,
callback?: (error: ErrnoException | null, bytes?: number) => void,
): void;
send(
buffer: unknown,
offset?: unknown,
length?: unknown,
port?: unknown,
address?: unknown,
callback?: unknown,
): void {
let list: MessageType[] | null;
const state = this[kStateSymbol];
const connected = state.connectState === CONNECT_STATE_CONNECTED;
if (!connected) {
if (address || (port && typeof port !== "function")) {
buffer = sliceBuffer(
buffer as MessageType,
offset as number,
length as number,
);
} else {
callback = port;
port = offset;
address = length;
}
} else {
if (typeof length === "number") {
buffer = sliceBuffer(buffer as MessageType, offset as number, length);
if (typeof port === "function") {
callback = port;
port = null;
}
} else {
callback = offset;
}
if (port || address) {
throw new ERR_SOCKET_DGRAM_IS_CONNECTED();
}
}
if (!Array.isArray(buffer)) {
if (typeof buffer === "string") {
list = [Buffer.from(buffer)];
} else if (!isArrayBufferView(buffer)) {
throw new ERR_INVALID_ARG_TYPE(
"buffer",
["Buffer", "TypedArray", "DataView", "string"],
buffer,
);
} else {
list = [buffer as MessageType];
}
} else if (!(list = fixBufferList(buffer))) {
throw new ERR_INVALID_ARG_TYPE(
"buffer list arguments",
["Buffer", "TypedArray", "DataView", "string"],
buffer,
);
}
if (!connected) {
port = validatePort(port, "Port", false);
}
// Normalize callback so it's either a function or undefined but not anything
// else.
if (typeof callback !== "function") {
callback = undefined;
}
if (typeof address === "function") {
callback = address;
address = undefined;
} else if (address && typeof address !== "string") {
throw new ERR_INVALID_ARG_TYPE("address", ["string", "falsy"], address);
}
healthCheck(this);
if (state.bindState === BIND_STATE_UNBOUND) {
this.bind({ port: 0, exclusive: true });
}
if (list.length === 0) {
list.push(Buffer.alloc(0));
}
// If the socket hasn't been bound yet, push the outbound packet onto the
// send queue and send after binding is complete.
if (state.bindState !== BIND_STATE_BOUND) {
// @ts-ignore mapping unknowns back onto themselves doesn't type nicely
enqueue(this, this.send.bind(this, list, port, address, callback));
return;
}
const afterDns = (ex: ErrnoException | null, ip: string) => {
defaultTriggerAsyncIdScope(
this[asyncIdSymbol],
doSend,
ex,
this,
ip,
list,
address,
port,
callback,
);
};
if (!connected) {
state.handle!.lookup(address as string, afterDns);
} else {
afterDns(null, "");
}
}
/**
* Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP
* packets may be sent to a local interface's broadcast address.
*
* This method throws `EBADF` if called on an unbound socket.
*/
setBroadcast(arg: boolean): void {
const err = this[kStateSymbol].handle!.setBroadcast(arg ? 1 : 0);
if (err) {