-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathpty_win.js
354 lines (270 loc) · 7.36 KB
/
pty_win.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
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
/**
* pty_win.js
* Copyright (c) 2012-2015, Christopher Jeffrey, Peter Sunde (MIT License)
*/
var net = require('net');
var path = require('path');
var extend = require('extend');
var inherits = require('util').inherits;
var BaseTerminal = require('./pty').Terminal;
var pty = require('../build/Release/pty.node');
// Counter of number of "pipes" created so far.
var pipeIncr = 0;
/**
* Agent. Internal class.
*
* Everytime a new pseudo terminal is created it is contained
* within agent.exe. When this process is started there are two
* available named pipes (control and data socket).
*/
function Agent(file, args, env, cwd, cols, rows, debug) {
var self = this;
// Increment the number of pipes created.
pipeIncr++;
// Unique identifier per pipe created.
var timestamp = Date.now();
// The data pipe is the direct connection to the forked terminal.
this.dataPipe = '\\\\.\\pipe\\winpty-data-' + pipeIncr + '' + timestamp;
// Dummy socket for awaiting `ready` event.
this.ptySocket = new net.Socket();
// Create terminal pipe IPC channel and forward
// to a local unix socket.
this.ptyDataPipe = net.createServer(function (socket) {
// Default socket encoding.
socket.setEncoding('utf8');
// Pause until `ready` event is emitted.
socket.pause();
// Sanitize input variable.
file = file;
args = args.join(' ');
cwd = path.resolve(cwd);
// Start terminal session.
pty.startProcess(self.pid, file, args, env, cwd);
// Emit ready event.
self.ptySocket.emit('ready_datapipe', socket);
}).listen(this.dataPipe);
// Open pty session.
var term = pty.open(self.dataPipe, cols, rows, debug);
// Terminal pid.
this.pid = term.pid;
// Not available on windows.
this.fd = term.fd;
// Generated incremental number that has no real purpose besides
// using it as a terminal id.
this.pty = term.pty;
}
/**
* Terminal
*/
/*
var pty = require('./');
var term = pty.fork('cmd.exe', [], {
name: 'Windows Shell',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env,
debug: true
});
term.on('data', function(data) {
console.log(data);
});
*/
function Terminal(file, args, opt) {
var self = this,
env, cwd, name, cols, rows, term, agent, debug;
// Backward compatibility.
if (typeof args === 'string') {
opt = {
name: arguments[1],
cols: arguments[2],
rows: arguments[3],
cwd: process.env.HOME
};
args = [];
}
// Arguments.
args = args || [];
file = file || 'cmd.exe';
opt = opt || {};
env = extend({}, opt.env);
cols = opt.cols || 80;
rows = opt.rows || 30;
cwd = opt.cwd || process.cwd();
name = opt.name || env.TERM || 'Windows Shell';
debug = opt.debug || false;
env.TERM = name;
// Initialize environment variables.
env = environ(env);
// If the terminal is ready
this.isReady = false;
// Functions that need to run after `ready` event is emitted.
this.deferreds = [];
// Create new termal.
this.agent = new Agent(file, args, env, cwd, cols, rows, debug);
// The dummy socket is used so that we can defer everything
// until its available.
this.socket = this.agent.ptySocket;
// The terminal socket when its available
this.dataPipe = null;
// Not available until `ready` event emitted.
this.pid = this.agent.pid;
this.fd = this.agent.fd;
this.pty = this.agent.pty;
// The forked windows terminal is not available
// until `ready` event is emitted.
this.socket.on('ready_datapipe', function (socket) {
// Set terminal socket
self.dataPipe = socket;
// These events needs to be forwarded.
['connect', 'data', 'end', 'timeout', 'drain'].forEach(function(event) {
self.dataPipe.on(event, function(data) {
// Wait until the first data event is fired
// then we can run deferreds.
if(!self.isReady && event == 'data') {
// Terminal is now ready and we can
// avoid having to defer method calls.
self.isReady = true;
// Execute all deferred methods
self.deferreds.forEach(function(fn) {
// NB! In order to ensure that `this` has all
// its references updated any variable that
// need to be available in `this` before
// the deferred is run has to be declared
// above this forEach statement.
fn.run();
});
// Reset
self.deferreds = [];
}
// Emit to dummy socket
self.socket.emit(event, data);
});
});
// Resume socket.
self.dataPipe.resume();
// Shutdown if `error` event is emitted.
self.dataPipe.on('error', function (err) {
// Close terminal session.
self._close();
// EIO, happens when someone closes our child
// process: the only process in the terminal.
// node < 0.6.14: errno 5
// node >= 0.6.14: read EIO
if (err.code) {
if (~err.code.indexOf('errno 5') || ~err.code.indexOf('EIO')) return;
}
// Throw anything else.
if (self.listeners('error').length < 2) {
throw err;
}
});
// Cleanup after the socket is closed.
self.dataPipe.on('close', function () {
Terminal.total--;
self.emit('exit', null);
self._close();
});
});
this.file = file;
this.name = name;
this.cols = cols;
this.rows = rows;
this.readable = true;
this.writable = true;
Terminal.total++;
}
Terminal.fork =
Terminal.spawn =
Terminal.createTerminal = function (file, args, opt) {
return new Terminal(file, args, opt);
};
// Inherit from pty.js
inherits(Terminal, BaseTerminal);
// Keep track of the total
// number of terminals for
// the process.
Terminal.total = 0;
/**
* Events
*/
/**
* openpty
*/
Terminal.open = function () {
throw new Error("open() not supported on windows, use Fork() instead.");
};
/**
* Events
*/
Terminal.prototype.write = function(data) {
defer(this, function() {
this.dataPipe.write(data);
});
};
/**
* TTY
*/
Terminal.prototype.resize = function (cols, rows) {
defer(this, function() {
cols = cols || 80;
rows = rows || 24;
this.cols = cols;
this.rows = rows;
pty.resize(this.pid, cols, rows);
});
};
Terminal.prototype.destroy = function () {
defer(this, function() {
this.kill();
});
};
Terminal.prototype.kill = function (sig) {
defer(this, function() {
if (sig !== undefined) {
throw new Error("Signals not supported on windows.");
}
this._close();
pty.kill(this.pid);
});
};
Terminal.prototype.__defineGetter__('process', function () {
return this.name;
});
/**
* Helpers
*/
function defer(terminal, deferredFn) {
// Ensure that this method is only used within Terminal class.
if (!(terminal instanceof Terminal)) {
throw new Error("Must be instanceof Terminal");
}
// If the terminal is ready, execute.
if (terminal.isReady) {
deferredFn.apply(terminal, null);
return;
}
// Queue until terminal is ready.
terminal.deferreds.push({
run: function() {
// Run deffered.
deferredFn.apply(terminal, null);
}
});
}
function environ(env) {
var keys = Object.keys(env || {})
, l = keys.length
, i = 0
, pairs = [];
for (; i < l; i++) {
pairs.push(keys[i] + '=' + env[keys[i]]);
}
return pairs;
}
/**
* Expose
*/
module.exports = exports = Terminal;
exports.Terminal = Terminal;
exports.native = pty;