-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
executable file
·611 lines (549 loc) · 16.4 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
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/**
* @package node-ssh
* @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax.org>
* @author Gabor Krizsanits <gabor AT ajax DOT org>
* @license http://github.com/ajaxorg/node-ssh/blob/master/LICENSE MIT License
*/
var ssh = require('./build/default/ssh');
//var constants = sftp.constants;
var fs = require("fs");
var path = require('path');
var constants = process.binding('constants');
var sys = require('sys');
var events = require('events');
/**
* Exported Object
*/
var SSH = module.exports = {};
/**
* Base class used by both ssh port forwarding and sftp
*/
function SSHBase(){
this.setupEvent = function() {
var _self = this;
// Every async task that is running in the wrapped c++ component
// emitts a callback event. When the last task is done, we want to
// start the next one.
this._session.on('callback',function(error,result,more){
// clear the timeout for the task (see _executeNext)
if (_self._timeout) {
clearTimeout(_self._timeout);
_self._timeout = 0;
}
var cb = _self._tasks[0].cb;
// _self._cb is used to prevent _addCommand to trigger an extra _executeNext
_self._cb = true;
// remove the exetuted task
_self._tasks.shift();
if (cb && typeof cb == "function"){
// executing the callback of the finished task
cb(error,result,more);
}
_self._cb = false;
// start next task
_self._executeNext();
});
};
// queue a new task
this._addCommand = function(cmd, args, cb) {
var task = {
cmd:cmd,
args:args,
cb:cb
};
this._tasks.push(task);
// if there was no running task, execute it asap:
if (this._tasks.length == 1 && !this._cb)
this._executeNext();
};
// executes next task on the queue
this._executeNext = function() {
var self = this;
if (this._tasks.length>0) {
//console.error('execute: ', this._tasks[0].cmd);
if (this._timeout) {
clearTimeout(this._timeout);
}
// setting a timeout, if it times out, we have to interrupt the blocking
// operation, then we report the error
if (this._tasks[0].cmd != 'spawn')
this._timeout = setTimeout(function(){
clearTimeout(this._timeout);
self._timeout = 0;
console.error("error: sftp timeout");
self._session.removeAllListeners("callback");
self._session.interrupt();
self._lastCb = self._tasks[0].cb;
console.error(self._tasks[0].cmd);
if (self._tasks[0].cb)
return self._tasks[0].cb(
"Error: SSH: Connection timed out");
}, 15000);
//console.error('setTIMEOUT: ', this._timeout);
// if the command starts with '_' that means it's a javascript function
// to call, otherwise it's a c++ function on _session:
if (this._tasks[0].cmd.indexOf("_") === 0)
this[this._tasks[0].cmd].apply(this, this._tasks[0].args);
else {
this._session[this._tasks[0].cmd].apply(this._session, this._tasks[0].args);
}
}
else
{
// no commands left, let's send out a command after a while for
// stay alive
this._timeout = setTimeout(function(){
self.stat("");},100000);
}
};
this.init = function(options, cb) {
if (!options ||
!options.host ||
!options.user ||
!options.port)
throw new Error('Invalid argument.');
if (!cb)
cb = function(){};
var self = this;
this._session.init(options);
this._options = options;
if (options.pubKey && options.prvKey) {
this.setPubKey(options.pubKey, function(error){
if (error)
return cb(error);
self.setPrvKey(options.prvKey, function(error){
self._inited = true;
cb(error);
});
});
}
else
self._inited = true;
};
this.setPubKey = function(pub, cb) {
var _self = this;
if (!cb)
cb = function(){};
this._addCommand("_writeTmpFile", [pub], function(error, tmp) {
if (error)
return cb(error);
_self._addCommand("setPubKey", [tmp], function(error) {
fs.unlink(tmp);
cb(error);
});
});
};
this.setPrvKey = function(prv, cb) {
var _self = this;
if (!cb)
cb = function(){};
this._addCommand("_writeTmpFile", [prv], function(error, tmp) {
if (error)
return cb(error);
_self._addCommand("setPrvKey", [tmp], function(error) {
//fs.unlink(tmp);
cb(error);
});
});
};
this.connect = function(cb) {
this._addCommand("connect", [], cb);
};
this._openTmpFile = function() {
var tmpFile = tmpDir + "/" + uuid();
var _self = this;
fs.open(tmpFile, "w+", function(error, fd) {
_self._session.emit("callback", error, {fd:fd, path:tmpFile});
});
};
this._writeTmpFile = function(data) {
var tmpFile = tmpDir + "/" + uuid();
var _self = this;
fs.writeFile(tmpFile, data, function(error) {
_self._session.emit("callback", error, tmpFile);
});
};
this._readTmpFile = function(path) {
var _self = this;
fs.readFile(path, function(error, data) {
_self._session.emit("callback", error, data);
fs.unlink(path);
});
};
}
var SFTP = SSH.sftp = function () {
this._session = new ssh.SFTP();
this._tasks = [];
this._subTasks = [];
this._callback = false;
this._timeout = 0;
this._options = {};
this._stats = {};
this.setupEvent();
};
(function(){
SSHBase.call(this);
this.isConnected = function() {
return this._session.isConnected();
};
this._recreate = function() {
this._session = new ssh.SFTP();
};
/**
* Async mkdir, the callback gets the error message on failure.
*
* @param {String} path
* @param {String,octal} mode
* @param {Function} cb
* @type {void}
*/
this.mkdir = function(path, mode, cb) {
if (typeof path !== "string")
throw new Error('Invalid argument.');
if (typeof mode === "string")
mode = parseInt(mode,10);
if (typeof mode !== "number")
throw new Error('Invalid argument.');
this._addCommand("mkdir", [path, mode], cb);
};
/**
* Asynchronously writes data to a file. data can be a string or a buffer.
* Example:
* <pre class="code">
* sftp.writeFile("message.txt", "Hello Node", function(err) {
* if (err)
* throw err;
* console.log("It's saved!");
* });
* </pre>
*
* @param {String} filename
* @param {String,Buffer} data
* @param {String} encoding
* @param {Function} callback
* @type {void}
*/
this.writeFile = function(path, data, type, cb) {
if (typeof data === 'string') {
data = new Buffer(data);
//console.log(data);
}
if (typeof type === 'function')
cb = type;
if (typeof path !== "string" || typeof data !== "object")
throw new Error('Invalid argument.');
this._addCommand("writeFile", [path, data], cb);
};
/**
* Asynchronously reads the entire contents of a file.
* The callback is passed two arguments (err, data), where data is the contents
* of the file.
* If no encoding is specified, then the raw buffer is returned.
* Example:
* <pre class="code">
* sftp.readFile("/etc/passwd", function(err, data) {
* if (err)
* throw err;
* console.log(data);
* });
* </pre>
*
* @param {String} filename
* @param {String} encoding
* @param {Function} callback
* @type {void}
*/
this.readFile = function(path, type, cb) {
if (typeof path !== "string")
throw new Error('Invalid argument.');
if (typeof type === 'function')
cb = type;
var _self = this;
this._addCommand("_openTmpFile", [], function(error, tmp) {
if (error)
return cb(error);
_self._addCommand("readFile", [tmp.fd, path], function(error) {
if (error)
return cb(error);
fs.closeSync(tmp.fd);
_self._addCommand("_readTmpFile", [tmp.path], function(error, data){
if (error == null)
error = "";
fs.unlink(tmp.path);
return cb(error, data);
});
});
});
};
/**
* Async list a directory, the callback gets two arguments, the error message
* on failure and the array of names of the children. '.' and '..' are exluded.
*
* @param {String} path
* @param {Function} cb
* @type {void}
*/
this.readdir = function(path,cb) {
if (typeof path !== "string")
throw new Error('Invalid argument.');
var self = this;
this._addCommand("listDir", [path], function(err, entries, stats) {
for (var i=0, l=entries.length; i<l; i++) {
self._stats[path + '/' + entries[i]] = stats[i];
//console.error("stat: ", i, stats[i], stats[i].isDirectory());
}
cb(err, entries);
});
};
/**
* Async rename, the callback gets the error message on failure.
*
* @param {String} path
* @param {String} to
* @param {Function} cb
* @type {void}
*/
this.rename = function(path, to, cb) {
if (typeof path !== "string" || typeof to !== "string")
throw new Error('Invalid argument.');
this._addCommand("rename", [path, to], cb);
};
/**
* Async chomd, the callback gets the error message on failure.
*
* @param {String} path
* @param {String, octal} mode
* @param {Function} cb
* @type {void}
*/
this.chmod = function(path, mode, cb) {
if (typeof mode === "string")
mode = parseInt(mode,10);
if (typeof path !== "string" || typeof mode !== "number")
throw new Error('Invalid argument.');
this._addCommand("chmod", [path, mode], cb);
};
/**
* Async chown, the callback gets the error message on failure.
*
* @param {String} path
* @param {String, number} uid
* @param {String, octal} gid
* @param {Function} cb
* @type {void}
*/
this.chown = function(path, uid, gid, cb) {
if (typeof uid === "string")
uid = parseInt(mode,10);
if (typeof gid === "string")
gid = parseInt(mode,10);
if (typeof path !== "string" ||
typeof uid !== "number" ||
typeof gid !== "number")
throw new Error('Invalid argument.');
this._addCommand("chown", [path, uid, gid], cb);
};
/**
* Async stat, the callback gets two arguments, the error string and a stat
* object. On error the stat object is undefined.
*
* @param {String} path
* @param {Function} cb
* @type {void}
*/
this.stat = function(path, cb) {
// console.error("stat ", path);
if (typeof path !== "string")
throw new Error('Invalid argument.');
if (path && this._stats[path])
cb("", this._stats[path]);
else
this._addCommand("stat", [path], cb);
};
/*
this.lstat = function(path, cb) {
this._addCommand("lstat", [path], cb);
};
this.sftptat = function(fd, cb) {
this._addCommand("sftptat", [path], cb);
};
*/
/**
* Async delete file, the callback gets the error message on failure.
*
* @param {String} path
* @param {Function} cb
* @type {void}
*/
this.unlink = function(path, cb) {
if (typeof path !== "string")
throw new Error('Invalid argument.');
this._addCommand("unlink", [path], cb);
};
/**
* Asynch remove directory. Directory must be empty. The callback gets the
* error message on failure.
*
* @param {String} path
* @param {Function} cb
* @type {void}
*/
this.rmdir = function(path, cb) {
if (typeof path !== "string")
throw new Error('Invalid argument.');
this._addCommand("rmdir", [path], cb);
};
this.spawn = function(command, args, options) {
if (typeof command !== "string")
throw new Error('Invalid argument.');
if (options && options.cwd)
command = "cd " + options.cwd + " && " + command;
if (options && options.env)
for (var key in options.env)
command = key + "=" + options.env[key] + " && " + command;
if (args)
command = command + " '" + args.join("' '") + "'";
var child = new Child(this);
this._session.removeAllListeners("stderr");
this._session.removeAllListeners("stdout");
//console.error(command);
this._session.on("stderr", function(data){
child.stderr.emit("data", data);
});
this._session.on("stdout", function(data){
child.stdout.emit("data", data);
});
this._addCommand("spawn", [command], function(exit, error){
//console.log("FFS!!!!!!!!!!!!!!!");
child.emit("exit", exit, error);
});
return child;
};
}).call(SFTP.prototype);
var Tunnel = SSH.tunnel = function () {
events.EventEmitter.call(this);
this._session = new ssh.Tunnel();
this._tasks = [];
this._subTasks = [];
this._callback = false;
this._timeout = 0;
this._options = {};
this._stats = {};
this.setupEvent();
};
sys.inherits(Tunnel, events.EventEmitter);
(function(){
SSHBase.call(this);
this._recreate = function() {
this._session = new ssh.Tunnel();
};
this.write = function(data, cb) {
if (typeof data === 'string') {
data = new Buffer(data);
//console.log(data);
}
if (typeof data !== "object")
throw new Error('Invalid argument.');
this._addCommand("write", [data], cb);
};
this.read = function(cb) {
var self = this;
this._addCommand("read", [], cb);
};
this.startReading = function() {
var self = this;
var cb = function(){
//console.log(".");
self.read(function(err, data) {
if (data || err) {
self.emit("data", err, data);
}
setTimeout(cb, data ? 100 : 500);
});
};
setTimeout(cb,100);
};
this.connect = function(cb) {
var self = this;
this._addCommand("connect", [], function(err){
self.startReading();
cb(err);
});
};
}).call(Tunnel.prototype);
// UTILS
var tmpDir = (function() {
var value,
def = "/tmp",
envVars = ["TMPDIR", "TMP", "TEMP"],
i = 0,
l = envVars.length;
for(; i < l; ++i) {
value = process.env[envVars[i]];
if (value)
return fs.realpathSync(value).replace(/\/+$/, "");
}
return fs.realpathSync(def).replace(/\/+$/, "");
})();
var uuid = function(len, radix) {
var i,
chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),
uuid = [],
rnd = Math.random;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++)
uuid[i] = chars[0 | rnd() * radix];
}
else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
uuid[14] = "4";
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | rnd() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
}
}
}
return uuid.join("");
};
var Child = function(sftp){
events.EventEmitter.call(this);
this._sftp = sftp;
this.stdout = new events.EventEmitter();
this.stderr = new events.EventEmitter();
this.kill = function(){
this._sftp._session.kill();
}
}
sys.inherits(Child, events.EventEmitter);
ssh.Stats.prototype._checkModeProperty = function(property) {
return ((this.mode & constants.S_IFMT) === property);
};
ssh.Stats.prototype.isDirectory = function() {
return this._checkModeProperty(constants.S_IFDIR);
};
ssh.Stats.prototype.isFile = function() {
return this._checkModeProperty(constants.S_IFREG);
};
ssh.Stats.prototype.isBlockDevice = function() {
return this._checkModeProperty(constants.S_IFBLK);
};
ssh.Stats.prototype.isCharacterDevice = function() {
return this._checkModeProperty(constants.S_IFCHR);
};
ssh.Stats.prototype.isSymbolicLink = function() {
return this._checkModeProperty(constants.S_IFLNK);
};
ssh.Stats.prototype.isFIFO = function() {
return this._checkModeProperty(constants.S_IFIFO);
};
ssh.Stats.prototype.isSocket = function() {
return this._checkModeProperty(constants.S_IFSOCK);
};