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 | 1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
| var inherits = require('util').inherits;
var DuplexStream = require('stream').Duplex;
var ReadableStream = require('stream').Readable;
var WritableStream = require('stream').Writable;
var STDERR = require('ssh2-streams').constants.CHANNEL_EXTENDED_DATATYPE.STDERR;
var PACKET_SIZE = 32 * 1024;
var MAX_WINDOW = 1 * 1024 * 1024;
var WINDOW_THRESHOLD = MAX_WINDOW / 2;
var CUSTOM_EVENTS = [
'CHANNEL_EOF',
'CHANNEL_CLOSE',
'CHANNEL_DATA',
'CHANNEL_EXTENDED_DATA',
'CHANNEL_WINDOW_ADJUST',
'CHANNEL_SUCCESS',
'CHANNEL_FAILURE',
'CHANNEL_REQUEST'
];
var CUSTOM_EVENTS_LEN = CUSTOM_EVENTS.length;
function Channel(info, client, opts) {
var streamOpts = {
highWaterMark: MAX_WINDOW,
allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false))
};
this.allowHalfOpen = streamOpts.allowHalfOpen;
DuplexStream.call(this, streamOpts);
var self = this;
var server = opts && opts.server;
this.server = server;
this.type = info.type;
this.subtype = undefined;
/*
incoming and outgoing contain these properties:
{
id: undefined,
window: undefined,
packetSize: undefined,
state: 'closed'
}
*/
var incoming = this.incoming = info.incoming;
var incomingId = incoming.id;
var outgoing = this.outgoing = info.outgoing;
var callbacks = this._callbacks = [];
var exitCode;
var exitSignal;
var exitDump;
var exitDesc;
var exitLang;
this._client = client;
this._hasX11 = false;
var channels = client._channels;
var sshstream = client._sshstream;
function ondrain() {
if (self._waitClientDrain) {
self._waitClientDrain = false;
if (!self._waitWindow) {
if (self._chunk)
self._write(self._chunk, null, self._chunkcb);
else if (self._chunkcb)
self._chunkcb();
else if (self._chunkErr)
self.stderr._write(self._chunkErr, null, self._chunkcbErr);
else if (self._chunkcbErr)
self._chunkcbErr();
}
}
}
client._sock.on('drain', ondrain);
sshstream.once('CHANNEL_EOF:' + incomingId, function() {
if (incoming.state === 'closed' || incoming.state === 'eof')
return;
incoming.state = 'eof';
if (self.readable)
self.push(null);
if (!server && self.stderr.readable)
self.stderr.push(null);
}).once('CHANNEL_CLOSE:' + incomingId, function() {
if (incoming.state === 'closed')
return;
incoming.state = 'closed';
if (self.readable)
self.push(null);
if (server && self.stderr.writable)
self.stderr.end();
else if (!server && self.stderr.readable)
self.stderr.push(null);
if (outgoing.state === 'open' || outgoing.state === 'eof')
self.close();
if (outgoing.state === 'closing')
outgoing.state = 'closed';
delete channels[incomingId];
var state = self._writableState;
client._sock.removeListener('drain', ondrain);
if (!state.ending && !state.finished)
self.end();
// Take care of any outstanding channel requests
self._callbacks = [];
for (var i = 0; i < callbacks.length; ++i)
callbacks[i](true);
callbacks = self._callbacks;
if (!server) {
// align more with node child processes, where the close event gets the
// same arguments as the exit event
if (!self.readable) {
if (exitCode === null) {
self.emit('close', exitCode, exitSignal, exitDump, exitDesc,
exitLang);
} else
self.emit('close', exitCode);
} else {
self.once('end', function() {
if (exitCode === null) {
self.emit('close', exitCode, exitSignal, exitDump, exitDesc,
exitLang);
} else
self.emit('close', exitCode);
});
}
if (!self.stderr.readable)
self.stderr.emit('close');
else {
self.stderr.once('end', function() {
self.stderr.emit('close');
});
}
} else { // Server mode
if (!self.readable)
self.emit('close');
else {
self.once('end', function() {
self.emit('close');
});
}
}
for (var i = 0; i < CUSTOM_EVENTS_LEN; ++i)
sshstream.removeAllListeners(CUSTOM_EVENTS[i] + ':' + incomingId);
}).on('CHANNEL_DATA:' + incomingId, function(data) {
// the remote party should not be sending us data if there is no window
// space available ...
if (incoming.window === 0)
return;
incoming.window -= data.length;
if (!self.push(data)) {
self._waitChanDrain = true;
return;
}
if (incoming.window <= WINDOW_THRESHOLD)
windowAdjust(self);
}).on('CHANNEL_WINDOW_ADJUST:' + incomingId, function(amt) {
// the server is allowing us to send `amt` more bytes of data
outgoing.window += amt;
if (self._waitWindow) {
self._waitWindow = false;
if (!self._waitClientDrain) {
if (self._chunk)
self._write(self._chunk, null, self._chunkcb);
else if (self._chunkcb)
self._chunkcb();
else if (self._chunkErr)
self.stderr._write(self._chunkErr, null, self._chunkcbErr);
else if (self._chunkcbErr)
self._chunkcbErr();
}
}
}).on('CHANNEL_SUCCESS:' + incomingId, function() {
if (server) {
sshstream._kalast = Date.now();
sshstream._kacnt = 0;
} else
client._resetKA();
if (callbacks.length)
callbacks.shift()(false);
}).on('CHANNEL_FAILURE:' + incomingId, function() {
if (server) {
sshstream._kalast = Date.now();
sshstream._kacnt = 0;
} else
client._resetKA();
if (callbacks.length)
callbacks.shift()(true);
}).on('CHANNEL_REQUEST:' + incomingId, function(info) {
if (!server) {
if (info.request === 'exit-status') {
self.emit('exit', exitCode = info.code);
return;
} else if (info.request === 'exit-signal') {
self.emit('exit',
exitCode = null,
exitSignal = 'SIG' + info.signal,
exitDump = info.coredump,
exitDesc = info.description,
exitLang = info.lang);
return;
}
}
// keepalive request? OpenSSH will send one as a channel request if there
// is a channel open
if (info.wantReply)
sshstream.channelFailure(outgoing.id);
});
this.stdin = this.stdout = this;
if (server)
this.stderr = new ServerStderr(this);
else {
this.stderr = new ReadableStream(streamOpts);
this.stderr._read = function(n) {
if (self._waitChanDrain) {
self._waitChanDrain = false;
if (incoming.window <= WINDOW_THRESHOLD)
windowAdjust(self);
}
};
sshstream.on('CHANNEL_EXTENDED_DATA:' + incomingId,
function(type, data) {
// the remote party should not be sending us data if there is no window
// space available ...
if (incoming.window === 0)
return;
incoming.window -= data.length;
if (!self.stderr.push(data)) {
self._waitChanDrain = true;
return;
}
if (incoming.window <= WINDOW_THRESHOLD)
windowAdjust(self);
}
);
}
// outgoing data
this._waitClientDrain = false; // Client stream-level backpressure
this._waitWindow = false; // SSH-level backpressure
// incoming data
this._waitChanDrain = false; // Channel Readable side backpressure
this._chunk = undefined;
this._chunkcb = undefined;
this._chunkErr = undefined;
this._chunkcbErr = undefined;
function onFinish() {
self.eof();
if (server || (!server && !self.allowHalfOpen))
self.close();
self.writable = false;
}
this.on('finish', onFinish)
.on('prefinish', onFinish); // for node v0.11+
function onEnd() {
self.readable = false;
}
this.on('end', onEnd)
.on('close', onEnd);
}
inherits(Channel, DuplexStream);
Channel.prototype.eof = function() {
var ret = true;
var outgoing = this.outgoing;
if (outgoing.state === 'open') {
outgoing.state = 'eof';
ret = this._client._sshstream.channelEOF(outgoing.id);
}
return ret;
};
Channel.prototype.close = function() {
var ret = true;
var outgoing = this.outgoing;
if (outgoing.state === 'open' || outgoing.state === 'eof') {
outgoing.state = 'closing';
ret = this._client._sshstream.channelClose(outgoing.id);
}
return ret;
};
Channel.prototype._read = function(n) {
if (this._waitChanDrain) {
this._waitChanDrain = false;
if (this.incoming.window <= WINDOW_THRESHOLD)
windowAdjust(this);
}
};
Channel.prototype._write = function(data, encoding, cb) {
var sshstream = this._client._sshstream;
var outgoing = this.outgoing;
var packetSize = outgoing.packetSize;
var id = outgoing.id;
var window = outgoing.window;
var len = data.length;
var p = 0;
var ret;
var buf;
var sliceLen;
if (outgoing.state !== 'open')
return;
while (len - p > 0 && window > 0) {
sliceLen = len - p;
if (sliceLen > window)
sliceLen = window;
if (sliceLen > packetSize)
sliceLen = packetSize;
ret = sshstream.channelData(id, data.slice(p, p + sliceLen));
p += sliceLen;
window -= sliceLen;
if (!ret) {
this._waitClientDrain = true;
this._chunk = undefined;
this._chunkcb = cb;
break;
}
}
outgoing.window = window;
if (len - p > 0) {
if (window === 0)
this._waitWindow = true;
if (p > 0) {
// partial
buf = new Buffer(len - p);
data.copy(buf, 0, p);
this._chunk = buf;
} else
this._chunk = data;
this._chunkcb = cb;
return;
}
if (!this._waitClientDrain)
cb();
};
Channel.prototype.destroy = function() {
this.end();
};
// session type-specific methods
Channel.prototype.setWindow = function(rows, cols, height, width) {
if (this.server)
throw new Error('Client-only method called in server mode');
if (this.type === 'session'
&& (this.subtype === 'shell' || this.subtype === 'exec')
&& this.writable
&& this.outgoing.state === 'open') {
return this._client._sshstream.windowChange(this.outgoing.id,
rows,
cols,
height,
width);
}
return true;
};
Channel.prototype.signal = function(signalName) {
if (this.server)
throw new Error('Client-only method called in server mode');
if (this.type === 'session'
&& this.writable
&& this.outgoing.state === 'open')
return this._client._sshstream.signal(this.outgoing.id, signalName);
return true;
};
Channel.prototype.exit = function(name, coreDumped, msg) {
if (!this.server)
throw new Error('Server-only method called in client mode');
if (this.type === 'session'
&& this.writable
&& this.outgoing.state === 'open') {
if (typeof name === 'number')
return this._client._sshstream.exitStatus(this.outgoing.id, name);
else {
return this._client._sshstream.exitSignal(this.outgoing.id,
name,
coreDumped,
msg);
}
}
return true;
};
Channel.MAX_WINDOW = MAX_WINDOW;
Channel.PACKET_SIZE = PACKET_SIZE;
function windowAdjust(self) {
if (self.outgoing.state !== 'open')
return true;
var amt = MAX_WINDOW - self.incoming.window;
if (amt <= 0)
return true;
self.incoming.window += amt;
return self._client._sshstream.channelWindowAdjust(self.outgoing.id, amt);
}
function ServerStderr(channel) {
WritableStream.call(this, { highWaterMark: MAX_WINDOW });
this._channel = channel;
}
inherits(ServerStderr, WritableStream);
ServerStderr.prototype._write = function(data, encoding, cb) {
var channel = this._channel;
var sshstream = channel._client._sshstream;
var outgoing = channel.outgoing;
var packetSize = outgoing.packetSize;
var id = outgoing.id;
var window = outgoing.window;
var len = data.length;
var p = 0;
var ret;
var buf;
var sliceLen;
if (channel.outgoing.state !== 'open')
return;
while (len - p > 0 && window > 0) {
sliceLen = len - p;
if (sliceLen > window)
sliceLen = window;
if (sliceLen > packetSize)
sliceLen = packetSize;
ret = sshstream.channelExtData(id, data.slice(p, p + sliceLen), STDERR);
p += sliceLen;
window -= sliceLen;
if (!ret) {
channel._waitClientDrain = true;
channel._chunkErr = undefined;
channel._chunkcbErr = cb;
break;
}
}
outgoing.window = window;
if (len - p > 0) {
if (window === 0)
channel._waitWindow = true;
if (p > 0) {
// partial
buf = new Buffer(len - p);
data.copy(buf, 0, p);
channel._chunkErr = buf;
} else
channel._chunkErr = data;
channel._chunkcbErr = cb;
return;
}
if (!channel._waitClientDrain)
cb();
};
module.exports = Channel;
|