forked from gemini-testing/ssh-tun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
165 lines (136 loc) · 4.79 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
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
'use strict';
var inherit = require('inherit'),
q = require('q'),
childProcess = require('child_process'),
util = require('util');
var DEFAULTS = {
MAX_RETRIES: 5,
CONNECT_TIMEOUT: 10000,
SSH_PORT: 22
};
var Tunnel = inherit({
/**
* Constuctor
* @param {object} opts tunnel options
* @param {string} opts.host remote host address
* @param {object} opts.ports remote host ports range
* @param {number} opts.localport local port number
* @param {string} [opts.user] remote host user
* @param {string} [opts.sshPort=22] host port to create tunnel
* @param {number} [opts.maxRetries=5] max attempts to create tunnel
* @param {number} [opts.connectTimeout=10000] ssh connect timeout
*/
__constructor: function (opts) {
this.host = opts.host;
this.port = this._generateRandomPort(opts.ports);
this._sshPort = opts.sshPort || DEFAULTS.SSH_PORT;
this.user = opts.user;
this.proxyHost = util.format('%s:%d', this.host, this.port);
this.proxyUrl = this.proxyHost; // deprecated, use proxyHost
this._localPort = opts.localport;
this._connectTimeout = opts.connectTimeout || DEFAULTS.CONNECT_TIMEOUT;
this._tunnel = null;
this._tunnelDeferred = q.defer();
this._closeDeferred = q.defer();
},
/**
* Tries to open ssh connection to remote server
* @returns {Promise}
*/
open: function () {
var _this = this;
console.info('INFO: creating tunnel to %s', this.proxyHost);
this._tunnel = childProcess.spawn('ssh', this._buildSSHArgs());
this._tunnel.stderr.on('data', function (data) {
if (/success/.test(data)) {
return _this._resolveTunnel();
}
if (/failed/.test(data)) {
if (_this._tunnelDeferred.promise.isFulfilled()) {
return;
}
return _this._rejectTunnel();
}
if (/killed/i.test(data)) {
var msg = data.toString().toLowerCase();
var killMsg = msg.slice(msg.indexOf('killed')).trim();
console.info('INFO: Tunnel is ' + killMsg);
}
});
this._tunnel.on('close', function (code) {
return _this._closeTunnel(code);
});
this._tunnel.on('error', function () {
return _this._rejectTunnel();
});
return _this._tunnelDeferred.promise.timeout(this._connectTimeout);
},
/**
* Closes connection. If no connection established does nothing
* @returns {Promise}
*/
close: function () {
if (!this._tunnel) {
return q();
}
var _this = this;
this._tunnel.kill('SIGTERM');
return this._closeDeferred.promise.timeout(3000).fail(function () {
_this._tunnel.kill('SIGKILL');
return _this._closeTunnel(-1);
});
},
_resolveTunnel: function () {
console.info('INFO: Tunnel created to %s', this.proxyHost);
this._tunnelDeferred.resolve();
},
_rejectTunnel: function () {
var message = util.format('ERROR: failed to create tunnel to %s.', this.proxyHost),
error = new Error(message);
console.info(message);
this._tunnelDeferred.reject(error);
},
_closeTunnel: function (exitCode) {
console.info('INFO: Tunnel to %s closed. Exit code: %d', this.proxyHost, exitCode);
this._closeDeferred.resolve();
},
_buildSSHArgs: function () {
return [
util.format('-R %d:localhost:%d', this.port, this._localPort),
'-N',
'-v',
util.format('-p %d', this._sshPort),
(this.user ? this.user + '@' : '') + this.host
];
},
_generateRandomPort: function (ports) {
var min = ports.min,
max = ports.max;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
});
/**
* Tries to open tunnel several times
* @param {object} opts opts which will be passed to created tunnel
* @param {number} retries amount of retries to open tunnel
* @returns {Promise}
*/
Tunnel.openWithRetries = function (opts, retries) {
retries = retries || DEFAULTS.MAX_RETRIES;
function retry_(retriesLeft) {
if (!retriesLeft) {
return q.reject(util.format('ERROR: failed to create tunnel after %d attempts', retries));
}
var tunnel = new Tunnel(opts);
return tunnel.open()
.then(function () {
return q.resolve(tunnel);
})
.fail(function () {
return tunnel.close()
.then(retry_.bind(null, retriesLeft - 1));
});
}
return retry_(retries);
};
module.exports = Tunnel;