-
Notifications
You must be signed in to change notification settings - Fork 0
/
publishPort.js
295 lines (251 loc) · 9.43 KB
/
publishPort.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
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
// publishPort.js
const net = require('net');
const tls = require('tls');
const dgram = require('dgram');
const fs = require('fs');
const { Buffer } = require('buffer');
const EventEmitter = require('events');
const { Duplex } = require('stream');
const DiodeRPC = require('./rpc');
class DiodeSocket extends Duplex {
constructor(ref, rpc) {
super();
this.ref = ref;
this.rpc = rpc;
}
_write(chunk, encoding, callback) {
// Send data to the Diode client via portSend
this.rpc.portSend(this.ref, chunk)
.then(() => callback())
.catch((err) => callback(err));
}
_read(size) {
// No need to implement this method
}
// Method to push data received from Diode client
pushData(data) {
this.push(data);
}
}
class PublishPort extends EventEmitter {
constructor(connection, publishedPorts, certPath) {
super();
this.connection = connection;
this.publishedPorts = publishedPorts; // Array of ports to publish
this.connections = new Map(); // Map to store active connections
this.startListening();
this.rpc = new DiodeRPC(connection);
this.certPath = certPath;
}
startListening() {
// Listen for unsolicited messages from the connection
this.connection.on('unsolicited', (message) => {
const [sessionIdRaw, messageContent] = message;
const messageTypeRaw = messageContent[0];
const messageType = Buffer.from(messageTypeRaw).toString('utf8');
if (messageType === 'portopen') {
this.handlePortOpen(sessionIdRaw, messageContent);
} else if (messageType === 'portsend') {
this.handlePortSend(sessionIdRaw, messageContent);
} else if (messageType === 'portclose') {
this.handlePortClose(sessionIdRaw, messageContent);
} else {
console.warn(`Unknown unsolicited message type: ${messageType}`);
}
});
}
handlePortOpen(sessionIdRaw, messageContent) {
// messageContent: ['portopen', portString, ref, deviceId]
const portStringRaw = messageContent[1];
const refRaw = messageContent[2];
const deviceIdRaw = messageContent[3];
const sessionId = Buffer.from(sessionIdRaw);
const portString = Buffer.from(portStringRaw).toString('utf8');
const ref = Buffer.from(refRaw);
const deviceId = Buffer.from(deviceIdRaw).toString('hex');
console.log(`Received portopen request for portString ${portString} with ref ${ref.toString('hex')} from device ${deviceId}`);
// Extract protocol and port number from portString
const [protocol, portStr] = portString.split(':');
const port = parseInt(portStr, 10);
// Check if the port is published
if (!this.publishedPorts.includes(port)) {
console.warn(`Port ${port} is not published. Rejecting request.`);
// Send error response
this.rpc.sendError(sessionId, ref, 'Port is not published');
return;
}
// Handle based on protocol
if (protocol === 'tcp') {
this.handleTCPConnection(sessionId, ref, port);
} else if (protocol === 'tls') {
this.handleTLSConnection(sessionId, ref, port);
} else if (protocol === 'udp') {
this.handleUDPConnection(sessionId, ref, port);
} else {
console.warn(`Unsupported protocol: ${protocol}`);
this.rpc.sendError(sessionId, ref, `Unsupported protocol: ${protocol}`);
}
}
setupLocalSocketHandlers(localSocket, ref, protocol) {
if (protocol === 'udp') {
} else {
localSocket.on('data', (data) => {
// When data is received from the local service, send it back via Diode
this.rpc.portSend(ref, data);
});
localSocket.on('end', () => {
console.log(`Local service disconnected`);
// Send portclose message to Diode
this.rpc.portClose(ref);
this.connections.delete(ref.toString('hex'));
});
localSocket.on('error', (err) => {
console.error(`Error with local service:`, err);
// Send portclose message to Diode
this.rpc.portClose(ref);
this.connections.delete(ref.toString('hex'));
});
}
}
handleTCPConnection(sessionId, ref, port) {
// Create a TCP connection to the local service on the specified port
const localSocket = net.connect({ port: port }, () => {
console.log(`Connected to local TCP service on port ${port}`);
// Send success response
this.rpc.sendResponse(sessionId, ref, 'ok');
});
// Handle data, end, and error events
this.setupLocalSocketHandlers(localSocket, ref, 'tcp');
// Store the local socket with the ref
this.connections.set(ref.toString('hex'), { socket: localSocket, protocol: 'tcp' });
}
handleTLSConnection(sessionId, ref, port) {
// Create a DiodeSocket instance
const diodeSocket = new DiodeSocket(ref, this.rpc);
// TLS options with your server's certificate and key
const tlsOptions = {
cert: fs.readFileSync(this.certPath),
key: fs.readFileSync(this.certPath),
rejectUnauthorized: false,
ciphers: 'ECDHE-ECDSA-AES256-GCM-SHA384',
ecdhCurve: 'secp256k1',
minVersion: 'TLSv1.2',
maxVersion: 'TLSv1.2',
};
// Create a TLS socket in server mode using the DiodeSocket
const tlsSocket = new tls.TLSSocket(diodeSocket, {
isServer: true,
...tlsOptions,
});
// Connect to the local service (TCP or TLS as needed)
const localSocket = net.connect({ port: port }, () => {
console.log(`Connected to local TCP service on port ${port}`);
// Send success response
this.rpc.sendResponse(sessionId, ref, 'ok');
});
// Pipe data between the TLS socket and the local service
tlsSocket.pipe(localSocket).pipe(tlsSocket);
// Handle errors and cleanup
tlsSocket.on('error', (err) => {
console.error('TLS Socket error:', err);
this.rpc.portClose(ref);
this.connections.delete(ref.toString('hex'));
});
tlsSocket.on('close', () => {
console.log('TLS Socket closed');
this.connections.delete(ref.toString('hex'));
});
// Store the connection info
this.connections.set(ref.toString('hex'), {
diodeSocket,
tlsSocket,
localSocket,
protocol: 'tls',
});
}
handleUDPConnection(sessionId, ref, port) {
// Create a UDP socket
const localSocket = dgram.createSocket('udp4');
// Store the remote address and port from the Diode client
const remoteInfo = {port, address: '127.0.0.1'};
// Send success response
this.rpc.sendResponse(sessionId, ref, 'ok');
// Store the connection info
this.connections.set(ref.toString('hex'), {
socket: localSocket,
protocol: 'udp',
remoteInfo,
});
// Handle messages from the local UDP service
localSocket.on('message', (msg, rinfo) => {
//need to add 4 bytes of data length to the beginning of the message but it's Big Endian
const dataLength = Buffer.alloc(4);
dataLength.writeUInt32LE(msg.length, 0);
const data = Buffer.concat([dataLength, msg]);
// Send the data back to the Diode client via portSend
this.rpc.portSend(ref, data);
});
localSocket.on('error', (err) => {
console.error(`UDP Socket error:`, err);
this.rpc.portClose(ref);
this.connections.delete(ref.toString('hex'));
});
}
handlePortSend(sessionIdRaw, messageContent) {
const refRaw = messageContent[1];
const dataRaw = messageContent[2];
const sessionId = Buffer.from(sessionIdRaw);
const ref = Buffer.from(refRaw);
const data = Buffer.from(dataRaw).slice(4);
const connectionInfo = this.connections.get(ref.toString('hex'));
if (connectionInfo) {
const { socket: localSocket, protocol, remoteInfo } = connectionInfo;
if (protocol === 'udp') {
// Send data to the local UDP service
// Since UDP is connectionless, we need to specify the address and port
localSocket.send(data, remoteInfo.port, remoteInfo.address, (err) => {
if (err) {
console.error(`Error sending UDP data:`, err);
}
});
// Update remoteInfo if not set
if (!localSocket.remoteAddress) {
localSocket.remoteAddress = '127.0.0.1'; // Assuming local service is on localhost
localSocket.remotePort = port;
}
} else if (protocol === 'tcp') {
// Write data to the local service
localSocket.write(data);
} else if (protocol === 'tls') {
const { diodeSocket } = connectionInfo;
// Push data into the DiodeSocket
diodeSocket.pushData(data);
}
} else {
console.warn(`No local connection found for ref ${ref.toString('hex')}. Sending portclose.`);
this.rpc.sendError(sessionId, ref, 'No local connection found');
}
}
handlePortClose(sessionIdRaw, messageContent) {
const refRaw = messageContent[1];
const sessionId = Buffer.from(sessionIdRaw);
const ref = Buffer.from(refRaw);
console.log(`Received portclose for ref ${ref.toString('hex')}`);
const connectionInfo = this.connections.get(ref.toString('hex'));
if (connectionInfo) {
const { diodeSocket, tlsSocket, socket: localSocket } = connectionInfo;
// End all sockets
if (diodeSocket) diodeSocket.end();
if (tlsSocket) tlsSocket.end();
if (localSocket) {
if (localSocket.type === 'udp4' || localSocket.type === 'udp6') {
localSocket.close();
} else {
localSocket.end();
}
}
this.connections.delete(ref.toString('hex'));
}
}
}
module.exports = PublishPort;