-
Notifications
You must be signed in to change notification settings - Fork 7
/
net.ts
774 lines (728 loc) · 26.6 KB
/
net.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
/**
* Functions for working with the network, such as connecting to a TCP server,
* binding a UDP socket, etc.
*
* This module is designed to provide a unified interface to work with network
* in Node.js, Deno, Bun (and Cloudflare Workers for limited support), based on
* modern Web APIs. It does not work in the browser.
*
* NOTE: This module depends on the Web Streams API, in Node.js, it requires
* Node.js v18.0 or above.
* @module
* @experimental
*/
import { asyncTask } from "./async.ts";
import { isBun, isDeno, isNode, isNodeLike } from "./env.ts";
import { ToDict } from "./types.ts";
import {
NetAddress,
SocketStream,
TcpConnectOptions,
TcpSocketStream,
UdpBindOptions,
UdpConnectOptions,
UdpSocket,
UdpSocketStream,
UnixConnectOptions,
UnixSocketStream,
} from "./net/types.ts";
import type { Socket as NodeSocket } from "node:net";
import type { TLSSocket } from "node:tls";
import chan from "./chan.ts";
export type * from "./net/types.ts";
/**
* Returns the IP address of the current machine.
*
* NOTE: This function is not available in the browser and worker runtimes such
* as Cloudflare Workers.
*/
export async function getMyIp(): Promise<string> {
if (isNodeLike) {
const { createSocket } = await import("node:dgram");
const socket = createSocket("udp4");
return new Promise<string>((resolve) => {
socket.connect(53, "8.8.8.8", () => {
const addr = socket.address();
socket.close();
resolve(addr.address);
});
});
} else if (isDeno) {
const conn = await Deno.connect({
hostname: "8.8.8.8",
port: 53,
});
const addr = conn.localAddr as Deno.NetAddr;
conn.close();
return addr.hostname;
} else {
throw new Error("Unsupported runtime");
}
}
/**
* Returns a random port number that is available for listening.
*
* NOTE: This function is not available in the browser and worker runtimes such
* as Cloudflare Workers.
*
* @param prefer The preferred port number to return if it is available,
* otherwise a random port is returned.
*
* @param hostname The hostname to bind the port to. Default is "0.0.0.0", only
* used when `prefer` is set and not `0`.
*/
export async function randomPort(
prefer: number | undefined = undefined,
hostname: string | undefined = undefined
): Promise<number> {
hostname ||= "0.0.0.0";
if (isDeno) {
try {
const listener = Deno.listen({
hostname,
port: prefer ?? 0,
});
const { port } = listener.addr as Deno.NetAddr;
listener.close();
return Promise.resolve(port);
} catch (err) {
if (prefer) {
return randomPort(0);
} else {
throw err;
}
}
} else if (isBun) {
try {
const listener = Bun.listen({
hostname,
port: prefer ?? 0,
socket: {
data: () => { },
},
}) as { port: number; stop: (force?: boolean) => void; };
const { port } = listener;
listener.stop(true);
return Promise.resolve(port);
} catch (err) {
if (prefer) {
return randomPort(0);
} else {
throw err;
}
}
} else if (isNode) {
const { createServer, connect } = await import("node:net");
if (prefer) {
// In Node.js listening on a port used by another process may work,
// so we don't use `listen` method to check if the port is available.
// Instead, we use the `connect` method to check if the port can be
// reached, if so, the port is open and we don't use it.
const isOpen = await new Promise<boolean>((resolve, reject) => {
const conn = connect(prefer, hostname === "0.0.0.0" ? "localhost" : hostname);
conn.once("connect", () => {
conn.end();
resolve(true);
}).once("error", (err) => {
if ((err as any)["code"] === "ECONNREFUSED") {
resolve(false);
} else {
reject(err);
}
});
});
if (isOpen) {
return randomPort(0);
} else {
return prefer;
}
} else {
const server = createServer();
server.listen({ port: 0, exclusive: true });
const port = (server.address() as any).port as number;
return new Promise<number>((resolve, reject) => {
server.close(err => err ? reject(err) : resolve(port));
});
}
} else {
throw new Error("Unsupported runtime");
}
}
/**
* This function provides a unified interface to connect to a TCP server or UDP
* peer in Node.js, Deno, Bun and Cloudflare Workers, based on modern Web APIs.
*
* NOTE: This function depends on the Web Streams API, in Node.js, it requires
* Node.js v18.0 or above.
*
* @example
* ```ts
* // TCP
* import bytes from "@ayonli/jsext/bytes";
* import { readAsText } from "@ayonli/jsext/reader";
* import { connect } from "@ayonli/jsext/net";
*
* const socket = await connect({ hostname: "example.com", port: 80 });
* const writer = socket.writable.getWriter();
*
* await writer.write(bytes("GET / HTTP/1.1\r\n"));
* await writer.write(bytes("Accept: plain/html\r\n"));
* await writer.write(bytes("Host: example.com\r\n"));
* await writer.write(bytes("\r\n"));
* await writer.close();
*
* const message = await readAsText(socket.readable);
* console.log(message);
* ```
*/
export async function connect(options: TcpConnectOptions): Promise<TcpSocketStream>;
export async function connect(options: UnixConnectOptions): Promise<UnixSocketStream>;
export async function connect(options: UdpConnectOptions): Promise<UdpSocketStream>;
export function connect(
options: TcpConnectOptions | UnixConnectOptions | UdpConnectOptions
): Promise<TcpSocketStream | UnixSocketStream | UdpSocketStream> {
if (options.transport === "udp") {
return connectUdp(options);
} else if (options.transport === "unix" || "path" in options) {
return connectUnix(options);
} else {
return connectTcp(options);
}
}
async function connectTcp(options: TcpConnectOptions): Promise<TcpSocketStream> {
const { tls = false, ..._options } = options;
if (isNode) {
const { createConnection } = await import("node:net");
const { connect } = await import("node:tls");
const _socket = tls ? connect({
..._options,
rejectUnauthorized: false,
}) : createConnection({
host: options.hostname,
port: options.port,
localPort: 0,
});
const props = await nodeToSocket(_socket);
return new TcpSocketStream({
localAddress: {
hostname: _socket.localAddress || "localhost",
port: _socket.localPort ?? 0,
},
remoteAddress: {
hostname: _socket.remoteAddress!,
port: _socket.remotePort!,
},
...props,
setKeepAlive: _socket.setKeepAlive.bind(_socket),
setNoDelay: _socket.setNoDelay.bind(_socket),
});
} else if (isDeno) {
const _socket = tls
? await Deno.connectTls(_options)
: await Deno.connect(_options);
const { localAddr, remoteAddr } = _socket;
return new TcpSocketStream({
localAddress: {
hostname: localAddr.hostname,
port: localAddr.port,
},
remoteAddress: {
hostname: remoteAddr.hostname,
port: remoteAddr.port,
},
...denoToSocket(_socket),
setKeepAlive: (keepAlive) => {
if ("setKeepAlive" in _socket) {
_socket.setKeepAlive(keepAlive);
}
},
setNoDelay: (noDelay) => {
if ("setNoDelay" in _socket) {
_socket.setNoDelay(noDelay);
}
},
});
} else if (isBun) {
const ready = asyncTask<void>();
const closed = asyncTask<void>();
let readCtrl: ReadableStreamDefaultController<Uint8Array> | null = null;
let writeCtrl: WritableStreamDefaultController | null = null;
const closeStreams = () => {
try { _socket.terminate(); } catch { }
try { readCtrl?.close(); } catch { }
try { writeCtrl?.error(new TypeError("The stream is closed.")); } catch { }
};
const readable = new ReadableStream<Uint8Array>({
start(controller) {
readCtrl = controller;
},
cancel(reason) {
reason ? closed.reject(reason) : closed.resolve();
closeStreams();
},
});
const writable = new WritableStream<Uint8Array>({
start(controller) {
writeCtrl = controller;
},
write(chunk) {
_socket.write(chunk);
},
close() {
writeCtrl!.error(new TypeError("The stream is closed."));
_socket.shutdown();
},
});
const _socket = await Bun.connect({
..._options,
tls,
socket: {
binaryType: "uint8array",
open() {
ready.resolve();
},
data(_socket, data: Uint8Array) {
readCtrl!.enqueue(data);
},
error(_socket, error) {
try { readCtrl!.error(error); } catch { }
try { writeCtrl!.error(error); } catch { }
closed.reject(error);
},
close() {
closeStreams();
closed.resolve();
},
}
});
await ready;
return new TcpSocketStream({
localAddress: {
hostname: "localhost",
port: _socket.localPort,
},
remoteAddress: {
hostname: _socket.remoteAddress,
port: options.port,
},
readable,
writable,
closed,
close: closeStreams,
ref: () => _socket.ref(),
unref: () => _socket.unref(),
setKeepAlive: (keepAlive) => {
if ("setKeepAlive" in _socket) {
_socket.setKeepAlive(keepAlive);
}
},
setNoDelay: (noDelay) => {
if ("setNoDelay" in _socket) {
_socket.setNoDelay(noDelay);
}
},
});
} else {
throw new Error("Unsupported runtime");
}
}
async function connectUnix(options: UnixConnectOptions): Promise<UnixSocketStream> {
const { path } = options;
if (isNode) {
const { createConnection } = await import("node:net");
const _socket = createConnection({ path });
const props = await nodeToSocket(_socket);
return new UnixSocketStream(props);
} else if (isDeno) {
const _socket = await Deno.connect({ transport: "unix", path });
return new UnixSocketStream(denoToSocket(_socket));
} else if (isBun) {
const ready = asyncTask<void>();
const closed = asyncTask<void>();
let readCtrl: ReadableStreamDefaultController<Uint8Array> | null = null;
let writeCtrl: WritableStreamDefaultController | null = null;
const closeStreams = () => {
try { _socket.terminate(); } catch { }
try { readCtrl?.close(); } catch { }
try { writeCtrl?.error(new TypeError("The stream is closed.")); } catch { }
};
const readable = new ReadableStream<Uint8Array>({
start(controller) {
readCtrl = controller;
},
cancel(reason) {
reason ? closed.reject(reason) : closed.resolve();
closeStreams();
},
});
const writable = new WritableStream<Uint8Array>({
start(controller) {
writeCtrl = controller;
},
write(chunk) {
_socket.write(chunk);
},
close() {
_socket.shutdown();
},
});
const _socket = await Bun.connect({
unix: path,
socket: {
binaryType: "uint8array",
open() {
ready.resolve();
},
data(_socket, data: Uint8Array) {
readCtrl!.enqueue(data);
},
error(_socket, error) {
try { readCtrl!.error(error); } catch { }
try { writeCtrl!.error(error); } catch { }
closed.reject(error);
},
close() {
closeStreams();
closed.resolve();
},
}
});
await ready;
return new UnixSocketStream({
readable,
writable,
closed,
close: closeStreams,
ref: () => _socket.ref(),
unref: () => _socket.unref(),
});
} else {
throw new Error("Unsupported runtime");
}
}
async function nodeToSocket(
socket: NodeSocket | TLSSocket
): Promise<ToDict<SocketStream>> {
const ready = asyncTask<void>();
const closed = asyncTask<void>();
let readCtrl: ReadableStreamDefaultController<Uint8Array> | null = null;
let writeCtrl: WritableStreamDefaultController | null = null;
const closeStreams = () => {
try { socket.destroyed || socket.destroy(); } catch { }
try { readCtrl?.close(); } catch { }
try { writeCtrl?.error(new TypeError("The stream is closed.")); } catch { }
};
const readable = new ReadableStream<Uint8Array>({
start(controller) {
readCtrl = controller;
},
cancel(reason) {
reason ? closed.reject(reason) : closed.resolve();
closeStreams();
},
});
const writable = new WritableStream<Uint8Array>({
start(controller) {
writeCtrl = controller;
},
write(chunk) {
return new Promise<void>((resolve, reject) => {
socket.write(chunk, err => {
err ? reject(err) : resolve();
});
});
},
close() {
return new Promise<void>(resolve => {
socket.end(resolve);
});
},
});
socket.once("connect", () => {
ready.resolve();
}).on("data", data => {
readCtrl!.enqueue(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
}).once("error", (error) => {
try { readCtrl!.error(error); } catch { }
try { writeCtrl!.error(error); } catch { }
closed.reject(error);
ready.reject(error);
}).once("close", (hasError) => {
if (!hasError) {
closeStreams();
closed.resolve();
}
});
await ready;
return {
readable,
writable,
closed,
close: () => void socket.destroy(),
ref: () => void socket.ref(),
unref: () => void socket.unref(),
};
}
function denoToSocket(
socket: Deno.TcpConn | Deno.TlsConn | Deno.UnixConn
): ToDict<SocketStream> {
const closed = asyncTask<void>();
let closeCalled = false;
let readCtrl: ReadableStreamDefaultController<Uint8Array> | null = null;
let writeCtrl: WritableStreamDefaultController | null = null;
const closeStreams = () => {
try { socket.close(); } catch { }
try { readCtrl?.close(); } catch { }
try { writeCtrl?.error(new TypeError("The stream is closed.")); } catch { }
};
return {
readable: new ReadableStream<Uint8Array>({
start(controller) {
readCtrl = controller;
},
async pull(readCtrl) {
try {
while (true) {
const value = new Uint8Array(4096);
const n = await socket.read(value);
if (n === null) {
closeStreams();
closed.resolve();
break;
}
readCtrl.enqueue(value.subarray(0, n));
}
} catch (err) {
try { socket.close(); } catch { }
try { readCtrl.error(err); } catch { }
try { writeCtrl?.error(err); } catch { }
closeCalled ? closed.resolve() : closed.reject(err);
}
},
cancel(reason) {
reason ? closed.reject(reason) : closed.resolve();
closeStreams();
},
}),
writable: new WritableStream<Uint8Array>({
start(controller) {
writeCtrl = controller;
},
async write(chunk) {
await socket.write(chunk);
},
close() {
return socket.closeWrite();
},
}),
closed,
close: () => {
closeCalled = true;
closeStreams();
},
ref: socket.ref.bind(socket),
unref: socket.unref.bind(socket),
};
}
async function connectUdp(remoteAddress: NetAddress): Promise<UdpSocketStream> {
const socket = await udpSocket();
return socket.connect(remoteAddress);
}
/**
* This function provides a unified interface to bind a UDP socket in Node.js,
* Deno and Bun, based on modern Web APIs.
*
* NOTE: This function depends on the Web Streams API, in Node.js, it requires
* Node.js v18.0 or above.
*
* @example
* ```ts
* import { udpSocket } from "@ayonli/jsext/net";
*
* const socket = await udpSocket({ port: 8080 });
*
* for await (const [data, addr] of socket) {
* console.log(`Received ${data.byteLength} bytes from ${addr.hostname}:${addr.port}`);
* }
* ```
*/
export async function udpSocket(localAddress: UdpBindOptions = {}): Promise<UdpSocket> {
// if (isDeno) {
// const _socket = Deno.listenDatagram({
// hostname: localAddress.hostname ?? "0.0.0.0",
// port: localAddress.port ?? 0,
// transport: "udp",
// });
// const addr = _socket.addr as Deno.NetAddr;
// const closed = asyncTask<void>();
// return new UdpSocket({
// localAddress: constructNetAddress({
// hostname: addr.hostname,
// port: addr.port,
// }),
// closed,
// close: _socket.close.bind(_socket),
// ref: () => void 0,
// unref: () => void 0,
// receive: async () => {
// try {
// const [data, addr] = await _socket.receive();
// return [data, {
// hostname: (addr as Deno.NetAddr).hostname,
// port: (addr as Deno.NetAddr).port,
// }];
// } catch (err) {
// closed.reject(err);
// try { _socket.close(); } catch { }
// throw err;
// }
// },
// send: (data, remoteAddress) => {
// return _socket.send(data, { transport: "udp", ...remoteAddress });
// },
// connect: (remoteAddress) => {
// void remoteAddress;
// throw new Error("Deno does not support UDP connection at the moment");
// },
// });
// } else if (isNodeLike) {
if (isDeno || isNodeLike) {
const { createSocket } = await import("node:dgram");
const _socket = createSocket(localAddress.hostname?.includes(":") ? "udp6" : "udp4");
let isConnected = false;
let isClosed = false;
const closed = asyncTask<void>();
const channel = chan<[Uint8Array, NetAddress]>(Infinity);
await new Promise<void>(resolve => {
_socket.bind(localAddress.port, localAddress.hostname, resolve);
});
_socket.on("message", (data, rinfo) => {
channel.send([new Uint8Array(data.buffer, data.byteOffset, data.byteLength), {
hostname: rinfo.address,
port: rinfo.port,
}]).catch(() => { });
}).once("error", err => {
channel.close(err);
closed.reject(err);
}).once("close", () => {
isClosed = true;
channel.close();
closed.resolve();
});
const localAddr = _socket.address();
const props: Pick<UdpSocket, "localAddress" | "closed" | "close" | "ref" | "unref"> = {
localAddress: {
hostname: localAddr.address,
port: localAddr.port,
},
closed,
close: () => void _socket.close(),
ref: _socket.ref.bind(_socket),
unref: _socket.unref.bind(_socket),
};
return new UdpSocket({
...props,
joinMulticast: _socket.addMembership.bind(_socket),
leaveMulticast: _socket.dropMembership.bind(_socket),
setBroadcast: _socket.setBroadcast.bind(_socket),
setMulticastLoopback: _socket.setMulticastLoopback.bind(_socket),
setMulticastTTL: _socket.setMulticastTTL.bind(_socket),
setTTL: _socket.setTTL.bind(_socket),
receive: async () => {
if (isConnected) {
throw new TypeError("The socket is connected.");
} else if (isClosed) {
throw new TypeError("The socket is closed.");
}
const msg = await channel.recv();
if (msg) {
return msg;
} else {
throw new TypeError("The socket is closed.");
}
},
send: async (data, remoteAddress) => {
if (isConnected) {
throw new TypeError("The socket is connected.");
} else if (isClosed) {
throw new TypeError("The socket is closed.");
}
return new Promise<number>((resolve, reject) => {
_socket.send(data, remoteAddress.port, remoteAddress.hostname, (err, n) => {
err ? reject(err) : resolve(n);
});
});
},
connect: (remoteAddress) => {
return new Promise<UdpSocketStream>(resolve => {
isConnected = true;
_socket.connect(remoteAddress.port, remoteAddress.hostname, () => {
const localAddr = _socket.address();
const remoteAddr = _socket.remoteAddress();
let readCtrl: ReadableStreamDefaultController<Uint8Array> | null = null;
let writeCtrl: WritableStreamDefaultController | null = null;
const closeStreams = () => {
channel.close();
try { _socket.close(); } catch { }
try { readCtrl?.close(); } catch { }
try { writeCtrl?.error(new TypeError("The stream is closed.")); } catch { }
};
resolve(new UdpSocketStream({
...props,
localAddress: {
hostname: localAddr.address,
port: localAddr.port,
},
remoteAddress: {
hostname: remoteAddr.address,
port: remoteAddr.port,
},
readable: new ReadableStream<Uint8Array>({
start(controller) {
readCtrl = controller;
},
async pull(readCtrl) {
try {
while (true) {
const msg = await channel.recv();
if (msg === undefined) {
closeStreams();
closed.resolve();
break;
}
readCtrl.enqueue(msg[0]);
}
} catch (err) {
channel.close(err as Error);
try { _socket.close(); } catch { }
try { readCtrl.error(err); } catch { }
try { writeCtrl?.error(err); } catch { }
isClosed ? closed.resolve() : closed.reject(err);
}
},
cancel(reason) {
reason ? closed.reject(reason) : closed.resolve();
closeStreams();
},
}),
writable: new WritableStream<Uint8Array>({
start(controller) {
writeCtrl = controller;
},
write(chunk) {
return new Promise((resolve, reject) => {
_socket.send(chunk, err => {
err ? reject(err) : resolve();
});
});
},
}),
}));
});
});
},
});
} else {
throw new Error("Unsupported runtime");
}
}