Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

connection.js 29KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. var fs = require('fs'),
  2. tls = require('tls'),
  3. zlib = require('zlib'),
  4. Socket = require('net').Socket,
  5. EventEmitter = require('events').EventEmitter,
  6. inherits = require('util').inherits,
  7. inspect = require('util').inspect;
  8. var Parser = require('./parser');
  9. var XRegExp = require('xregexp').XRegExp;
  10. var REX_TIMEVAL = XRegExp.cache('^(?<year>\\d{4})(?<month>\\d{2})(?<date>\\d{2})(?<hour>\\d{2})(?<minute>\\d{2})(?<second>\\d+)(?:.\\d+)?$'),
  11. RE_PASV = /([\d]+),([\d]+),([\d]+),([\d]+),([-\d]+),([-\d]+)/,
  12. RE_EOL = /\r?\n/g,
  13. RE_WD = /"(.+)"(?: |$)/,
  14. RE_SYST = /^([^ ]+)(?: |$)/;
  15. var /*TYPE = {
  16. SYNTAX: 0,
  17. INFO: 1,
  18. SOCKETS: 2,
  19. AUTH: 3,
  20. UNSPEC: 4,
  21. FILESYS: 5
  22. },*/
  23. RETVAL = {
  24. PRELIM: 1,
  25. OK: 2,
  26. WAITING: 3,
  27. ERR_TEMP: 4,
  28. ERR_PERM: 5
  29. },
  30. /*ERRORS = {
  31. 421: 'Service not available, closing control connection',
  32. 425: 'Can\'t open data connection',
  33. 426: 'Connection closed; transfer aborted',
  34. 450: 'Requested file action not taken / File unavailable (e.g., file busy)',
  35. 451: 'Requested action aborted: local error in processing',
  36. 452: 'Requested action not taken / Insufficient storage space in system',
  37. 500: 'Syntax error / Command unrecognized',
  38. 501: 'Syntax error in parameters or arguments',
  39. 502: 'Command not implemented',
  40. 503: 'Bad sequence of commands',
  41. 504: 'Command not implemented for that parameter',
  42. 530: 'Not logged in',
  43. 532: 'Need account for storing files',
  44. 550: 'Requested action not taken / File unavailable (e.g., file not found, no access)',
  45. 551: 'Requested action aborted: page type unknown',
  46. 552: 'Requested file action aborted / Exceeded storage allocation (for current directory or dataset)',
  47. 553: 'Requested action not taken / File name not allowed'
  48. },*/
  49. bytesNOOP = new Buffer('NOOP\r\n');
  50. var FTP = module.exports = function() {
  51. if (!(this instanceof FTP))
  52. return new FTP();
  53. this._socket = undefined;
  54. this._pasvSock = undefined;
  55. this._feat = undefined;
  56. this._curReq = undefined;
  57. this._queue = [];
  58. this._secstate = undefined;
  59. this._debug = undefined;
  60. this._keepalive = undefined;
  61. this._ending = false;
  62. this._parser = undefined;
  63. this.options = {
  64. host: undefined,
  65. port: undefined,
  66. user: undefined,
  67. password: undefined,
  68. secure: false,
  69. secureOptions: undefined,
  70. connTimeout: undefined,
  71. pasvTimeout: undefined,
  72. aliveTimeout: undefined
  73. };
  74. this.connected = false;
  75. };
  76. inherits(FTP, EventEmitter);
  77. FTP.prototype.connect = function(options) {
  78. var self = this;
  79. if (typeof options !== 'object')
  80. options = {};
  81. this.connected = false;
  82. this.options.host = options.host || 'localhost';
  83. this.options.port = options.port || 21;
  84. this.options.user = options.user || 'anonymous';
  85. this.options.password = options.password || 'anonymous@';
  86. this.options.secure = options.secure || false;
  87. this.options.secureOptions = options.secureOptions;
  88. this.options.connTimeout = options.connTimeout || 10000;
  89. this.options.pasvTimeout = options.pasvTimeout || 10000;
  90. this.options.aliveTimeout = options.keepalive || 10000;
  91. if (typeof options.debug === 'function')
  92. this._debug = options.debug;
  93. var secureOptions,
  94. debug = this._debug,
  95. socket = new Socket();
  96. socket.setTimeout(0);
  97. socket.setKeepAlive(true);
  98. this._parser = new Parser({ debug: debug });
  99. this._parser.on('response', function(code, text) {
  100. var retval = code / 100 >> 0;
  101. if (retval === RETVAL.ERR_TEMP || retval === RETVAL.ERR_PERM) {
  102. if (self._curReq)
  103. self._curReq.cb(makeError(code, text), undefined, code);
  104. else
  105. self.emit('error', makeError(code, text));
  106. } else if (self._curReq)
  107. self._curReq.cb(undefined, text, code);
  108. // a hack to signal we're waiting for a PASV data connection to complete
  109. // first before executing any more queued requests ...
  110. //
  111. // also: don't forget our current request if we're expecting another
  112. // terminating response ....
  113. if (self._curReq && retval !== RETVAL.PRELIM) {
  114. self._curReq = undefined;
  115. self._send();
  116. }
  117. noopreq.cb();
  118. });
  119. if (this.options.secure) {
  120. secureOptions = {};
  121. secureOptions.host = this.options.host;
  122. for (var k in this.options.secureOptions)
  123. secureOptions[k] = this.options.secureOptions[k];
  124. secureOptions.socket = socket;
  125. this.options.secureOptions = secureOptions;
  126. }
  127. if (this.options.secure === 'implicit')
  128. this._socket = tls.connect(secureOptions, onconnect);
  129. else {
  130. socket.once('connect', onconnect);
  131. this._socket = socket;
  132. }
  133. var noopreq = {
  134. cmd: 'NOOP',
  135. cb: function() {
  136. clearTimeout(self._keepalive);
  137. self._keepalive = setTimeout(donoop, self.options.aliveTimeout);
  138. }
  139. };
  140. function donoop() {
  141. if (!self._socket || !self._socket.writable)
  142. clearTimeout(self._keepalive);
  143. else if (!self._curReq && self._queue.length === 0) {
  144. self._curReq = noopreq;
  145. debug&&debug('[connection] > NOOP');
  146. self._socket.write(bytesNOOP);
  147. } else
  148. noopreq.cb();
  149. }
  150. function onconnect() {
  151. clearTimeout(timer);
  152. clearTimeout(self._keepalive);
  153. self.connected = true;
  154. self._socket = socket; // re-assign for implicit secure connections
  155. var cmd;
  156. if (self._secstate) {
  157. if (self._secstate === 'upgraded-tls' && self.options.secure === true) {
  158. cmd = 'PBSZ';
  159. self._send('PBSZ 0', reentry, true);
  160. } else {
  161. cmd = 'USER';
  162. self._send('USER ' + self.options.user, reentry, true);
  163. }
  164. } else {
  165. self._curReq = {
  166. cmd: '',
  167. cb: reentry
  168. };
  169. }
  170. function reentry(err, text, code) {
  171. if (err && (!cmd || cmd === 'USER' || cmd === 'PASS' || cmd === 'TYPE')) {
  172. self.emit('error', err);
  173. return self._socket && self._socket.end();
  174. }
  175. if ((cmd === 'AUTH TLS' && code !== 234 && self.options.secure !== true)
  176. || (cmd === 'AUTH SSL' && code !== 334)
  177. || (cmd === 'PBSZ' && code !== 200)
  178. || (cmd === 'PROT' && code !== 200)) {
  179. self.emit('error', makeError(code, 'Unable to secure connection(s)'));
  180. return self._socket && self._socket.end();
  181. }
  182. if (!cmd) {
  183. // sometimes the initial greeting can contain useful information
  184. // about authorized use, other limits, etc.
  185. self.emit('greeting', text);
  186. if (self.options.secure && self.options.secure !== 'implicit') {
  187. cmd = 'AUTH TLS';
  188. self._send(cmd, reentry, true);
  189. } else {
  190. cmd = 'USER';
  191. self._send('USER ' + self.options.user, reentry, true);
  192. }
  193. } else if (cmd === 'USER') {
  194. if (code !== 230) {
  195. // password required
  196. if (!self.options.password) {
  197. self.emit('error', makeError(code, 'Password required'));
  198. return self._socket && self._socket.end();
  199. }
  200. cmd = 'PASS';
  201. self._send('PASS ' + self.options.password, reentry, true);
  202. } else {
  203. // no password required
  204. cmd = 'PASS';
  205. reentry(undefined, text, code);
  206. }
  207. } else if (cmd === 'PASS') {
  208. cmd = 'FEAT';
  209. self._send(cmd, reentry, true);
  210. } else if (cmd === 'FEAT') {
  211. if (!err)
  212. self._feat = Parser.parseFeat(text);
  213. cmd = 'TYPE';
  214. self._send('TYPE I', reentry, true);
  215. } else if (cmd === 'TYPE')
  216. self.emit('ready');
  217. else if (cmd === 'PBSZ') {
  218. cmd = 'PROT';
  219. self._send('PROT P', reentry, true);
  220. } else if (cmd === 'PROT') {
  221. cmd = 'USER';
  222. self._send('USER ' + self.options.user, reentry, true);
  223. } else if (cmd.substr(0, 4) === 'AUTH') {
  224. if (cmd === 'AUTH TLS' && code !== 234) {
  225. cmd = 'AUTH SSL';
  226. return self._send(cmd, reentry, true);
  227. } else if (cmd === 'AUTH TLS')
  228. self._secstate = 'upgraded-tls';
  229. else if (cmd === 'AUTH SSL')
  230. self._secstate = 'upgraded-ssl';
  231. socket.removeAllListeners('data');
  232. socket.removeAllListeners('error');
  233. socket._decoder = null;
  234. self._curReq = null; // prevent queue from being processed during
  235. // TLS/SSL negotiation
  236. secureOptions.socket = self._socket;
  237. secureOptions.session = undefined;
  238. socket = tls.connect(secureOptions, onconnect);
  239. socket.setEncoding('binary');
  240. socket.on('data', ondata);
  241. socket.once('end', onend);
  242. socket.on('error', onerror);
  243. }
  244. }
  245. }
  246. socket.on('data', ondata);
  247. function ondata(chunk) {
  248. debug&&debug('[connection] < ' + inspect(chunk.toString('binary')));
  249. if (self._parser)
  250. self._parser.write(chunk);
  251. }
  252. socket.on('error', onerror);
  253. function onerror(err) {
  254. clearTimeout(timer);
  255. clearTimeout(self._keepalive);
  256. self.emit('error', err);
  257. }
  258. socket.once('end', onend);
  259. function onend() {
  260. ondone();
  261. self.emit('end');
  262. }
  263. socket.once('close', function(had_err) {
  264. ondone();
  265. self.emit('close', had_err);
  266. });
  267. var hasReset = false;
  268. function ondone() {
  269. if (!hasReset) {
  270. hasReset = true;
  271. clearTimeout(timer);
  272. self._reset();
  273. }
  274. }
  275. var timer = setTimeout(function() {
  276. self.emit('error', new Error('Timeout while connecting to server'));
  277. self._socket && self._socket.destroy();
  278. self._reset();
  279. }, this.options.connTimeout);
  280. this._socket.connect(this.options.port, this.options.host);
  281. };
  282. FTP.prototype.end = function() {
  283. if (this._queue.length)
  284. this._ending = true;
  285. else
  286. this._reset();
  287. };
  288. FTP.prototype.destroy = function() {
  289. this._reset();
  290. };
  291. // "Standard" (RFC 959) commands
  292. FTP.prototype.ascii = function(cb) {
  293. return this._send('TYPE A', cb);
  294. };
  295. FTP.prototype.binary = function(cb) {
  296. return this._send('TYPE I', cb);
  297. };
  298. FTP.prototype.abort = function(immediate, cb) {
  299. if (typeof immediate === 'function') {
  300. cb = immediate;
  301. immediate = true;
  302. }
  303. if (immediate)
  304. this._send('ABOR', cb, true);
  305. else
  306. this._send('ABOR', cb);
  307. };
  308. FTP.prototype.cwd = function(path, cb, promote) {
  309. this._send('CWD ' + path, function(err, text, code) {
  310. if (err)
  311. return cb(err);
  312. var m = RE_WD.exec(text);
  313. cb(undefined, m ? m[1] : undefined);
  314. }, promote);
  315. };
  316. FTP.prototype.delete = function(path, cb) {
  317. this._send('DELE ' + path, cb);
  318. };
  319. FTP.prototype.site = function(cmd, cb) {
  320. this._send('SITE ' + cmd, cb);
  321. };
  322. FTP.prototype.status = function(cb) {
  323. this._send('STAT', cb);
  324. };
  325. FTP.prototype.rename = function(from, to, cb) {
  326. var self = this;
  327. this._send('RNFR ' + from, function(err) {
  328. if (err)
  329. return cb(err);
  330. self._send('RNTO ' + to, cb, true);
  331. });
  332. };
  333. FTP.prototype.logout = function(cb) {
  334. this._send('QUIT', cb);
  335. };
  336. FTP.prototype.listSafe = function(path, zcomp, cb) {
  337. if (typeof path === 'string') {
  338. var self = this;
  339. // store current path
  340. this.pwd(function(err, origpath) {
  341. if (err) return cb(err);
  342. // change to destination path
  343. self.cwd(path, function(err) {
  344. if (err) return cb(err);
  345. // get dir listing
  346. self.list(zcomp || false, function(err, list) {
  347. // change back to original path
  348. if (err) return self.cwd(origpath, cb);
  349. self.cwd(origpath, function(err) {
  350. if (err) return cb(err);
  351. cb(err, list);
  352. });
  353. });
  354. });
  355. });
  356. } else
  357. this.list(path, zcomp, cb);
  358. };
  359. FTP.prototype.list = function(path, zcomp, cb) {
  360. var self = this, cmd;
  361. if (typeof path === 'function') {
  362. // list(function() {})
  363. cb = path;
  364. path = undefined;
  365. cmd = 'LIST';
  366. zcomp = false;
  367. } else if (typeof path === 'boolean') {
  368. // list(true, function() {})
  369. cb = zcomp;
  370. zcomp = path;
  371. path = undefined;
  372. cmd = 'LIST';
  373. } else if (typeof zcomp === 'function') {
  374. // list('/foo', function() {})
  375. cb = zcomp;
  376. cmd = 'LIST ' + path;
  377. zcomp = false;
  378. } else
  379. cmd = 'LIST ' + path;
  380. this._pasv(function(err, sock) {
  381. if (err)
  382. return cb(err);
  383. if (self._queue[0] && self._queue[0].cmd === 'ABOR') {
  384. sock.destroy();
  385. return cb();
  386. }
  387. var sockerr, done = false, replies = 0, entries, buffer = '', source = sock;
  388. if (zcomp) {
  389. source = zlib.createInflate();
  390. sock.pipe(source);
  391. }
  392. source.on('data', function(chunk) { buffer += chunk.toString('binary'); });
  393. source.once('error', function(err) {
  394. if (!sock.aborting)
  395. sockerr = err;
  396. });
  397. source.once('end', ondone);
  398. source.once('close', ondone);
  399. function ondone() {
  400. done = true;
  401. final();
  402. }
  403. function final() {
  404. if (done && replies === 2) {
  405. replies = 3;
  406. if (sockerr)
  407. return cb(new Error('Unexpected data connection error: ' + sockerr));
  408. if (sock.aborting)
  409. return cb();
  410. // process received data
  411. entries = buffer.split(RE_EOL);
  412. entries.pop(); // ending EOL
  413. var parsed = [];
  414. for (var i = 0, len = entries.length; i < len; ++i) {
  415. var parsedVal = Parser.parseListEntry(entries[i]);
  416. if (parsedVal !== null)
  417. parsed.push(parsedVal);
  418. }
  419. if (zcomp) {
  420. self._send('MODE S', function() {
  421. cb(undefined, parsed);
  422. }, true);
  423. } else
  424. cb(undefined, parsed);
  425. }
  426. }
  427. if (zcomp) {
  428. self._send('MODE Z', function(err, text, code) {
  429. if (err) {
  430. sock.destroy();
  431. return cb(makeError(code, 'Compression not supported'));
  432. }
  433. sendList();
  434. }, true);
  435. } else
  436. sendList();
  437. function sendList() {
  438. // this callback will be executed multiple times, the first is when server
  439. // replies with 150 and then a final reply to indicate whether the
  440. // transfer was actually a success or not
  441. self._send(cmd, function(err, text, code) {
  442. if (err) {
  443. sock.destroy();
  444. if (zcomp) {
  445. self._send('MODE S', function() {
  446. cb(err);
  447. }, true);
  448. } else
  449. cb(err);
  450. return;
  451. }
  452. // some servers may not open a data connection for empty directories
  453. if (++replies === 1 && code === 226) {
  454. replies = 2;
  455. sock.destroy();
  456. final();
  457. } else if (replies === 2)
  458. final();
  459. }, true);
  460. }
  461. });
  462. };
  463. FTP.prototype.get = function(path, zcomp, cb) {
  464. var self = this;
  465. if (typeof zcomp === 'function') {
  466. cb = zcomp;
  467. zcomp = false;
  468. }
  469. this._pasv(function(err, sock) {
  470. if (err)
  471. return cb(err);
  472. if (self._queue[0] && self._queue[0].cmd === 'ABOR') {
  473. sock.destroy();
  474. return cb();
  475. }
  476. // modify behavior of socket events so that we can emit 'error' once for
  477. // either a TCP-level error OR an FTP-level error response that we get when
  478. // the socket is closed (e.g. the server ran out of space).
  479. var sockerr, started = false, lastreply = false, done = false,
  480. source = sock;
  481. if (zcomp) {
  482. source = zlib.createInflate();
  483. sock.pipe(source);
  484. sock._emit = sock.emit;
  485. sock.emit = function(ev, arg1) {
  486. if (ev === 'error') {
  487. if (!sockerr)
  488. sockerr = arg1;
  489. return;
  490. }
  491. sock._emit.apply(sock, Array.prototype.slice.call(arguments));
  492. };
  493. }
  494. source._emit = source.emit;
  495. source.emit = function(ev, arg1) {
  496. if (ev === 'error') {
  497. if (!sockerr)
  498. sockerr = arg1;
  499. return;
  500. } else if (ev === 'end' || ev === 'close') {
  501. if (!done) {
  502. done = true;
  503. ondone();
  504. }
  505. return;
  506. }
  507. source._emit.apply(source, Array.prototype.slice.call(arguments));
  508. };
  509. function ondone() {
  510. if (done && lastreply) {
  511. self._send('MODE S', function() {
  512. source._emit('end');
  513. source._emit('close');
  514. }, true);
  515. }
  516. }
  517. sock.pause();
  518. if (zcomp) {
  519. self._send('MODE Z', function(err, text, code) {
  520. if (err) {
  521. sock.destroy();
  522. return cb(makeError(code, 'Compression not supported'));
  523. }
  524. sendRetr();
  525. }, true);
  526. } else
  527. sendRetr();
  528. function sendRetr() {
  529. // this callback will be executed multiple times, the first is when server
  530. // replies with 150, then a final reply after the data connection closes
  531. // to indicate whether the transfer was actually a success or not
  532. self._send('RETR ' + path, function(err, text, code) {
  533. if (sockerr || err) {
  534. sock.destroy();
  535. if (!started) {
  536. if (zcomp) {
  537. self._send('MODE S', function() {
  538. cb(sockerr || err);
  539. }, true);
  540. } else
  541. cb(sockerr || err);
  542. } else {
  543. source._emit('error', sockerr || err);
  544. source._emit('close', true);
  545. }
  546. return;
  547. }
  548. // server returns 125 when data connection is already open; we treat it
  549. // just like a 150
  550. if (code === 150 || code === 125) {
  551. started = true;
  552. cb(undefined, source);
  553. sock.resume();
  554. } else {
  555. lastreply = true;
  556. ondone();
  557. }
  558. }, true);
  559. }
  560. });
  561. };
  562. FTP.prototype.put = function(input, path, zcomp, cb) {
  563. this._store('STOR ' + path, input, zcomp, cb);
  564. };
  565. FTP.prototype.append = function(input, path, zcomp, cb) {
  566. this._store('APPE ' + path, input, zcomp, cb);
  567. };
  568. FTP.prototype.pwd = function(cb) { // PWD is optional
  569. var self = this;
  570. this._send('PWD', function(err, text, code) {
  571. if (code === 502) {
  572. return self.cwd('.', function(cwderr, cwd) {
  573. if (cwderr)
  574. return cb(cwderr);
  575. if (cwd === undefined)
  576. cb(err);
  577. else
  578. cb(undefined, cwd);
  579. }, true);
  580. } else if (err)
  581. return cb(err);
  582. cb(undefined, RE_WD.exec(text)[1]);
  583. });
  584. };
  585. FTP.prototype.cdup = function(cb) { // CDUP is optional
  586. var self = this;
  587. this._send('CDUP', function(err, text, code) {
  588. if (code === 502)
  589. self.cwd('..', cb, true);
  590. else
  591. cb(err);
  592. });
  593. };
  594. FTP.prototype.mkdir = function(path, recursive, cb) { // MKD is optional
  595. if (typeof recursive === 'function') {
  596. cb = recursive;
  597. recursive = false;
  598. }
  599. if (!recursive)
  600. this._send('MKD ' + path, cb);
  601. else {
  602. var self = this, owd, abs, dirs, dirslen, i = -1, searching = true;
  603. abs = (path[0] === '/');
  604. var nextDir = function() {
  605. if (++i === dirslen) {
  606. // return to original working directory
  607. return self._send('CWD ' + owd, cb, true);
  608. }
  609. if (searching) {
  610. self._send('CWD ' + dirs[i], function(err, text, code) {
  611. if (code === 550) {
  612. searching = false;
  613. --i;
  614. } else if (err) {
  615. // return to original working directory
  616. return self._send('CWD ' + owd, function() {
  617. cb(err);
  618. }, true);
  619. }
  620. nextDir();
  621. }, true);
  622. } else {
  623. self._send('MKD ' + dirs[i], function(err, text, code) {
  624. if (err) {
  625. // return to original working directory
  626. return self._send('CWD ' + owd, function() {
  627. cb(err);
  628. }, true);
  629. }
  630. self._send('CWD ' + dirs[i], nextDir, true);
  631. }, true);
  632. }
  633. };
  634. this.pwd(function(err, cwd) {
  635. if (err)
  636. return cb(err);
  637. owd = cwd;
  638. if (abs)
  639. path = path.substr(1);
  640. if (path[path.length - 1] === '/')
  641. path = path.substring(0, path.length - 1);
  642. dirs = path.split('/');
  643. dirslen = dirs.length;
  644. if (abs)
  645. self._send('CWD /', function(err) {
  646. if (err)
  647. return cb(err);
  648. nextDir();
  649. }, true);
  650. else
  651. nextDir();
  652. });
  653. }
  654. };
  655. FTP.prototype.rmdir = function(path, recursive, cb) { // RMD is optional
  656. if (typeof recursive === 'function') {
  657. cb = recursive;
  658. recursive = false;
  659. }
  660. if (!recursive) {
  661. return this._send('RMD ' + path, cb);
  662. }
  663. var self = this;
  664. this.list(path, function(err, list) {
  665. if (err) return cb(err);
  666. var idx = 0;
  667. // this function will be called once per listing entry
  668. var deleteNextEntry;
  669. deleteNextEntry = function(err) {
  670. if (err) return cb(err);
  671. if (idx >= list.length) {
  672. if (list[0] && list[0].name === path) {
  673. return cb(null);
  674. } else {
  675. return self.rmdir(path, cb);
  676. }
  677. }
  678. var entry = list[idx++];
  679. // get the path to the file
  680. var subpath = null;
  681. if (entry.name[0] === '/') {
  682. // this will be the case when you call deleteRecursively() and pass
  683. // the path to a plain file
  684. subpath = entry.name;
  685. } else {
  686. if (path[path.length - 1] == '/') {
  687. subpath = path + entry.name;
  688. } else {
  689. subpath = path + '/' + entry.name
  690. }
  691. }
  692. // delete the entry (recursively) according to its type
  693. if (entry.type === 'd') {
  694. if (entry.name === "." || entry.name === "..") {
  695. return deleteNextEntry();
  696. }
  697. self.rmdir(subpath, true, deleteNextEntry);
  698. } else {
  699. self.delete(subpath, deleteNextEntry);
  700. }
  701. }
  702. deleteNextEntry();
  703. });
  704. };
  705. FTP.prototype.system = function(cb) { // SYST is optional
  706. this._send('SYST', function(err, text) {
  707. if (err)
  708. return cb(err);
  709. cb(undefined, RE_SYST.exec(text)[1]);
  710. });
  711. };
  712. // "Extended" (RFC 3659) commands
  713. FTP.prototype.size = function(path, cb) {
  714. var self = this;
  715. this._send('SIZE ' + path, function(err, text, code) {
  716. if (code === 502) {
  717. // Note: this may cause a problem as list() is _appended_ to the queue
  718. return self.list(path, function(err, list) {
  719. if (err)
  720. return cb(err);
  721. if (list.length === 1)
  722. cb(undefined, list[0].size);
  723. else {
  724. // path could have been a directory and we got a listing of its
  725. // contents, but here we echo the behavior of the real SIZE and
  726. // return 'File not found' for directories
  727. cb(new Error('File not found'));
  728. }
  729. }, true);
  730. } else if (err)
  731. return cb(err);
  732. cb(undefined, parseInt(text, 10));
  733. });
  734. };
  735. FTP.prototype.lastMod = function(path, cb) {
  736. var self = this;
  737. this._send('MDTM ' + path, function(err, text, code) {
  738. if (code === 502) {
  739. return self.list(path, function(err, list) {
  740. if (err)
  741. return cb(err);
  742. if (list.length === 1)
  743. cb(undefined, list[0].date);
  744. else
  745. cb(new Error('File not found'));
  746. }, true);
  747. } else if (err)
  748. return cb(err);
  749. var val = XRegExp.exec(text, REX_TIMEVAL), ret;
  750. if (!val)
  751. return cb(new Error('Invalid date/time format from server'));
  752. ret = new Date(val.year + '-' + val.month + '-' + val.date + 'T' + val.hour
  753. + ':' + val.minute + ':' + val.second);
  754. cb(undefined, ret);
  755. });
  756. };
  757. FTP.prototype.restart = function(offset, cb) {
  758. this._send('REST ' + offset, cb);
  759. };
  760. // Private/Internal methods
  761. FTP.prototype._pasv = function(cb) {
  762. var self = this, first = true, ip, port;
  763. this._send('PASV', function reentry(err, text) {
  764. if (err)
  765. return cb(err);
  766. self._curReq = undefined;
  767. if (first) {
  768. var m = RE_PASV.exec(text);
  769. if (!m)
  770. return cb(new Error('Unable to parse PASV server response'));
  771. ip = m[1];
  772. ip += '.';
  773. ip += m[2];
  774. ip += '.';
  775. ip += m[3];
  776. ip += '.';
  777. ip += m[4];
  778. port = (parseInt(m[5], 10) * 256) + parseInt(m[6], 10);
  779. first = false;
  780. }
  781. self._pasvConnect(ip, port, function(err, sock) {
  782. if (err) {
  783. // try the IP of the control connection if the server was somehow
  784. // misconfigured and gave for example a LAN IP instead of WAN IP over
  785. // the Internet
  786. if (self._socket && ip !== self._socket.remoteAddress) {
  787. ip = self._socket.remoteAddress;
  788. return reentry();
  789. }
  790. // automatically abort PASV mode
  791. self._send('ABOR', function() {
  792. cb(err);
  793. self._send();
  794. }, true);
  795. return;
  796. }
  797. cb(undefined, sock);
  798. self._send();
  799. });
  800. });
  801. };
  802. FTP.prototype._pasvConnect = function(ip, port, cb) {
  803. var self = this,
  804. socket = new Socket(),
  805. sockerr,
  806. timedOut = false,
  807. timer = setTimeout(function() {
  808. timedOut = true;
  809. socket.destroy();
  810. cb(new Error('Timed out while making data connection'));
  811. }, this.options.pasvTimeout);
  812. socket.setTimeout(0);
  813. socket.once('connect', function() {
  814. self._debug&&self._debug('[connection] PASV socket connected');
  815. if (self.options.secure === true) {
  816. self.options.secureOptions.socket = socket;
  817. self.options.secureOptions.session = self._socket.getSession();
  818. //socket.removeAllListeners('error');
  819. socket = tls.connect(self.options.secureOptions);
  820. //socket.once('error', onerror);
  821. socket.setTimeout(0);
  822. }
  823. clearTimeout(timer);
  824. self._pasvSocket = socket;
  825. cb(undefined, socket);
  826. });
  827. socket.once('error', onerror);
  828. function onerror(err) {
  829. sockerr = err;
  830. }
  831. socket.once('end', function() {
  832. clearTimeout(timer);
  833. });
  834. socket.once('close', function(had_err) {
  835. clearTimeout(timer);
  836. if (!self._pasvSocket && !timedOut) {
  837. var errmsg = 'Unable to make data connection';
  838. if (sockerr) {
  839. errmsg += '( ' + sockerr + ')';
  840. sockerr = undefined;
  841. }
  842. cb(new Error(errmsg));
  843. }
  844. self._pasvSocket = undefined;
  845. });
  846. socket.connect(port, ip);
  847. };
  848. FTP.prototype._store = function(cmd, input, zcomp, cb) {
  849. var isBuffer = Buffer.isBuffer(input);
  850. if (!isBuffer && input.pause !== undefined)
  851. input.pause();
  852. if (typeof zcomp === 'function') {
  853. cb = zcomp;
  854. zcomp = false;
  855. }
  856. var self = this;
  857. this._pasv(function(err, sock) {
  858. if (err)
  859. return cb(err);
  860. if (self._queue[0] && self._queue[0].cmd === 'ABOR') {
  861. sock.destroy();
  862. return cb();
  863. }
  864. var sockerr, dest = sock;
  865. sock.once('error', function(err) {
  866. sockerr = err;
  867. });
  868. if (zcomp) {
  869. self._send('MODE Z', function(err, text, code) {
  870. if (err) {
  871. sock.destroy();
  872. return cb(makeError(code, 'Compression not supported'));
  873. }
  874. // draft-preston-ftpext-deflate-04 says min of 8 should be supported
  875. dest = zlib.createDeflate({ level: 8 });
  876. dest.pipe(sock);
  877. sendStore();
  878. }, true);
  879. } else
  880. sendStore();
  881. function sendStore() {
  882. // this callback will be executed multiple times, the first is when server
  883. // replies with 150, then a final reply after the data connection closes
  884. // to indicate whether the transfer was actually a success or not
  885. self._send(cmd, function(err, text, code) {
  886. if (sockerr || err) {
  887. if (zcomp) {
  888. self._send('MODE S', function() {
  889. cb(sockerr || err);
  890. }, true);
  891. } else
  892. cb(sockerr || err);
  893. return;
  894. }
  895. if (code === 150 || code === 125) {
  896. if (isBuffer)
  897. dest.end(input);
  898. else if (typeof input === 'string') {
  899. // check if input is a file path or just string data to store
  900. fs.stat(input, function(err, stats) {
  901. if (err)
  902. dest.end(input);
  903. else
  904. fs.createReadStream(input).pipe(dest);
  905. });
  906. } else {
  907. input.pipe(dest);
  908. input.resume();
  909. }
  910. } else {
  911. if (zcomp)
  912. self._send('MODE S', cb, true);
  913. else
  914. cb();
  915. }
  916. }, true);
  917. }
  918. });
  919. };
  920. FTP.prototype._send = function(cmd, cb, promote) {
  921. clearTimeout(this._keepalive);
  922. if (cmd !== undefined) {
  923. if (promote)
  924. this._queue.unshift({ cmd: cmd, cb: cb });
  925. else
  926. this._queue.push({ cmd: cmd, cb: cb });
  927. }
  928. var queueLen = this._queue.length;
  929. if (!this._curReq && queueLen && this._socket && this._socket.readable) {
  930. this._curReq = this._queue.shift();
  931. if (this._curReq.cmd === 'ABOR' && this._pasvSocket)
  932. this._pasvSocket.aborting = true;
  933. this._debug&&this._debug('[connection] > ' + inspect(this._curReq.cmd));
  934. this._socket.write(this._curReq.cmd + '\r\n');
  935. } else if (!this._curReq && !queueLen && this._ending)
  936. this._reset();
  937. };
  938. FTP.prototype._reset = function() {
  939. if (this._pasvSock && this._pasvSock.writable)
  940. this._pasvSock.end();
  941. if (this._socket && this._socket.writable)
  942. this._socket.end();
  943. this._socket = undefined;
  944. this._pasvSock = undefined;
  945. this._feat = undefined;
  946. this._curReq = undefined;
  947. this._secstate = undefined;
  948. clearTimeout(this._keepalive);
  949. this._keepalive = undefined;
  950. this._queue = [];
  951. this._ending = false;
  952. this._parser = undefined;
  953. this.options.host = this.options.port = this.options.user
  954. = this.options.password = this.options.secure
  955. = this.options.connTimeout = this.options.pasvTimeout
  956. = this.options.keepalive = this._debug = undefined;
  957. this.connected = false;
  958. };
  959. // Utility functions
  960. function makeError(code, text) {
  961. var err = new Error(text);
  962. err.code = code;
  963. return err;
  964. }