-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
96 lines (84 loc) · 2.39 KB
/
index.js
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
// Importing required modules
const HyperDHT = require("hyperdht"); // HyperDHT module for DHT functionality
const net = require("net"); // Net module for creating network clients and servers
const libNet = require("@holesail/hyper-cmd-lib-net"); // Custom network library
const b4a = require("b4a");
class holesailClient {
constructor(key, secure) {
// check if secure flag is enabled
if (secure === "secure") {
this.secure = true;
this.peerKey = HyperDHT.keyPair(b4a.from(key, "hex"));
this.dht = new HyperDHT({ keyPair: this.peerKey });
} else {
this.peerKey = key;
this.dht = new HyperDHT();
}
this.stats = {};
this.proxy;
}
connect(options, callback) {
if (!options.udp) {
this.handleTCP(options, callback);
} else {
this.handleUDP(options, callback);
}
} // end connect
// Handle TCP connections
handleTCP(options, callback) {
this.proxy = net.createServer({ allowHalfOpen: true }, (c) => {
return libNet.connPiper(
c,
() => {
let stream;
if (this.secure) {
stream = this.dht.connect(
Buffer.from(this.peerKey.publicKey, "hex"),
{ reusableSocket: true },
);
} else {
stream = this.dht.connect(Buffer.from(this.peerKey, "hex"), {
reusableSocket: true,
});
}
return stream;
},
{ compress: false },
this.stats,
);
});
const targetHost = options.address || "127.0.0.1";
this.proxy.listen(options.port, targetHost, () => {
if (typeof callback === "function") {
callback();
}
});
}
// Handle UDP connections
handleUDP(options, callback) {
let conn;
if (this.secure) {
conn = this.dht.connect(Buffer.from(this.peerKey.publicKey, "hex"));
} else {
conn = this.dht.connect(Buffer.from(this.peerKey, "hex"));
}
conn.once("open", function () {
const handleUDP = libNet.udpPiper(conn, () => {
return libNet.udpConnect({
port: options.port || 8989,
host: options.address || "127.0.0.1",
bind: true,
});
});
if (typeof callback === "function") {
callback();
}
});
}
destroy() {
this.dht.destroy();
this.proxy.close();
return 0;
}
} // end client class
module.exports = holesailClient;