forked from mscdex/ssh2-streams
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sftp.js
3127 lines (2724 loc) · 89.4 KB
/
sftp.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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// TODO: support EXTENDED request packets
var TransformStream = require('stream').Transform;
var ReadableStream = require('stream').Readable;
var WritableStream = require('stream').Writable;
var constants = require('fs').constants || process.binding('constants');
var util = require('util');
var inherits = util.inherits;
var isDate = util.isDate;
var listenerCount = require('events').EventEmitter.listenerCount;
var fs = require('fs');
var readString = require('./utils').readString;
var readInt = require('./utils').readInt;
var readUInt32BE = require('./buffer-helpers').readUInt32BE;
var writeUInt32BE = require('./buffer-helpers').writeUInt32BE;
var ATTR = {
SIZE: 0x00000001,
UIDGID: 0x00000002,
PERMISSIONS: 0x00000004,
ACMODTIME: 0x00000008,
EXTENDED: 0x80000000
};
var STATUS_CODE = {
OK: 0,
EOF: 1,
NO_SUCH_FILE: 2,
PERMISSION_DENIED: 3,
FAILURE: 4,
BAD_MESSAGE: 5,
NO_CONNECTION: 6,
CONNECTION_LOST: 7,
OP_UNSUPPORTED: 8
};
Object.keys(STATUS_CODE).forEach(function(key) {
STATUS_CODE[STATUS_CODE[key]] = key;
});
var STATUS_CODE_STR = {
0: 'No error',
1: 'End of file',
2: 'No such file or directory',
3: 'Permission denied',
4: 'Failure',
5: 'Bad message',
6: 'No connection',
7: 'Connection lost',
8: 'Operation unsupported'
};
SFTPStream.STATUS_CODE = STATUS_CODE;
var REQUEST = {
INIT: 1,
OPEN: 3,
CLOSE: 4,
READ: 5,
WRITE: 6,
LSTAT: 7,
FSTAT: 8,
SETSTAT: 9,
FSETSTAT: 10,
OPENDIR: 11,
READDIR: 12,
REMOVE: 13,
MKDIR: 14,
RMDIR: 15,
REALPATH: 16,
STAT: 17,
RENAME: 18,
READLINK: 19,
SYMLINK: 20,
EXTENDED: 200
};
Object.keys(REQUEST).forEach(function(key) {
REQUEST[REQUEST[key]] = key;
});
var RESPONSE = {
VERSION: 2,
STATUS: 101,
HANDLE: 102,
DATA: 103,
NAME: 104,
ATTRS: 105,
EXTENDED: 201
};
Object.keys(RESPONSE).forEach(function(key) {
RESPONSE[RESPONSE[key]] = key;
});
var OPEN_MODE = {
READ: 0x00000001,
WRITE: 0x00000002,
APPEND: 0x00000004,
CREAT: 0x00000008,
TRUNC: 0x00000010,
EXCL: 0x00000020
};
SFTPStream.OPEN_MODE = OPEN_MODE;
var MAX_PKT_LEN = 34000;
var MAX_REQID = Math.pow(2, 32) - 1;
var CLIENT_VERSION_BUFFER = Buffer.from([0, 0, 0, 5 /* length */,
REQUEST.INIT,
0, 0, 0, 3 /* version */]);
var SERVER_VERSION_BUFFER = Buffer.from([0, 0, 0, 5 /* length */,
RESPONSE.VERSION,
0, 0, 0, 3 /* version */]);
/*
http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02:
The maximum size of a packet is in practice determined by the client
(the maximum size of read or write requests that it sends, plus a few
bytes of packet overhead). All servers SHOULD support packets of at
least 34000 bytes (where the packet size refers to the full length,
including the header above). This should allow for reads and writes
of at most 32768 bytes.
OpenSSH caps this to 256kb instead of the ~34kb as mentioned in the sftpv3
spec.
*/
var RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/;
var OPENSSH_MAX_DATA_LEN = (256 * 1024) - (2 * 1024)/*account for header data*/;
function DEBUG_NOOP(msg) {}
function SFTPStream(cfg, remoteIdentRaw) {
if (typeof cfg === 'string' && !remoteIdentRaw) {
remoteIdentRaw = cfg;
cfg = undefined;
}
if (typeof cfg !== 'object' || !cfg)
cfg = {};
TransformStream.call(this, {
highWaterMark: (typeof cfg.highWaterMark === 'number'
? cfg.highWaterMark
: 32 * 1024)
});
this.debug = (typeof cfg.debug === 'function' ? cfg.debug : DEBUG_NOOP);
this.server = (cfg.server ? true : false);
this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw));
this._needContinue = false;
this._state = {
// common
status: 'packet_header',
writeReqid: -1,
pktLeft: undefined,
pktHdrBuf: Buffer.allocUnsafe(9), // room for pktLen + pktType + req id
pktBuf: undefined,
pktType: undefined,
version: undefined,
extensions: {},
// client
maxDataLen: (this._isOpenSSH ? OPENSSH_MAX_DATA_LEN : 32768),
requests: {}
};
var self = this;
this.on('end', function() {
self.readable = false;
}).on('finish', onFinish)
.on('prefinish', onFinish);
function onFinish() {
self.writable = false;
self._cleanup(false);
}
if (!this.server)
this.push(CLIENT_VERSION_BUFFER);
}
inherits(SFTPStream, TransformStream);
SFTPStream.prototype.__read = TransformStream.prototype._read;
SFTPStream.prototype._read = function(n) {
if (this._needContinue) {
this._needContinue = false;
this.emit('continue');
}
return this.__read(n);
};
SFTPStream.prototype.__push = TransformStream.prototype.push;
SFTPStream.prototype.push = function(chunk, encoding) {
if (!this.readable)
return false;
if (chunk === null)
this.readable = false;
var ret = this.__push(chunk, encoding);
this._needContinue = (ret === false);
return ret;
};
SFTPStream.prototype._cleanup = function(callback) {
var state = this._state;
state.pktBuf = undefined; // give GC something to do
var requests = state.requests;
var keys = Object.keys(requests);
var len = keys.length;
if (len) {
if (this.readable) {
var err = new Error('SFTP session ended early');
for (var i = 0, cb; i < len; ++i)
(cb = requests[keys[i]].cb) && cb(err);
}
state.requests = {};
}
if (this.readable)
this.push(null);
if (!this._readableState.endEmitted && !this._readableState.flowing) {
// Ugh!
this.resume();
}
if (callback !== false) {
this.debug('DEBUG[SFTP]: Parser: Malformed packet');
callback && callback(new Error('Malformed packet'));
}
};
SFTPStream.prototype._transform = function(chunk, encoding, callback) {
var state = this._state;
var server = this.server;
var status = state.status;
var pktType = state.pktType;
var pktBuf = state.pktBuf;
var pktLeft = state.pktLeft;
var version = state.version;
var pktHdrBuf = state.pktHdrBuf;
var requests = state.requests;
var debug = this.debug;
var chunkLen = chunk.length;
var chunkPos = 0;
var buffer;
var chunkLeft;
var id;
while (true) {
if (status === 'discard') {
chunkLeft = (chunkLen - chunkPos);
if (pktLeft <= chunkLeft) {
chunkPos += pktLeft;
pktLeft = 0;
status = 'packet_header';
buffer = pktBuf = undefined;
} else {
pktLeft -= chunkLeft;
break;
}
} else if (pktBuf !== undefined) {
chunkLeft = (chunkLen - chunkPos);
if (pktLeft <= chunkLeft) {
chunk.copy(pktBuf,
pktBuf.length - pktLeft,
chunkPos,
chunkPos + pktLeft);
chunkPos += pktLeft;
pktLeft = 0;
buffer = pktBuf;
pktBuf = undefined;
continue;
} else {
chunk.copy(pktBuf, pktBuf.length - pktLeft, chunkPos);
pktLeft -= chunkLeft;
break;
}
} else if (status === 'packet_header') {
if (!buffer) {
pktLeft = 5;
pktBuf = pktHdrBuf;
} else {
// here we read the right-most 5 bytes from buffer (pktHdrBuf)
pktLeft = readUInt32BE(buffer, 4) - 1; // account for type byte
pktType = buffer[8];
if (server) {
if (version === undefined && pktType !== REQUEST.INIT) {
debug('DEBUG[SFTP]: Parser: Unexpected packet before init');
this._cleanup(false);
return callback(new Error('Unexpected packet before init'));
} else if (version !== undefined && pktType === REQUEST.INIT) {
debug('DEBUG[SFTP]: Parser: Unexpected duplicate init');
status = 'bad_pkt';
} else if (pktLeft > MAX_PKT_LEN) {
var msg = 'Packet length ('
+ pktLeft
+ ') exceeds max length ('
+ MAX_PKT_LEN
+ ')';
debug('DEBUG[SFTP]: Parser: ' + msg);
this._cleanup(false);
return callback(new Error(msg));
} else if (pktType === REQUEST.EXTENDED) {
status = 'bad_pkt';
} else if (REQUEST[pktType] === undefined) {
debug('DEBUG[SFTP]: Parser: Unsupported packet type: ' + pktType);
status = 'discard';
}
} else if (version === undefined && pktType !== RESPONSE.VERSION) {
debug('DEBUG[SFTP]: Parser: Unexpected packet before version');
this._cleanup(false);
return callback(new Error('Unexpected packet before version'));
} else if (version !== undefined && pktType === RESPONSE.VERSION) {
debug('DEBUG[SFTP]: Parser: Unexpected duplicate version');
status = 'bad_pkt';
} else if (RESPONSE[pktType] === undefined) {
status = 'discard';
}
if (status === 'bad_pkt') {
// Copy original packet info to left of pktHdrBuf
writeUInt32BE(pktHdrBuf, pktLeft + 1, 0);
pktHdrBuf[4] = pktType;
pktLeft = 4;
pktBuf = pktHdrBuf;
} else {
pktBuf = Buffer.allocUnsafe(pktLeft);
status = 'payload';
}
}
} else if (status === 'payload') {
if (pktType === RESPONSE.VERSION || pktType === REQUEST.INIT) {
/*
uint32 version
<extension data>
*/
version = state.version = readInt(buffer, 0, this, callback);
if (version === false)
return;
if (version < 3) {
this._cleanup(false);
return callback(new Error('Incompatible SFTP version: ' + version));
} else if (server)
this.push(SERVER_VERSION_BUFFER);
var buflen = buffer.length;
var extname;
var extdata;
buffer._pos = 4;
while (buffer._pos < buflen) {
extname = readString(buffer, buffer._pos, 'ascii', this, callback);
if (extname === false)
return;
extdata = readString(buffer, buffer._pos, 'ascii', this, callback);
if (extdata === false)
return;
if (state.extensions[extname])
state.extensions[extname].push(extdata);
else
state.extensions[extname] = [ extdata ];
}
this.emit('ready');
} else {
/*
All other packets (client and server) begin with a (client) request
id:
uint32 id
*/
id = readInt(buffer, 0, this, callback);
if (id === false)
return;
var filename;
var attrs;
var handle;
var data;
if (!server) {
var req = requests[id];
var cb = req && req.cb;
debug('DEBUG[SFTP]: Parser: Response: ' + RESPONSE[pktType]);
if (req && cb) {
if (pktType === RESPONSE.STATUS) {
/*
uint32 error/status code
string error message (ISO-10646 UTF-8)
string language tag
*/
var code = readInt(buffer, 4, this, callback);
if (code === false)
return;
if (code === STATUS_CODE.OK) {
cb();
} else {
// We borrow OpenSSH behavior here, specifically we make the
// message and language fields optional, despite the
// specification requiring them (even if they are empty). This
// helps to avoid problems with buggy implementations that do
// not fully conform to the SFTP(v3) specification.
var msg;
var lang = '';
if (buffer.length >= 12) {
msg = readString(buffer, 8, 'utf8', this, callback);
if (msg === false)
return;
if ((buffer._pos + 4) < buffer.length) {
lang = readString(buffer,
buffer._pos,
'ascii',
this,
callback);
if (lang === false)
return;
}
}
var err = new Error(msg
|| STATUS_CODE_STR[code]
|| 'Unknown status');
err.code = code;
err.lang = lang;
cb(err);
}
} else if (pktType === RESPONSE.HANDLE) {
/*
string handle
*/
handle = readString(buffer, 4, this, callback);
if (handle === false)
return;
cb(undefined, handle);
} else if (pktType === RESPONSE.DATA) {
/*
string data
*/
if (req.buffer) {
// we have already pre-allocated space to store the data
var dataLen = readInt(buffer, 4, this, callback);
if (dataLen === false)
return;
var reqBufLen = req.buffer.length;
if (dataLen > reqBufLen) {
// truncate response data to fit expected size
writeUInt32BE(buffer, reqBufLen, 4);
}
data = readString(buffer, 4, req.buffer, this, callback);
if (data === false)
return;
cb(undefined, data, dataLen);
} else {
data = readString(buffer, 4, this, callback);
if (data === false)
return;
cb(undefined, data);
}
} else if (pktType === RESPONSE.NAME) {
/*
uint32 count
repeats count times:
string filename
string longname
ATTRS attrs
*/
var namesLen = readInt(buffer, 4, this, callback);
if (namesLen === false)
return;
var names = [],
longname;
buffer._pos = 8;
for (var i = 0; i < namesLen; ++i) {
// we are going to assume UTF-8 for filenames despite the SFTPv3
// spec not specifying an encoding because the specs for newer
// versions of the protocol all explicitly specify UTF-8 for
// filenames
filename = readString(buffer,
buffer._pos,
'utf8',
this,
callback);
if (filename === false)
return;
// `longname` only exists in SFTPv3 and since it typically will
// contain the filename, we assume it is also UTF-8
longname = readString(buffer,
buffer._pos,
'utf8',
this,
callback);
if (longname === false)
return;
attrs = readAttrs(buffer, buffer._pos, this, callback);
if (attrs === false)
return;
names.push({
filename: filename,
longname: longname,
attrs: attrs
});
}
cb(undefined, names);
} else if (pktType === RESPONSE.ATTRS) {
/*
ATTRS attrs
*/
attrs = readAttrs(buffer, 4, this, callback);
if (attrs === false)
return;
cb(undefined, attrs);
} else if (pktType === RESPONSE.EXTENDED) {
if (req.extended) {
switch (req.extended) {
case '[email protected]':
case '[email protected]':
/*
uint64 f_bsize // file system block size
uint64 f_frsize // fundamental fs block size
uint64 f_blocks // number of blocks (unit f_frsize)
uint64 f_bfree // free blocks in file system
uint64 f_bavail // free blocks for non-root
uint64 f_files // total file inodes
uint64 f_ffree // free file inodes
uint64 f_favail // free file inodes for to non-root
uint64 f_fsid // file system id
uint64 f_flag // bit mask of f_flag values
uint64 f_namemax // maximum filename length
*/
var stats = {
f_bsize: undefined,
f_frsize: undefined,
f_blocks: undefined,
f_bfree: undefined,
f_bavail: undefined,
f_files: undefined,
f_ffree: undefined,
f_favail: undefined,
f_sid: undefined,
f_flag: undefined,
f_namemax: undefined
};
stats.f_bsize = readUInt64BE(buffer, 4, this, callback);
if (stats.f_bsize === false)
return;
stats.f_frsize = readUInt64BE(buffer, 12, this, callback);
if (stats.f_frsize === false)
return;
stats.f_blocks = readUInt64BE(buffer, 20, this, callback);
if (stats.f_blocks === false)
return;
stats.f_bfree = readUInt64BE(buffer, 28, this, callback);
if (stats.f_bfree === false)
return;
stats.f_bavail = readUInt64BE(buffer, 36, this, callback);
if (stats.f_bavail === false)
return;
stats.f_files = readUInt64BE(buffer, 44, this, callback);
if (stats.f_files === false)
return;
stats.f_ffree = readUInt64BE(buffer, 52, this, callback);
if (stats.f_ffree === false)
return;
stats.f_favail = readUInt64BE(buffer, 60, this, callback);
if (stats.f_favail === false)
return;
stats.f_sid = readUInt64BE(buffer, 68, this, callback);
if (stats.f_sid === false)
return;
stats.f_flag = readUInt64BE(buffer, 76, this, callback);
if (stats.f_flag === false)
return;
stats.f_namemax = readUInt64BE(buffer, 84, this, callback);
if (stats.f_namemax === false)
return;
cb(undefined, stats);
break;
}
}
// XXX: at least provide the raw buffer data to the callback in
// case of unexpected extended response?
cb();
}
}
if (req)
delete requests[id];
} else {
// server
var evName = REQUEST[pktType];
var offset;
var path;
debug('DEBUG[SFTP]: Parser: Request: ' + evName);
if (listenerCount(this, evName)) {
if (pktType === REQUEST.OPEN) {
/*
string filename
uint32 pflags
ATTRS attrs
*/
filename = readString(buffer, 4, 'utf8', this, callback);
if (filename === false)
return;
var pflags = readInt(buffer, buffer._pos, this, callback);
if (pflags === false)
return;
attrs = readAttrs(buffer, buffer._pos + 4, this, callback);
if (attrs === false)
return;
this.emit(evName, id, filename, pflags, attrs);
} else if (pktType === REQUEST.CLOSE
|| pktType === REQUEST.FSTAT
|| pktType === REQUEST.READDIR) {
/*
string handle
*/
handle = readString(buffer, 4, this, callback);
if (handle === false)
return;
this.emit(evName, id, handle);
} else if (pktType === REQUEST.READ) {
/*
string handle
uint64 offset
uint32 len
*/
handle = readString(buffer, 4, this, callback);
if (handle === false)
return;
offset = readUInt64BE(buffer, buffer._pos, this, callback);
if (offset === false)
return;
var len = readInt(buffer, buffer._pos, this, callback);
if (len === false)
return;
this.emit(evName, id, handle, offset, len);
} else if (pktType === REQUEST.WRITE) {
/*
string handle
uint64 offset
string data
*/
handle = readString(buffer, 4, this, callback);
if (handle === false)
return;
offset = readUInt64BE(buffer, buffer._pos, this, callback);
if (offset === false)
return;
data = readString(buffer, buffer._pos, this, callback);
if (data === false)
return;
this.emit(evName, id, handle, offset, data);
} else if (pktType === REQUEST.LSTAT
|| pktType === REQUEST.STAT
|| pktType === REQUEST.OPENDIR
|| pktType === REQUEST.REMOVE
|| pktType === REQUEST.RMDIR
|| pktType === REQUEST.REALPATH
|| pktType === REQUEST.READLINK) {
/*
string path
*/
path = readString(buffer, 4, 'utf8', this, callback);
if (path === false)
return;
this.emit(evName, id, path);
} else if (pktType === REQUEST.SETSTAT
|| pktType === REQUEST.MKDIR) {
/*
string path
ATTRS attrs
*/
path = readString(buffer, 4, 'utf8', this, callback);
if (path === false)
return;
attrs = readAttrs(buffer, buffer._pos, this, callback);
if (attrs === false)
return;
this.emit(evName, id, path, attrs);
} else if (pktType === REQUEST.FSETSTAT) {
/*
string handle
ATTRS attrs
*/
handle = readString(buffer, 4, this, callback);
if (handle === false)
return;
attrs = readAttrs(buffer, buffer._pos, this, callback);
if (attrs === false)
return;
this.emit(evName, id, handle, attrs);
} else if (pktType === REQUEST.RENAME
|| pktType === REQUEST.SYMLINK) {
/*
RENAME:
string oldpath
string newpath
SYMLINK:
string linkpath
string targetpath
*/
var str1;
var str2;
str1 = readString(buffer, 4, 'utf8', this, callback);
if (str1 === false)
return;
str2 = readString(buffer, buffer._pos, 'utf8', this, callback);
if (str2 === false)
return;
if (pktType === REQUEST.SYMLINK && this._isOpenSSH) {
// OpenSSH has linkpath and targetpath positions switched
this.emit(evName, id, str2, str1);
} else
this.emit(evName, id, str1, str2);
}
} else {
// automatically reject request if no handler for request type
this.status(id, STATUS_CODE.OP_UNSUPPORTED);
}
}
}
// prepare for next packet
status = 'packet_header';
buffer = pktBuf = undefined;
} else if (status === 'bad_pkt') {
if (server && buffer[4] !== REQUEST.INIT) {
var errCode = (buffer[4] === REQUEST.EXTENDED
? STATUS_CODE.OP_UNSUPPORTED
: STATUS_CODE.FAILURE);
// no request id for init/version packets, so we have no way to send a
// status response, so we just close up shop ...
if (buffer[4] === REQUEST.INIT || buffer[4] === RESPONSE.VERSION)
return this._cleanup(callback);
id = readInt(buffer, 5, this, callback);
if (id === false)
return;
this.status(id, errCode);
}
// by this point we have already read the type byte and the id bytes, so
// we subtract those from the number of bytes to skip
pktLeft = readUInt32BE(buffer, 0) - 5;
status = 'discard';
}
if (chunkPos >= chunkLen)
break;
}
state.status = status;
state.pktType = pktType;
state.pktBuf = pktBuf;
state.pktLeft = pktLeft;
state.version = version;
callback();
};
// client
SFTPStream.prototype.createReadStream = function(path, options) {
if (this.server)
throw new Error('Client-only method called in server mode');
return new ReadStream(this, path, options);
};
SFTPStream.prototype.createWriteStream = function(path, options) {
if (this.server)
throw new Error('Client-only method called in server mode');
return new WriteStream(this, path, options);
};
SFTPStream.prototype.open = function(path, flags_, attrs, cb) {
if (this.server)
throw new Error('Client-only method called in server mode');
var state = this._state;
if (typeof attrs === 'function') {
cb = attrs;
attrs = undefined;
}
var flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_));
if (flags === null)
throw new Error('Unknown flags string: ' + flags_);
var attrFlags = 0;
var attrBytes = 0;
if (typeof attrs === 'string' || typeof attrs === 'number') {
attrs = { mode: attrs };
}
if (typeof attrs === 'object' && attrs !== null) {
attrs = attrsToBytes(attrs);
attrFlags = attrs.flags;
attrBytes = attrs.nbytes;
attrs = attrs.bytes;
}
/*
uint32 id
string filename
uint32 pflags
ATTRS attrs
*/
var pathlen = Buffer.byteLength(path);
var p = 9;
var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathlen + 4 + 4 + attrBytes);
writeUInt32BE(buf, buf.length - 4, 0);
buf[4] = REQUEST.OPEN;
var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID;
writeUInt32BE(buf, reqid, 5);
writeUInt32BE(buf, pathlen, p);
buf.write(path, p += 4, pathlen, 'utf8');
writeUInt32BE(buf, flags, p += pathlen);
writeUInt32BE(buf, attrFlags, p += 4);
if (attrs && attrFlags) {
p += 4;
for (var i = 0, len = attrs.length; i < len; ++i)
for (var j = 0, len2 = attrs[i].length; j < len2; ++j)
buf[p++] = attrs[i][j];
}
state.requests[reqid] = { cb: cb };
this.debug('DEBUG[SFTP]: Outgoing: Writing OPEN');
return this.push(buf);
};
SFTPStream.prototype.close = function(handle, cb) {
if (this.server)
throw new Error('Client-only method called in server mode');
else if (!Buffer.isBuffer(handle))
throw new Error('handle is not a Buffer');
var state = this._state;
/*
uint32 id
string handle
*/
var handlelen = handle.length;
var p = 9;
var buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen);
writeUInt32BE(buf, buf.length - 4, 0);
buf[4] = REQUEST.CLOSE;
var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID;
writeUInt32BE(buf, reqid, 5);
writeUInt32BE(buf, handlelen, p);
handle.copy(buf, p += 4);
state.requests[reqid] = { cb: cb };
this.debug('DEBUG[SFTP]: Outgoing: Writing CLOSE');
return this.push(buf);
};
SFTPStream.prototype.readData = function(handle, buf, off, len, position, cb) {
if (this.server)
throw new Error('Client-only method called in server mode');
else if (!Buffer.isBuffer(handle))
throw new Error('handle is not a Buffer');
else if (!Buffer.isBuffer(buf))
throw new Error('buffer is not a Buffer');
else if (off >= buf.length)
throw new Error('offset is out of bounds');
else if (off + len > buf.length)
throw new Error('length extends beyond buffer');
else if (position === null)
throw new Error('null position currently unsupported');
var state = this._state;
/*
uint32 id
string handle
uint64 offset
uint32 len
*/
var handlelen = handle.length;
var p = 9;
var pos = position;
var out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen + 8 + 4);
writeUInt32BE(out, out.length - 4, 0);
out[4] = REQUEST.READ;
var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID;
writeUInt32BE(out, reqid, 5);
writeUInt32BE(out, handlelen, p);
handle.copy(out, p += 4);
p += handlelen;
for (var i = 7; i >= 0; --i) {
out[p + i] = pos & 0xFF;
pos /= 256;
}
writeUInt32BE(out, len, p += 8);
state.requests[reqid] = {
cb: function(err, data, nb) {
if (err) {
if (cb._wantEOFError || err.code !== STATUS_CODE.EOF)
return cb(err);
} else if (nb > len) {
return cb(new Error('Received more data than requested'));
}
cb(undefined, nb || 0, data, position);
},
buffer: buf.slice(off, off + len)
};
this.debug('DEBUG[SFTP]: Outgoing: Writing READ');
return this.push(out);
};
SFTPStream.prototype.writeData = function(handle, buf, off, len, position, cb) {
if (this.server)
throw new Error('Client-only method called in server mode');
else if (!Buffer.isBuffer(handle))
throw new Error('handle is not a Buffer');
else if (!Buffer.isBuffer(buf))
throw new Error('buffer is not a Buffer');
else if (off > buf.length)
throw new Error('offset is out of bounds');
else if (off + len > buf.length)
throw new Error('length extends beyond buffer');
else if (position === null)
throw new Error('null position currently unsupported');
var self = this;
var state = this._state;
if (!len) {
cb && process.nextTick(function() { cb(undefined, 0); });
return;
}
var overflow = (len > state.maxDataLen
? len - state.maxDataLen
: 0);
var origPosition = position;
if (overflow)
len = state.maxDataLen;
/*
uint32 id
string handle
uint64 offset
string data
*/
var handlelen = handle.length;
var p = 9;
var out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handlelen + 8 + 4 + len);
writeUInt32BE(out, out.length - 4, 0);
out[4] = REQUEST.WRITE;
var reqid = state.writeReqid = (state.writeReqid + 1) % MAX_REQID;
writeUInt32BE(out, reqid, 5);
writeUInt32BE(out, handlelen, p);
handle.copy(out, p += 4);
p += handlelen;
for (var i = 7; i >= 0; --i) {
out[p + i] = position & 0xFF;
position /= 256;
}
writeUInt32BE(out, len, p += 8);
buf.copy(out, p += 4, off, off + len);
state.requests[reqid] = {
cb: function(err) {
if (err)
cb && cb(err);
else if (overflow) {
self.writeData(handle,
buf,
off + len,
overflow,
origPosition + len,
cb);
} else
cb && cb(undefined, off + len);
}
};
this.debug('DEBUG[SFTP]: Outgoing: Writing WRITE');
return this.push(out);
};
function tryCreateBuffer(size) {
try {
return Buffer.allocUnsafe(size);
} catch (ex) {
return ex;
}
}
function fastXfer(src, dst, srcPath, dstPath, opts, cb) {
var concurrency = 64;
var chunkSize = 32768;
//var preserve = false;
var onstep;
var mode;
var fileSize;
if (typeof opts === 'function') {