Channel.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. var inherits = require('util').inherits;
  2. var DuplexStream = require('stream').Duplex;
  3. var ReadableStream = require('stream').Readable;
  4. var WritableStream = require('stream').Writable;
  5. var STDERR = require('ssh2-streams').constants.CHANNEL_EXTENDED_DATATYPE.STDERR;
  6. var PACKET_SIZE = 32 * 1024;
  7. var MAX_WINDOW = 1 * 1024 * 1024;
  8. var WINDOW_THRESHOLD = MAX_WINDOW / 2;
  9. var CUSTOM_EVENTS = [
  10. 'CHANNEL_EOF',
  11. 'CHANNEL_CLOSE',
  12. 'CHANNEL_DATA',
  13. 'CHANNEL_EXTENDED_DATA',
  14. 'CHANNEL_WINDOW_ADJUST',
  15. 'CHANNEL_SUCCESS',
  16. 'CHANNEL_FAILURE',
  17. 'CHANNEL_REQUEST'
  18. ];
  19. var CUSTOM_EVENTS_LEN = CUSTOM_EVENTS.length;
  20. function Channel(info, client, opts) {
  21. var streamOpts = {
  22. highWaterMark: MAX_WINDOW,
  23. allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false))
  24. };
  25. this.allowHalfOpen = streamOpts.allowHalfOpen;
  26. DuplexStream.call(this, streamOpts);
  27. var self = this;
  28. var server = opts && opts.server;
  29. this.server = server;
  30. this.type = info.type;
  31. this.subtype = undefined;
  32. /*
  33. incoming and outgoing contain these properties:
  34. {
  35. id: undefined,
  36. window: undefined,
  37. packetSize: undefined,
  38. state: 'closed'
  39. }
  40. */
  41. var incoming = this.incoming = info.incoming;
  42. var incomingId = incoming.id;
  43. var outgoing = this.outgoing = info.outgoing;
  44. var callbacks = this._callbacks = [];
  45. var exitCode;
  46. var exitSignal;
  47. var exitDump;
  48. var exitDesc;
  49. var exitLang;
  50. this._client = client;
  51. this._hasX11 = false;
  52. var channels = client._channels;
  53. var sshstream = client._sshstream;
  54. function ondrain() {
  55. if (self._waitClientDrain) {
  56. self._waitClientDrain = false;
  57. if (!self._waitWindow) {
  58. if (self._chunk)
  59. self._write(self._chunk, null, self._chunkcb);
  60. else if (self._chunkcb)
  61. self._chunkcb();
  62. else if (self._chunkErr)
  63. self.stderr._write(self._chunkErr, null, self._chunkcbErr);
  64. else if (self._chunkcbErr)
  65. self._chunkcbErr();
  66. }
  67. }
  68. }
  69. client._sock.on('drain', ondrain);
  70. sshstream.once('CHANNEL_EOF:' + incomingId, function() {
  71. if (incoming.state !== 'open')
  72. return;
  73. incoming.state = 'eof';
  74. if (self.readable)
  75. self.push(null);
  76. if (!server && self.stderr.readable)
  77. self.stderr.push(null);
  78. }).once('CHANNEL_CLOSE:' + incomingId, function() {
  79. if (incoming.state === 'closed')
  80. return;
  81. incoming.state = 'closed';
  82. if (self.readable)
  83. self.push(null);
  84. if (server && self.stderr.writable)
  85. self.stderr.end();
  86. else if (!server && self.stderr.readable)
  87. self.stderr.push(null);
  88. if (outgoing.state === 'open' || outgoing.state === 'eof')
  89. self.close();
  90. if (outgoing.state === 'closing')
  91. outgoing.state = 'closed';
  92. delete channels[incomingId];
  93. var state = self._writableState;
  94. client._sock.removeListener('drain', ondrain);
  95. if (!state.ending && !state.finished)
  96. self.end();
  97. // Take care of any outstanding channel requests
  98. self._callbacks = [];
  99. for (var i = 0; i < callbacks.length; ++i)
  100. callbacks[i](true);
  101. callbacks = self._callbacks;
  102. if (!server) {
  103. // align more with node child processes, where the close event gets the
  104. // same arguments as the exit event
  105. if (!self.readable) {
  106. if (exitCode === null) {
  107. self.emit('close', exitCode, exitSignal, exitDump, exitDesc,
  108. exitLang);
  109. } else
  110. self.emit('close', exitCode);
  111. } else {
  112. self.once('end', function() {
  113. if (exitCode === null) {
  114. self.emit('close', exitCode, exitSignal, exitDump, exitDesc,
  115. exitLang);
  116. } else
  117. self.emit('close', exitCode);
  118. });
  119. }
  120. if (!self.stderr.readable)
  121. self.stderr.emit('close');
  122. else {
  123. self.stderr.once('end', function() {
  124. self.stderr.emit('close');
  125. });
  126. }
  127. } else { // Server mode
  128. if (!self.readable)
  129. self.emit('close');
  130. else {
  131. self.once('end', function() {
  132. self.emit('close');
  133. });
  134. }
  135. }
  136. for (var i = 0; i < CUSTOM_EVENTS_LEN; ++i)
  137. sshstream.removeAllListeners(CUSTOM_EVENTS[i] + ':' + incomingId);
  138. }).on('CHANNEL_DATA:' + incomingId, function(data) {
  139. // the remote party should not be sending us data if there is no window
  140. // space available ...
  141. // TODO: raise error on data with not enough window
  142. if (incoming.window === 0)
  143. return;
  144. incoming.window -= data.length;
  145. if (!self.push(data)) {
  146. self._waitChanDrain = true;
  147. return;
  148. }
  149. if (incoming.window <= WINDOW_THRESHOLD)
  150. windowAdjust(self);
  151. }).on('CHANNEL_WINDOW_ADJUST:' + incomingId, function(amt) {
  152. // the server is allowing us to send `amt` more bytes of data
  153. outgoing.window += amt;
  154. if (self._waitWindow) {
  155. self._waitWindow = false;
  156. if (!self._waitClientDrain) {
  157. if (self._chunk)
  158. self._write(self._chunk, null, self._chunkcb);
  159. else if (self._chunkcb)
  160. self._chunkcb();
  161. else if (self._chunkErr)
  162. self.stderr._write(self._chunkErr, null, self._chunkcbErr);
  163. else if (self._chunkcbErr)
  164. self._chunkcbErr();
  165. }
  166. }
  167. }).on('CHANNEL_SUCCESS:' + incomingId, function() {
  168. if (server) {
  169. sshstream._kalast = Date.now();
  170. sshstream._kacnt = 0;
  171. } else
  172. client._resetKA();
  173. if (callbacks.length)
  174. callbacks.shift()(false);
  175. }).on('CHANNEL_FAILURE:' + incomingId, function() {
  176. if (server) {
  177. sshstream._kalast = Date.now();
  178. sshstream._kacnt = 0;
  179. } else
  180. client._resetKA();
  181. if (callbacks.length)
  182. callbacks.shift()(true);
  183. }).on('CHANNEL_REQUEST:' + incomingId, function(info) {
  184. if (!server) {
  185. if (info.request === 'exit-status') {
  186. self.emit('exit', exitCode = info.code);
  187. return;
  188. } else if (info.request === 'exit-signal') {
  189. self.emit('exit',
  190. exitCode = null,
  191. exitSignal = 'SIG' + info.signal,
  192. exitDump = info.coredump,
  193. exitDesc = info.description,
  194. exitLang = info.lang);
  195. return;
  196. }
  197. }
  198. // keepalive request? OpenSSH will send one as a channel request if there
  199. // is a channel open
  200. if (info.wantReply)
  201. sshstream.channelFailure(outgoing.id);
  202. });
  203. this.stdin = this.stdout = this;
  204. if (server)
  205. this.stderr = new ServerStderr(this);
  206. else {
  207. this.stderr = new ReadableStream(streamOpts);
  208. this.stderr._read = function(n) {
  209. if (self._waitChanDrain) {
  210. self._waitChanDrain = false;
  211. if (incoming.window <= WINDOW_THRESHOLD)
  212. windowAdjust(self);
  213. }
  214. };
  215. sshstream.on('CHANNEL_EXTENDED_DATA:' + incomingId,
  216. function(type, data) {
  217. // the remote party should not be sending us data if there is no window
  218. // space available ...
  219. // TODO: raise error on data with not enough window
  220. if (incoming.window === 0)
  221. return;
  222. incoming.window -= data.length;
  223. if (!self.stderr.push(data)) {
  224. self._waitChanDrain = true;
  225. return;
  226. }
  227. if (incoming.window <= WINDOW_THRESHOLD)
  228. windowAdjust(self);
  229. }
  230. );
  231. }
  232. // outgoing data
  233. this._waitClientDrain = false; // Client stream-level backpressure
  234. this._waitWindow = false; // SSH-level backpressure
  235. // incoming data
  236. this._waitChanDrain = false; // Channel Readable side backpressure
  237. this._chunk = undefined;
  238. this._chunkcb = undefined;
  239. this._chunkErr = undefined;
  240. this._chunkcbErr = undefined;
  241. function onFinish() {
  242. self.eof();
  243. if (server || (!server && !self.allowHalfOpen))
  244. self.close();
  245. self.writable = false;
  246. }
  247. this.on('finish', onFinish)
  248. .on('prefinish', onFinish); // for node v0.11+
  249. function onEnd() {
  250. self.readable = false;
  251. }
  252. this.on('end', onEnd)
  253. .on('close', onEnd);
  254. }
  255. inherits(Channel, DuplexStream);
  256. Channel.prototype.eof = function() {
  257. var ret = true;
  258. var outgoing = this.outgoing;
  259. if (outgoing.state === 'open') {
  260. outgoing.state = 'eof';
  261. ret = this._client._sshstream.channelEOF(outgoing.id);
  262. }
  263. return ret;
  264. };
  265. Channel.prototype.close = function() {
  266. var ret = true;
  267. var outgoing = this.outgoing;
  268. if (outgoing.state === 'open' || outgoing.state === 'eof') {
  269. outgoing.state = 'closing';
  270. ret = this._client._sshstream.channelClose(outgoing.id);
  271. }
  272. return ret;
  273. };
  274. Channel.prototype._read = function(n) {
  275. if (this._waitChanDrain) {
  276. this._waitChanDrain = false;
  277. if (this.incoming.window <= WINDOW_THRESHOLD)
  278. windowAdjust(this);
  279. }
  280. };
  281. Channel.prototype._write = function(data, encoding, cb) {
  282. var sshstream = this._client._sshstream;
  283. var outgoing = this.outgoing;
  284. var packetSize = outgoing.packetSize;
  285. var id = outgoing.id;
  286. var window = outgoing.window;
  287. var len = data.length;
  288. var p = 0;
  289. var ret;
  290. var buf;
  291. var sliceLen;
  292. if (outgoing.state !== 'open')
  293. return;
  294. while (len - p > 0 && window > 0) {
  295. sliceLen = len - p;
  296. if (sliceLen > window)
  297. sliceLen = window;
  298. if (sliceLen > packetSize)
  299. sliceLen = packetSize;
  300. ret = sshstream.channelData(id, data.slice(p, p + sliceLen));
  301. p += sliceLen;
  302. window -= sliceLen;
  303. if (!ret) {
  304. this._waitClientDrain = true;
  305. this._chunk = undefined;
  306. this._chunkcb = cb;
  307. break;
  308. }
  309. }
  310. outgoing.window = window;
  311. if (len - p > 0) {
  312. if (window === 0)
  313. this._waitWindow = true;
  314. if (p > 0) {
  315. // partial
  316. buf = Buffer.allocUnsafe(len - p);
  317. data.copy(buf, 0, p);
  318. this._chunk = buf;
  319. } else
  320. this._chunk = data;
  321. this._chunkcb = cb;
  322. return;
  323. }
  324. if (!this._waitClientDrain)
  325. cb();
  326. };
  327. Channel.prototype.destroy = function() {
  328. this.end();
  329. };
  330. // session type-specific methods
  331. Channel.prototype.setWindow = function(rows, cols, height, width) {
  332. if (this.server)
  333. throw new Error('Client-only method called in server mode');
  334. if (this.type === 'session'
  335. && (this.subtype === 'shell' || this.subtype === 'exec')
  336. && this.writable
  337. && this.outgoing.state === 'open') {
  338. return this._client._sshstream.windowChange(this.outgoing.id,
  339. rows,
  340. cols,
  341. height,
  342. width);
  343. }
  344. return true;
  345. };
  346. Channel.prototype.signal = function(signalName) {
  347. if (this.server)
  348. throw new Error('Client-only method called in server mode');
  349. if (this.type === 'session'
  350. && this.writable
  351. && this.outgoing.state === 'open')
  352. return this._client._sshstream.signal(this.outgoing.id, signalName);
  353. return true;
  354. };
  355. Channel.prototype.exit = function(name, coreDumped, msg) {
  356. if (!this.server)
  357. throw new Error('Server-only method called in client mode');
  358. if (this.type === 'session'
  359. && this.writable
  360. && this.outgoing.state === 'open') {
  361. if (typeof name === 'number')
  362. return this._client._sshstream.exitStatus(this.outgoing.id, name);
  363. else {
  364. return this._client._sshstream.exitSignal(this.outgoing.id,
  365. name,
  366. coreDumped,
  367. msg);
  368. }
  369. }
  370. return true;
  371. };
  372. Channel.MAX_WINDOW = MAX_WINDOW;
  373. Channel.PACKET_SIZE = PACKET_SIZE;
  374. function windowAdjust(self) {
  375. if (self.outgoing.state === 'closed')
  376. return true;
  377. var amt = MAX_WINDOW - self.incoming.window;
  378. if (amt <= 0)
  379. return true;
  380. self.incoming.window += amt;
  381. return self._client._sshstream.channelWindowAdjust(self.outgoing.id, amt);
  382. }
  383. function ServerStderr(channel) {
  384. WritableStream.call(this, { highWaterMark: MAX_WINDOW });
  385. this._channel = channel;
  386. }
  387. inherits(ServerStderr, WritableStream);
  388. ServerStderr.prototype._write = function(data, encoding, cb) {
  389. var channel = this._channel;
  390. var sshstream = channel._client._sshstream;
  391. var outgoing = channel.outgoing;
  392. var packetSize = outgoing.packetSize;
  393. var id = outgoing.id;
  394. var window = outgoing.window;
  395. var len = data.length;
  396. var p = 0;
  397. var ret;
  398. var buf;
  399. var sliceLen;
  400. if (channel.outgoing.state !== 'open')
  401. return;
  402. while (len - p > 0 && window > 0) {
  403. sliceLen = len - p;
  404. if (sliceLen > window)
  405. sliceLen = window;
  406. if (sliceLen > packetSize)
  407. sliceLen = packetSize;
  408. ret = sshstream.channelExtData(id, data.slice(p, p + sliceLen), STDERR);
  409. p += sliceLen;
  410. window -= sliceLen;
  411. if (!ret) {
  412. channel._waitClientDrain = true;
  413. channel._chunkErr = undefined;
  414. channel._chunkcbErr = cb;
  415. break;
  416. }
  417. }
  418. outgoing.window = window;
  419. if (len - p > 0) {
  420. if (window === 0)
  421. channel._waitWindow = true;
  422. if (p > 0) {
  423. // partial
  424. buf = Buffer.allocUnsafe(len - p);
  425. data.copy(buf, 0, p);
  426. channel._chunkErr = buf;
  427. } else
  428. channel._chunkErr = data;
  429. channel._chunkcbErr = cb;
  430. return;
  431. }
  432. if (!channel._waitClientDrain)
  433. cb();
  434. };
  435. module.exports = Channel;