This repository has been archived by the owner on Jun 29, 2023. It is now read-only.
forked from agebrock/tunnel-ssh
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
107 lines (93 loc) · 3.01 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
97
98
99
100
101
102
103
104
105
106
107
var net = require('net');
var debug = require('debug')('tunnel-ssh');
var Connection = require('ssh2');
var createConfig = require('./lib/config');
var events = require('events');
var noop = function () {
};
function bindSSHConnection(config, netConnection) {
var sshConnection = new Connection();
netConnection.on('close', sshConnection.end.bind(sshConnection));
sshConnection.on('ready', function () {
debug('sshConnection:ready');
netConnection.emit('sshConnection', sshConnection, netConnection);
sshConnection.forwardOut(config.srcHost, config.srcPort, config.dstHost, config.dstPort, function (err, sshStream) {
if (err) {
// Bubble up the error => netConnection => server
netConnection.emit('error', err);
debug('Destination port:', err);
return;
}
debug('sshStream:create');
netConnection.emit('sshStream', sshStream);
netConnection.pipe(sshStream).pipe(netConnection);
});
});
return sshConnection;
}
function createServer(config) {
var server;
var connections = [];
var connectionCount = 0;
server = net.createServer(function (netConnection) {
var sshConnection;
connectionCount++;
netConnection.on('error', server.emit.bind(server, 'error'));
netConnection.on('close', function () {
connectionCount--;
if (connectionCount === 0) {
if (!config.keepAlive) {
setTimeout(function () {
if (connectionCount === 0) {
server.close();
}
}, 2);
}
}
});
server.emit('netConnection', netConnection, server);
sshConnection = bindSSHConnection(config, netConnection);
sshConnection.on('error', server.emit.bind(server, 'error'));
netConnection.on('sshStream', function (sshStream) {
sshStream.on('error', function () {
server.close();
});
});
connections.push(sshConnection, netConnection);
try
{
sshConnection.connect(config);
}catch(error)
{
server.emit('error', error);
}
});
server.on('close', function () {
connections.forEach(function (connection) {
connection.end();
});
});
return server;
}
function tunnel(configArgs, callback) {
var server;
var config;
if (!callback) {
callback = noop;
}
try {
config = createConfig(configArgs);
server = createServer(config);
server.listen(config.localPort, config.localHost, function (error) {
callback(error, server);
});
} catch (e) {
server = new events.EventEmitter();
setImmediate(function () {
callback(e);
server.emit('error', e);
});
}
return server;
}
module.exports = tunnel;