-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
2052 lines (1876 loc) · 63.1 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
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
/**
* FTPimp
* @author Nicholas Riley
*/
"use strict";
require('colors');
var net = require('net'),//{{{
fs = require('fs'),
path = require('path'),
/**
* @mixin
* @see {@link https://nodejs.org/api/events.html|Node.js API: EventEmitter}
*/
EventEmitter = require('events').EventEmitter,
dbg,
StatObject,
Queue,
handle,
ftp,
cmd,
/** @constructor */
CMD = require('./lib/command'),
/**
* The main FTP API object
* @constructor
* @mixes EventEmitter
* @param {null|object} config - The ftp connection settings (optional)
* @param {boolean} connect - Whether or not to start the connection automatically; default is true;
* @todo The major functions have been added and this current version
* is more stable and geared for asynchronous NodeJS. The following commands need to be added:
* @todo Add FTP.stou
* @todo Add FTP.rein
* @todo Add FTP.site
* @todo Add FTP.mode
* @todo Add FTP.acct
* @todo Add FTP.appe
* @todo Add FTP.help
* @todo Add ability to opt into an active port connection for data transfers
*
* FTP extends the NodeJS EventEmitter - see
*/
FTP = function (cfg, connect) {
ftp = this;
connect = connect ? true : false;
if (cfg) {
Object.keys(cfg).forEach(function (key) {
ftp.config[key] = cfg[key];
});
if (undefined !== cfg.ascii) {
ftp.ascii = ftp.ascii.concat(cfg.ascii);
}
if (ftp.config.debug) {
debug.enable();
} else {
debug.disable();
}
}
//set new handler
cmd = ftp.cmd = CMD.create(ftp);
ftp.handle = ftp.Handle.create();
if (connect) {
ftp.connect();
}
},
/**
* A debugger for developing and issue tracking
* @namespace
* @memberof FTP
*/
debug = {
/** Disable debugging */
disable: function () {
dbg = debug.disabled;
},
/** Holds the disabled debugger */
disabled: function () {
return undefined;
},
/** Enable debugging */
enable: function () {
dbg = debug.enabled;
},
/** Holds the enabled debugger */
enabled: function () {
console.log.apply(console, arguments);
}
};//}}}
/**
* Initializes the main FTP sequence
* ftp will emit a ready event once
* the server connection has been established
* @param {null|object} config - The ftp connection settings (optional)
* @param {boolean} connect - Whether or not to start the connection automatically; default is true;
* @returns {object} FTP - return new FTP instance object
*/
FTP.create = function (cfg, connect) {
return new FTP(cfg, connect);
};
/**
* The command module
* @type {object}
* @extends module:command
*/
FTP.CMD = CMD;
FTP.prototype = new EventEmitter();
//expose debugger everywhere
FTP.debug = debug;
FTP.prototype.debug = debug;
/** @constructor */
FTP.prototype.Handle = function () {
return undefined;
};
//TODO - document totalPipes && openPipes
FTP.prototype.totalPipes = 0;
FTP.prototype.openPipes = 0;
/**
* Holds the current file transfer type [ascii, binary, ecbdic, local]
* @type {string}
*/
FTP.prototype.currentType = 'ascii';
/**
* List of files to get and put in ASCII
* @type {array}
*/
FTP.prototype.ascii = {
am: 1,
asp: 1,
bat: 1,
c: 1,
cfm: 1,
cgi: 1,
conf: 1,
cpp: 1,
css: 1,
dhtml: 1,
diz: 1,
h: 1,
hpp: 1,
htm: 1,
html: 1,
in: 1,
inc: 1,
java: 1,
js: 1,
jsp: 1,
lua: 1,
m4: 1,
mak: 1,
md5: 1,
nfo: 1,
nsi: 1,
pas: 1,
patch: 1,
php: 1,
phtml: 1,
pl: 1,
po: 1,
py: 1,
qmail: 1,
sh: 1,
shtml: 1,
sql: 1,
svg: 1,
tcl: 1,
tpl: 1,
txt: 1,
vbs: 1,
xhtml: 1,
xml: 1,
xrc: 1
};
/**
* Set once the ftp connection is established
* @type {boolean}
*/
FTP.prototype.isReady = false;
/**
* Refernce to the socket created for data transfers
* @alias FTP#pipe
* @type {object}
*/
FTP.prototype.pipe = null;
/**
* Set by the ftp.abort method to tell the pipe to close any open data connection
* @type {object}
* @alias FTP#pipeAborted
*/
FTP.prototype.pipeAborted = false;
/**
* Set by the ftp.openDataPort method to tell the process that the pipe has been closed
* @type {object}
* @alias FTP#pipeClosed
*/
FTP.prototype.pipeClosed = false;
/**
* Set by the ftp.put method while the pipe is connecting and while connected
* @type {object}
* @alias FTP#pipeActive
*/
FTP.prototype.pipeActive = false;
/**
* Refernce to the socket created for data transfers
* @type {object}
* @alias FTP#socket
*/
FTP.prototype.socket = null;
/**
* The FTP log in information.
* @type {string}
* @alias FTP#config
*/
FTP.prototype.config = {
host: 'localhost',
port: 21,
user: 'root',
pass: '',
debug: false
};
/**
* Current working directory.
* @type {string}
* @alias FTP#cwd
*/
FTP.prototype.cwd = '';
/**
* The user defined directory set by the FTP admin.
* @type {string}
* @alias FTP#baseDir
*/
FTP.prototype.baseDir = '';
/**
* Creates and returns a new FTP connection handler
* @returns {object} The new Handle instance
*/
FTP.prototype.Handle.create = function () {
return new FTP.prototype.Handle();
};
handle = FTP.prototype.Handle.prototype;
/**
* Ran at beginning to start a connection, can be overriden
* @example
* //Overriding the ftpimp.init instance method
* var FTP = require('ftpimp'),
* //get connection settings
* config = {
* host: 'localhost',
* port: 21,
* user: 'root',
* pass: ''
* },
* ftp,
* //override init
* MyFTP = function(){
* this.init();
* };
* //override the prototype
* MyFTP.prototype = FTP.prototype;
* //override the init method
* MyFTP.prototype.init = function () {
* dbg('Initializing!');
* ftp.handle = ftp.Handle.create();
* ftp.connect();
* };
* //start new MyFTP instance
* ftp = new MyFTP(config);
*/
FTP.prototype.init = function () {//{{{
//create a new socket and login
ftp.connect();
};//}}}
var ExeQueue = function (command, callback, runLevel, holdQueue) {
var that = this,
n,
method = command.split(' ', 1)[0],
bind = function (name) {
that[name.slice(1)] = function () {
if (name === '_responseHandler') {
}
dbg('calling : ' + name + ' > ' + command, arguments);
that[name].apply(that, arguments);
};
};
that.command = command;
that.method = method;
that.pipeData = [];
that.pipeDataSize = 0;
that.holdQueue = holdQueue;
that.callback = callback;
that.runLevel = runLevel;
that.ended = false;
that.ping = null;
handle.data.waiting = true;
for (n in ExeQueue.prototype) {
if (ExeQueue.prototype.hasOwnProperty(n) && n.charAt(0) === '_' && ExeQueue.prototype.hasOwnProperty(n)) {
//remove underscore and provide hook
bind(n);
}
}
ftp.once('response', that.responseHandler);
that.started = Date.now();
ftp.socket.write(command + '\r\n', function () {
dbg(('Run> command sent: ' + command).yellow);
});
};
ExeQueue.create = function (command, callback, runLevel, holdQueue) {
return new ExeQueue(command, callback, runLevel, holdQueue);
};
//end the queue
ExeQueue.prototype._end = function () {
var that = this;
that.checkProc();
};
//end the queue
ExeQueue.prototype._endStopwatch = function () {
var that = this;
that.ended = Date.now();
that.ping = that.ended - that.started;
};
ExeQueue.prototype.queueHolding = false;
ExeQueue.prototype._checkProc = function () {
var that = this;
dbg('check process for end: ', that);
if (that.holdQueue) {
dbg(('ExeQueue> Ending process, holding queue: ' + that.command).yellow);
} else {
dbg(('ExeQueue> Ending process: ' + that.command).yellow);
ftp.emit('endproc');
}
};
ExeQueue.prototype._closeTransfer = function () {
dbg('ExeQueue> closing transfer and ending Proc'.magenta);
var exeQueue = this;
exeQueue.closePipe();
//exeQueue.checkProc();
};
ExeQueue.prototype._closePipe = function () {
dbg('ExeQueue> closing transfer pipe'.magenta);
let exeQueue = this;
let data = exeQueue.pipeData;
let bufferSize = exeQueue.pipeDataSize;
try {
ftp.pipe.removeListener('data', exeQueue.receiveData);
ftp.pipe.removeListener('end', exeQueue.closePipe);
//check for buffers
if (data.length && Array.isArray(data)) {
data = Buffer.concat(data, bufferSize);
}
} catch (dataNotBoundError) {
dbg('data not bound: ', dataNotBoundError);
}
dbg('ExeQueue> total size(' + (data ? data.length : 0) + ')');
exeQueue.callback(null, data);
exeQueue.checkProc();
};
ExeQueue.prototype._responseHandler = function (code, data) {
dbg(('Response handler: ' + code).cyan, data);
var exeQueue = this;
exeQueue.endStopwatch();
//dbg('pipe is ' + (ftp.pipeClosed ? 'closed' : 'open'));
if (code >= 500 && code < 600) {
dbg('handling error response code...');
dbg(exeQueue);
//if we have an open pipe, wait for it to end
//if (ftp.pipeClosed) {
//end immediately
try {
dbg('killing pipe');
ftp.pipe.removeListener('data', exeQueue.receiveData);
ftp.pipe.removeListener('end', exeQueue.closePipe);
ftp.pipe.destroy();
dbg('---pipe down---'.red);
} catch (dataNotBoundError) {
dbg('data not bound: ', dataNotBoundError);
}
exeQueue.callback(new Error(data), null);
exeQueue.checkProc();
} else if (code === 150 || code === 125) {
if (exeQueue.method === 'STOR') {
ftp.once('dataTransferComplete', exeQueue.closeTransfer);
} else {
dbg('listening for pipe data'.red);
if (ftp.pipeClosed) {
dbg('pipe already closed'.yellow);
ftp.pipeClosed = false;
exeQueue.closePipe();
return;
}
ftp.pipe.on('end', exeQueue.closePipe);
ftp.pipe.on('data', exeQueue.receiveData);
}
} else {
exeQueue.callback(null, data);
if (code !== 227) {
exeQueue.checkProc();
}
}
};
ExeQueue.prototype._receiveData = function (data) {
let c = this;
c.pipeDataSize += data.length;
c.pipeData.push(data);
};
/**
* Run a raw ftp command and issue callback on success/error.
* Same as {@link FTP#run} except this command will be
* will be prioritized to be the next to run in the queue.
* - calls made with this provide a sequential queue
*
* @param {string} command - The command that will be issued ie: <b>"CWD foo"</b>
* @param {function} callback - The callback function to be issued on success/error
* @param {boolean} [holdQueue=false] - Prevents the queue from firing an endproc event, user must end manually
*/
FTP.prototype.runNext = function (command, callback, holdQueue) {
ftp.run(command, callback, Queue.RunNext, holdQueue);
};
/**
* Run a raw ftp command and issue callback on success/error.
* Same as {@link FTP#run} except this command will be ran immediately (in parallel)
* and will overrun any current queue action in place.
*
* @param {string} command - The command that will be issued ie: <b>"CWD foo"</b>
* @param {function} callback - The callback function to be issued on success/error
* @param {boolean} [holdQueue=false] - Prevents the queue from firing an endproc event, user must end manually
*/
FTP.prototype.runNow = function (command, callback, holdQueue) {
ftp.run(command, callback, Queue.RunNow, holdQueue);
};
/**
* Run a raw ftp command and issue callback on success/error.
* <br>
* Functions created with this provide a sequential queue
* that is asynchronous, so items will be processed
* in the order they are received, but this will happen
* immediately. Meaning, if you make a dozen sequential calls
* of <b>"ftp.run('MDTM', callback);"</b> they will all be read immediately,
* queued in order, and then processed one after the other. Unless
* you set the optional parameter <b>runLevel</b> to <b>true</b>
*
* @param {string} command - The command that will be issued ie: <b>"CWD foo"</b>
* @param {function} callback - The callback function to be issued on success/error
* @param {number} [runLevel=0] - TL;DR see {@link Queue.RunLevels}
* FTP#run will invoke a queueing process, callbacks
* will be stacked to maintain synchronicity. How they stack will depend on the value
* you set for the runLevel
* @param {boolean} [holdQueue=false] - Prevents the queue from firing an endproc event, user must end manually
*/
FTP.prototype.run = function (command, callback, runLevel, holdQueue) {//{{{
runLevel = runLevel === undefined ? false : runLevel;
holdQueue = holdQueue === undefined ? false : holdQueue;
var callbackConstruct = function () {
dbg('Run> running callbackConstruct'.yellow + ' ' + command);
//if (command === 'QUIT') {...}
dbg(command, runLevel, holdQueue);
ExeQueue.create(command, callback, runLevel, holdQueue);
};
if (undefined === command) { //TODO || cmd.allowed.indexOf(command.toLowerCase) {
throw new Error('ftp.run > parameter 1 expected command{string}');
} else if (undefined === callback || typeof callback !== 'function') {
throw new Error('ftp.run > parameter 2 expected a callback function');
}
dbg('ftp.Run: ' + [, holdQueue, command].join(' ').cyan);
ftp.queue.register(callbackConstruct, runLevel);
};//}}}
/**
* Establishes a queue to provide synchronicity to ftp
* processes that would otherwise fail from concurrency.
* This function is done automatically when using
* the {@link FTP#run} method to queue commands.
* @fires FTP#queueEmpty
* @member {object} FTP#queue
* @property {array} queue._queue - Stores registered procedures
* and holds them until called by the queue.run method
* @property {boolean} queue.processing - Returns true if there
* are items running in the queue
* @property {function} queue.register - Registers a new callback
* function to be triggered after the queued command completes
* @property {function} queue.run - If there is something in the
* queue and queue.processing is false, than the first item
* stored in queue._queue will be removed from the queue
* and processed.
*/
FTP.prototype.queue = {//{{{
_queue: [],
processing: false,
reset: function () {
//...resets the queue
ftp.queue._queue = [];
},
register: function (callback, runLevel) {
dbg('Queue> Registering callback...');
dbg(('Queue> processing: ' + ftp.queue.processing + '; size: ' + ftp.queue._queue.length).cyan);
runLevel = runLevel === undefined ? false : runLevel;
if (runLevel) {
//run next
if (runLevel === Queue.RunNext) {
ftp.queue._queue.unshift(callback);
} else {
//run now
callback();
return;
}
} else {
ftp.queue._queue.push(callback);
}
if (!ftp.queue.processing) {
ftp.queue.run();
//ftp.emit('endproc');
}
},
run: function () {
dbg('Queue> Loading queue'.yellow);
if (ftp.queue._queue.length > 0) {
ftp.queue.processing = true;
dbg('Queue> Loaded...running');
ftp.queue.currentProc = ftp.queue._queue.shift();
if (!ftp.error) {
ftp.queue.currentProc.call(ftp.queue.currentProc);
}
} else {
/**
* Fired when the primary queue is empty
* @event FTP#queueEmpty
*/
ftp.emit('queueEmpty');
ftp.queue.processing = false;
dbg('--queue empty--'.yellow);
}
}
};
FTP.prototype.on('endproc', function () {
dbg('Event> endproc'.magenta);
});
/** @todo - this needs to be defined */
FTP.prototype.on('endproc', FTP.prototype.queue.run);//}}}
/**
* Provides a factory to create a simple queue procedure. Look
* at the example below to see how we override the callback
* function to perform additional actions before exiting
* the queue and loading the next one.<br>
* Functions created with this provide a synchronized queue
* that is asynchronous in itself, so items will be processed
* in the order they are received, but this will happen
* immediately. Meaning, if you make a dozen sequential calls
* to {@link FTP#filemtime} they will all be read immediately,
* queued in order, and then processed one after the other.
* @constructor
* @memberof FTP
* @see {@link Queue}
* @param {string} command - The command that will be issued ie: <b>"CWD foo"</b>
* @returns {function} queueManager - The simple queue manager
* @TODO - documentation needs to be updated rewrite
*/
var Queue = function (command) {//{{{
var queue = this;
queue.command = command;
var builder = queue.builder();
builder.raw = command;
return builder;
};//}}}
/**
* The queue manager returned when creating a new {@link Queue} object
* @memberof Queue
* @inner
* @param {string} filepath - The location of the remote file to process the set command.
* @param {function} callback - The callback function to be issued.
* @param {boolean} runLevel - execution priority; @see {@link FTP.Queue.RunLevels}. Careful, concurrent connections
* will likely end in a socket error. This is meant for fine grained control over certain
* scenarios wherein the process is part of a running queue and you need to perform an ftp
* action prior to the {@link FTP#endproc} event firing and execing the next queue.
*/
Queue.prototype.builder = function () {
var queue = this,
command = queue.command;
return function (filepath, callback, runLevel, holdQueue) {
var hook = (undefined === queue[command + 'Hook']) ? null : queue[command + 'Hook'],
portHandler = function () {
dbg('Queue.builder: checking hook -> ' + typeof hook);
//hook data into custom instance function
ftp.runNow(command + ' ' + filepath, function (err, data) {
if (typeof hook === 'function') {
data = hook(data);
}
callback(err, data);
if (!holdQueue) {
ftp.emit('endproc');
}
}, true);
};
dbg(['Queue.builder::', command, filepath, '> setting '].join(' ').cyan);
dbg(runLevel, holdQueue);
//TODO add list of commands that don't need to change type, or should be a certain type
//ie ls:LIST
ftp.setType(filepath, function () {
dbg('type set');
ftp.openDataPort(portHandler, Queue.RunNow, true);
}, runLevel, true);
};
};
/**
* Static Queue value passed in the runLevel param of methods to control the priority of those methods.
* <br>
* - default RunLevel {@link FTP.Queue.RunLast}<br>
* - Most methods use the {@link FTP#run} call.<br>
* - Every {@link FTP#run} call issued is stacked in a series queue by default. To change to a waterfall
* or run in parallel. <br><br>
*
* <i>RunLevels are a design of FTPimp to control process flow only.</i><br>
* <strong>When implementing parallel actions, parallel calls should only be issued inside the callback
* of a parent waterfall or series queue. Otherwise, the FTP service itself likely will break
* from the concurrent connection attempts.</strong>
* @class
* @readonly
* @enum {number}
* @see {@link FTP#mkdir}, {@link FTP#rmdir}, {@link FTP#put} for examples
* @see {@link FTP#run} for series, {@link FTP#runNext} for waterfall, {@link FTP#runNow} for parallel
* @example
* //series
* ftp.ping(function () { //runs first
* ftp.ping(function () { //runs third
* });
* });
* ftp.ping(function () { //runs second
* });
*
* //waterfall
* var runNext = FTP.Queue.RunNext;
* ftp.ping(function () { //runs first
* //add runNow to the call
* ftp.ping(function () { //runs second
* }, runNow);
* });
* ftp.ping(function () { //runs third
* });
*
* //parallel
* var runNow = FTP.Queue.RunNow;
* ftp.put('foo', function () { //runs first
* });
* ftp.put('foo', function () { //runs second
* }, runNow);
*/
Queue.RunLevels = {
/** {@link FTP.Queue.RunLast} will push the command to the end of the queue; */
last: 0,
/** {@link FTP.Queue.RunNow} will run the command immediately; will overrun a current processing queue */
now: 1,
/** {@link FTP.Queue.RunNext} will run after current queue completes */
next: 2
};
/**
* @readonly
* @property {number} RunNext - value needed for runLevel parameter to run commands immediately after the current queue;
* @see {@link FTP.Queue.RunLevels.next}
* @see {@link FTP#run}
*/
Queue.RunNext = Queue.RunLevels.next;
/**
* @readonly
* @property {number} RunNow - value needed for runLevel parameter to run commands immediately, overrunning any current queue process;
* @see {@link FTP.Queue.RunLevels.now}
* @see {@link FTP#run}
*/
Queue.RunNow = Queue.RunLevels.now;
/**
* @readonly
* @property {number} RunLast - value needed for runLevel parameter, will add command to the end of the queue; default Queue.RunLevel;
* @see {@link FTP.Queue.RunLevels.last}
* @see {@link FTP#run}
*/
Queue.RunLast = Queue.RunLevels.last;
/**
* Create a new {@link Queue} instance for the command type.
* @param {string} command - The command that will be issued, no parameters, ie: <b>"CWD"</b>
*/
Queue.create = function (command) {//{{{
return new Queue(command);
};//}}}
/**
* Register a data hook function to intercept received data
* on the command (parameter 1)
* @param {string} command - The command that will be issued, no parameters, ie: <b>"CWD"</b>
* @param {function} callback - The callback function to be issued.
*/
Queue.registerHook = function (command, callback) {//{{{
if (undefined !== Queue.prototype[command + 'Hook']) {
throw new Error('Handle.Queue already has hook registered: ' + command + 'Hook');
}
Queue.prototype[command + 'Hook'] = callback;
};//}}}
/**
* Called once the socket has established
* a connection to the host
*/
let failedAttempts = [];
const failedTimeThreshold = 10 * 1000;
const maxFailedAttempts = 3;
handle.connected = function () {//{{{
dbg('socket connected!');
if (!ftp.socket.remoteAddress) {
let now = Date.now();
failedAttempts = failedAttempts.filter((time) => {
return time > (now - failedTimeThreshold);
});
if (failedAttempts.length > maxFailedAttempts) {
throw new Error('Max failed attempts reached trying to reconnect to FTP server');
}
failedAttempts.push(now);
setTimeout(ftp.connect, 1000);
return;
}
process.once('exit', ftp.exit);
process.once('SIGINT', ftp.exit);
ftp.config.pasvAddress = ftp.socket.remoteAddress.split('.').join(',');
ftp.socket.on('data', ftp.handle.data);
//process.once('uncaughtException', handle.uncaughtException);
};//}}}
/**
* Called anytime an uncaughtException error is thrown
*/
handle.uncaughtException = function (err) {//{{{
dbg(('!' + err.toString()).red);
ftp.exit();
};//}}}
/**
* Simple way to parse incoming data, and determine
* if we should run any commands from it. Commands
* are found in the lib/command.js file
*/
handle.data = function (data) {//{{{
dbg('....................');
var strData = data.toString().trim(),
strParts,
commandCodes = [],
commandData = {},
cmdName,
code,
i,
end = function () {
dbg('handle.data.waiting: ' + handle.data.waiting, code);
if (handle.data.waiting) {
dbg('handle.data.waiting:: ' + code + ' ' + strData);
if (!handle.data.start) {
handle.data.waiting = false;
/*if (code === 150) {
dbg('holding for data transfer'.yellow);
} else {*/
ftp.emit('response', code, strData);
//}
} else {
handle.data.waiting = true;
handle.data.start = false;
}
} else if (code === 553) {
}
},
run = function () {
if (undefined !== cmd.keys[code]) {
if (code === 227) {
handle.data.waiting = true;
ftp.once('commandComplete', end);
}
cmdName = cmd.keys[code];
dbg('>executing command: ' + cmdName);
cmd[cmdName](strData);
//only open once per ftp instance
}
//we will handle data transfer codes with the openDataPort
if (code !== 227 && code !== 226) {
end();
}
};
dbg(('\n>>>\n' + strData + '\n>>>\n').grey);
strData = strData.split(/[\r|\n]/).filter(Boolean);
strParts = strData.length;
for (i = 0; i < strParts; i++) {
code = strData[i].substr(0, 3);
//make sure its a number and not yet stored
if (code.search(/^[0-9]{3}/) > -1) {
if (commandCodes.indexOf(code) < 0) {
commandCodes.push(code);
commandData[code] = '';
}
commandData[code] += strData[i].substr(3);
}
}
dbg(commandCodes.join(', ').grey);
for (i = 0; i < commandCodes.length; i++) {
code = Number(commandCodes[i]);
strData = commandData[code].trim();
dbg('------------------');
dbg('CODE -> ' + code);
dbg('DATA -> ' + strData);
dbg('------------------');
run();
}
};//}}}
/**
* Waiting for response from server
* @property FTP#Handle#data.waiting
*/
handle.data.waiting = true;
handle.data.start = true;
/**
* Logout from the ftp server
* @param {number} sig - the signal code, if not 0, then socket will
* be destroyed to force closing
*/
FTP.prototype.exit = function (sig) {//{{{
if (undefined !== sig && sig === 0) {
ftp.socket.end();
} else {
//ftp.pipe.close();
ftp.socket.destroy();
if (ftp.pipeActive) {
ftp.pipeAborted = false;
ftp.pipeActive = false;
}
}
};//}}}
/**
* Creates a new socket connection for sending commands
* to the ftp server and runs an optional callback when logged in
* @param {function} callback - The callback function to be issued. (optional)
*/
FTP.prototype.connect = function (callback) {//{{{
/**
* Holds the connected socket object
* @member FTP#socket
*/
ftp.socket = net.createConnection(ftp.config.port, ftp.config.host);
ftp.socket.on('connect', handle.connected);
if (typeof callback === 'function') {
ftp.once('ready', callback);
}
dbg('connected: ' + ftp.config.host + ':' + ftp.config.port);
ftp.socket.on('close', function () {
dbg('**********socket CLOSED**************');
});
ftp.socket.on('end', function () {
dbg('**********socket END**************');
});
};//}}}
/**
* Opens a new data port to the remote server - pasv connection
* which allows for file transfers
* @param {function} callback - The callback function to be issued
* @param {boolean} runLevel - execution priority; @see {@link FTP.Queue.RunLevels}.
* @TODO Add in useActive parameter to choose how to handle data transfers
*/
FTP.prototype.openDataPort = function (callback, runLevel, holdQueue) {//{{{
holdQueue = !!holdQueue;
dbg('holdQ: ', holdQueue);
var dataHandler = function (err, data) {
if (err) {
dbg('error opening data port with PASV');
dbg(err);
return;
}
dbg('opening data port...'.cyan);
dbg(ftp.socket.remoteAddress);
dbg(ftp.config.pasvPort);
//ftp.on('dataPortReady', callback);
ftp.pipe = net.createConnection(
ftp.config.pasvPort,
ftp.socket.remoteAddress
);
//trigger callback once the server has confirmed the port is open
ftp.pipe.once('connect', function () {
dbg('passive connection established ... running callback'.green);
//dbg(callback.toString());
callback.call(ftp);
});
ftp.pipe.once('end', function () {
dbg('----> pipe end ----');
ftp.pipeClosed = true;
ftp.openPipes -= 1;
ftp.emit('dataPortClosed');
});
/*if (ftp.config.debug) {
ftp.pipe.on('data', function (data) {
dbg(data.toString().green);
});
}*/
/*
ftp.pipe.once('error', function (err) {
dbg(('pipe error: ' + err.errno).red);
dbg(ftp.openPipes);
});*/
};
ftp.pasv(dataHandler, runLevel, holdQueue);
};//}}}
/**
* Asynchronously queues files for transfer, and transfers them in order to the server.
* @function
* @param {string|array} paths - The path to read and send the file,
* if you are sending to the same (relative) location you are reading from then
* you can supply a string as a shortcut. Otherwise, use an array [from, to]
* @param {function} callback - The callback function to be issued once the file
* has been successfully written to the remote
* @TODO - rewrite needed, can be simplified at this point
*/
FTP.prototype.put = (function () {//{{{
var running = false,
//TODO - test this further
runQueue;
runQueue = function (curQueue) {
dbg('FTP::put> running the pipe queue'.green, running);
var callback,
data,
dataTransfer,