Compare commits

..

191 Commits
v2.1.0 ... v3

Author SHA1 Message Date
Tyler Stewart
aa1e543c24 WIP: wip 2018-05-25 09:55:50 -06:00
Tyler Stewart
57f7fa23cc WIP: wip 2018-05-21 21:38:11 -06:00
Tyler Stewart
e0dbbfce2d WIP(example): basic example 2018-03-28 20:33:13 -06:00
Tyler Stewart
fc8981021c WIP: message constants 2018-03-28 20:33:04 -06:00
Tyler Stewart
cf9852465a WIP: command processing and handling 2018-03-28 20:32:43 -06:00
Tyler Stewart
1f3f26706e WIP: queue system 2018-03-28 20:32:32 -06:00
Tyler Stewart
54cb2a2fe4 chore: meta files 2018-03-28 20:31:58 -06:00
Tyler Stewart
5fd6414e60 chore: update circle ci config 2018-03-11 17:38:12 -06:00
Tyler Stewart
ef7750def0 chore(examples): add basic example of usage 2018-03-07 21:07:37 -07:00
Tyler Stewart
427275a0b8 test: remove old test folder
Tests will now live beside src files
2018-03-07 21:07:09 -07:00
Tyler Stewart
c428787ade refactor: rewrite for v3 basis
BREAKING CHANGE: rewrite with new api
2018-03-07 21:06:09 -07:00
Tyler Stewart
8566df451e refactor(logo): async/await logo generation 2018-03-07 21:05:41 -07:00
Tyler Stewart
35789e430a chore: initiate new config files
Begining of v3
2018-03-07 21:05:13 -07:00
Tyler Stewart
a468d4ffd0 chore(readme): add file events to docs 2018-02-09 19:38:04 -07:00
Tyler Stewart
40b08893ac refactor(connection): only return IP of commandSocket
Since the dataSocket and commandSocket must be on the same IP for a data channel to open, it is redundant to check the dataSocket IP.
2018-02-09 19:38:04 -07:00
Tyler Stewart
8a2454ceea fix(connection): remove listeners on close 2018-02-09 19:38:04 -07:00
Tyler Stewart
0c7cc4fe6e test: new events 2018-02-09 19:38:04 -07:00
Tyler Stewart
6ea6baceb0 feat(server): extend event emitter 2018-02-09 19:38:04 -07:00
Tyler Stewart
b07e0189ee feat(connection): extend event emitter
Allow custom events
2018-02-09 19:38:04 -07:00
Tyler Stewart
ec30a5a4f3 feat(stor): emit connection event on upload success/failure 2018-02-09 19:38:04 -07:00
Tyler Stewart
6020409979 feat(retr): emit connection event on success/failure 2018-02-09 19:38:04 -07:00
Tyler Stewart
c60606971a chore(readme): update badges 2018-01-21 14:55:04 -07:00
Tyler Stewart
bd41b31821 chore(readme): update logo placement 2018-01-21 14:31:27 -07:00
Tyler Stewart
ce1c526c41 chore(logo): new logo design 2018-01-21 14:31:27 -07:00
Tyler Stewart
d822101a07 chore(readme): update coveralls badge 2018-01-10 11:13:28 -07:00
Tyler Stewart
47c8eedd3b chore: fix semantic release 2018-01-10 11:01:39 -07:00
Tyler Stewart
6c08cc2aed refactor: assimilate promises using resolve instead of try 2018-01-10 10:49:02 -07:00
Tyler Stewart
e2a5c78b0a fix(abor): send 225 if no file transfer in progress 2018-01-10 10:49:02 -07:00
Tyler Stewart
2cadac3f7e chore(readme): add reference links 2018-01-10 10:49:02 -07:00
Tyler Stewart
2255be9acd feat(connector): return promise on end 2018-01-10 10:49:02 -07:00
Tyler Stewart
d22c911a36 refactor(connection): completely parse message before handling 2018-01-10 10:49:02 -07:00
Tyler Stewart
5dabbc251b refactor(opts): simplify setting 2018-01-10 10:49:02 -07:00
Tyler Stewart
ef89577627 refactor(list): simplify reply 2018-01-10 10:49:02 -07:00
Tyler Stewart
8fbe750086 refactor(stat): simplify replys 2018-01-10 10:49:02 -07:00
Tyler Stewart
3b33508f44 feat: migrate to bluebird
Replace `when` with `bluebird` promise library
2018-01-10 10:49:02 -07:00
Tyler Stewart
23368b04b9 test: update stor fail test timing 2018-01-10 10:24:41 -07:00
Tyler Stewart
876a061e92 refactor: ensure reject is called on destroyConnection 2018-01-10 10:24:41 -07:00
Tyler Stewart
65b1fd27a0 fix(stor): pause connection to avoid memory build up 2018-01-10 10:24:41 -07:00
James Suárez
286c1063fa fix(retr): pause read stream to avoid memory build up 2018-01-10 10:24:41 -07:00
Tyler Stewart
e87c36d7ff chore: fix semantic releasing 2017-12-08 17:50:16 -07:00
Tyler Stewart
de0aafad2f fix(stat): fix stat on file
Ensure message sent raw
2017-12-08 17:50:16 -07:00
Tyler Stewart
4f80e11745 fix(stat): fix file response
Ensures correct response when `stat`-ing a file

```
212-Status begin
...
212 Status end
```
2017-12-08 17:40:10 -07:00
Tyler Stewart
6bbd905379 test: update integration tests 2017-11-12 20:50:11 -07:00
Tyler Stewart
de50f55457 test(circleci): fix workflow 2017-11-12 18:01:26 -07:00
Ozair Patel
32cdedd163 chore: add public properties to typings 2017-11-12 17:50:51 -07:00
Tyler Stewart
6c2c1a87dc test: use mock fs 2017-11-12 17:50:51 -07:00
Tyler Stewart
9e83143690 chore: improve tests 2017-11-12 17:50:51 -07:00
Tyler Stewart
0238529edf chore: change dev dependencies 2017-11-12 17:50:51 -07:00
Tyler Stewart
d0c204eb81 chore: migrate to circle ci 2.0 2017-11-12 17:50:51 -07:00
Tyler Stewart
cdebe9a464 chore: remove .env 2017-11-12 17:50:51 -07:00
Tyler Stewart
eeb8f9ab4d chore(mocha): use pretty bunyan nyan reporter 2017-11-12 17:50:51 -07:00
Tyler Stewart
60d06c21c8 test: update test flow
Wrap each difference in a describe block
2017-11-12 17:50:51 -07:00
Tyler Stewart
8609b1d02e chore(package): update dependenices
Adds back package-lock
2017-11-12 17:50:51 -07:00
Tyler Stewart
80b05215ff chore(config): add timeouts to tests 2017-11-12 17:50:51 -07:00
Peter Keuter
37f0a15549 fix: updated typings 2017-11-06 10:21:38 -07:00
Tyler Stewart
1ba67034b1 chore(README): fix class name references 2017-10-31 16:18:36 -06:00
Tyler Stewart
0a331c5998 fix(package): correct main file
This was changed with the confit update
2017-10-31 16:18:36 -06:00
Tyler Stewart
a7103ded7e fix: add values to resolved promises 2017-10-30 18:48:42 -06:00
Tyler Stewart
d787d4cab6 test(site): test site registry call 2017-10-30 17:52:05 -06:00
Tyler Stewart
154cd5a5d7 chore: eslint --fix 2017-10-30 17:52:05 -06:00
Tyler Stewart
5fc59b50b1 chore: update package versions 2017-10-30 17:52:05 -06:00
Tyler Stewart
043c97c80f chore: update build with confit 2017-10-30 17:52:05 -06:00
Tyler Stewart
772fe5ca06 feat: add eprt and epsv for IPv6 support 2017-10-30 17:52:05 -06:00
Ozair Patel
e272802525 feat(typings): swapped declare class for export interface 2017-10-25 21:46:24 -06:00
Ozair Patel
7589322abc feat(typings): removed Server extension for FtpServer 2017-10-25 21:46:24 -06:00
Ozair Patel
fae5564041 feat(typings): removed typed dependency and fixed import error 2017-10-25 21:46:24 -06:00
Ozair Patel
e9b4a6385d feat(typings): ypdated typescript typings 2017-10-25 21:46:24 -06:00
Tyler Stewart
71621aae4f Merge pull request #44 from trs/include-types-file-on-install
fix(package): include types file
2017-10-25 12:22:57 -06:00
Tyler Stewart
0eaa0f8743 chore(travis): only test v6
Node 8 fails for some reason, will look into in the future
2017-10-25 12:18:14 -06:00
Tyler Stewart
8828a4ea09 fix(package): include types file
Should ensure types are inluded on an install
2017-10-25 12:00:20 -06:00
Tyler Stewart
b33659320f Merge pull request #40 from trs/fix-socket-ref
fix(retr): check for connector socket
2017-09-30 11:14:31 -06:00
Tyler Stewart
6a6b949d3b fix(retr): check for connector socket
Ensures socket still exists and client hasn't disconnected
2017-09-30 11:09:30 -06:00
Tyler Stewart
283be85db3 Merge pull request #38 from trs/improve-connector-stream-handling
Improve connector stream handling
2017-08-18 12:45:32 -06:00
Tyler Stewart
e555ce9230 test(stor): add failure test 2017-08-18 12:06:58 -06:00
Tyler Stewart
e6575808f1 fix(stor): improve event and promise handling 2017-08-18 12:06:42 -06:00
Tyler Stewart
a5e58a106e fix(retr): improve event and promise handling 2017-08-18 12:06:42 -06:00
Tyler Stewart
ed086e576a Merge pull request #36 from trs/fix-process-exit
Fix process exit
2017-08-14 17:07:05 -06:00
Tyler Stewart
31f0f3b0dc fix: ensure process exits 2017-08-14 16:46:11 -06:00
Tyler Stewart
d763820c86 refactor: connector socket getter 2017-08-14 16:45:37 -06:00
Tyler Stewart
f3183314cc Merge pull request #34 from trs/add-typings
feat(typings): add TypeScript .d.ts files
2017-07-24 11:00:13 -06:00
Chris Rabl
dde7b36c46 feat(typings): add TypeScript .d.ts files
* created outline for TypeScript declarations
* added basic object shapes for FtpServer and FileSystem
2017-07-24 10:53:41 -06:00
Tyler Stewart
00af9e7e61 Merge pull request #32 from trs/command-args
Command args
2017-07-10 10:02:55 -06:00
Tyler Stewart
99a885cd44 test(commands): update parser tests 2017-07-10 09:58:24 -06:00
Tyler Stewart
443051d753 fix(commands): get flags from ftp command 2017-07-07 17:28:09 -06:00
Tyler Stewart
27ecc4d835 fix(feat): order features alphabetically 2017-07-06 17:51:06 -06:00
Tyler Stewart
c8526be1f4 Merge pull request #30 from trs/fix-utf8
Fix utf8
2017-06-26 19:54:51 -06:00
Tyler Stewart
e0b11ff480 fix: cleanup server 2017-06-26 16:39:00 -06:00
Tyler Stewart
58b9d8db9d chore: update fs readme 2017-06-26 16:39:00 -06:00
Tyler Stewart
fa121ba0fd test(REST): add tests 2017-06-26 16:39:00 -06:00
Tyler Stewart
2e02dc20ad feat(REST): add support for REST command
Allows the client to resume a transfer at the specified bytes
2017-06-26 16:38:59 -06:00
Tyler Stewart
8aeb6976d2 fix(auth): update checks, ensure secure is set using ftps 2017-06-26 16:38:59 -06:00
Tyler Stewart
84a68ae03c chore: dont append branch name to commit 2017-06-26 12:34:21 -06:00
Tyler Stewart
9dfc80b99d test(OPTS): update tests
master
2017-06-26 11:19:42 -06:00
Tyler Stewart
090e3d8105 chore: update log levels 2017-06-26 11:13:55 -06:00
Tyler Stewart
c3b0dbf5b0 feat(OPTS): add opts command handler for utf8
master
2017-06-26 11:13:49 -06:00
Tyler Stewart
69a5133936 fix(FEAT): correctly display feature list 2017-06-26 11:13:00 -06:00
Tyler Stewart
5394908a6b Merge pull request #29 from trs/fix-tls-check
Fix encoding/transfer type
2017-06-20 17:20:23 -06:00
Tyler Stewart
3e7bd5bcf9 chore: update licence format
Still MIT, just updating to ensure GitHub recognizes it
2017-06-20 17:09:49 -06:00
Tyler Stewart
175b422c5f chore: update dependencies 2017-06-20 17:02:05 -06:00
Tyler Stewart
b2a9851204 fix: ensure utf8 support; allows accent characters 2017-06-20 16:56:26 -06:00
Tyler Stewart
977dd1579a fix(TYPE): correctly set types, only use for data connections 2017-06-20 16:55:37 -06:00
Tyler Stewart
176b2b7ca8 fix: actually check _tls 2017-06-20 14:47:44 -06:00
Tyler Stewart
63777c0d74 Merge pull request #26 from trs/test-updates
Test updates
2017-06-16 15:17:31 -06:00
Tyler Stewart
9be8ffa60d test: add and update tests 2017-06-09 15:00:01 -06:00
Tyler Stewart
b8cd6022e1 fix: assign tls options to empty object 2017-06-09 14:40:19 -06:00
Tyler Stewart
0618a3c675 fix(passive): throw error on invalid port range 2017-06-09 14:39:21 -06:00
Tyler Stewart
3c533a5fbc Merge pull request #25 from trs/export-fs
Export fs
2017-06-09 10:31:42 -06:00
Tyler Stewart
3d0a58ca15 docs(readme): update file system override details
master

export-fs

export-fs
2017-06-09 10:28:03 -06:00
Tyler Stewart
4b4c809af8 feat: export FileSystem and FtpSrv
Non breaking, as it still exports FtpSrv by default
2017-06-09 10:28:03 -06:00
Tyler Stewart
a234534de0 Merge pull request #23 from trs/write-stream-close
feat(fs): close stream before ending
2017-06-08 17:35:58 -06:00
Tyler Stewart
635fb35341 fix(stor): end stream if no close listener present 2017-06-08 17:31:02 -06:00
Tyler Stewart
51a6448ac2 fix(stor): ensure stream is destroyed once used up 2017-06-08 17:23:14 -06:00
Tyler Stewart
4d8a69615c feat(fs): close stream before ending
This allows processing of the received data before a response is sent to the client.

write-stream-close
2017-06-08 17:17:09 -06:00
Tyler Stewart
ab5a2e9641 chore(travis): dont cleanup on deploy 2017-06-08 15:19:35 -06:00
Tyler Stewart
a7f25accd2 Merge pull request #21 from trs/list-fix
List fix
2017-06-08 15:16:09 -06:00
Tyler Stewart
c49a361c36 chore(package): add package-lock 2017-06-08 14:10:56 -06:00
Tyler Stewart
d3d65aa5cf chore(package): update package dependency versions 2017-06-08 14:09:44 -06:00
Tyler Stewart
e53848f881 chore(travis): test multiple node versions, update deployment script
list-fix

HEAD
2017-06-08 14:03:03 -06:00
Tyler Stewart
b5cf75b09f chore(package): specify npm files 2017-06-08 13:54:22 -06:00
Tyler Stewart
dd0a790519 docs(readme): update fs docs to reflect list changes 2017-06-08 13:40:41 -06:00
Tyler Stewart
e25ee55865 test: update tests to reflect list changes 2017-06-08 13:40:27 -06:00
Tyler Stewart
0433bb48cd fix(stat): allow a file as an argument
If a file is passed as an argument, will send only that file's stat.
Otherwise, send the stats for all items in directory (current or provided)
2017-06-08 13:38:00 -06:00
Tyler Stewart
350c2b3e81 chore(readme): add coveralls badge 2017-05-25 23:24:26 -06:00
Tyler Stewart
887bf1fa58 chore: upload test coverage to coveralls 2017-05-25 23:02:37 -06:00
Tyler Stewart
70a62f1da1 Merge pull request #17 from trs/update-logo
fix: update logo
2017-05-20 21:34:19 -06:00
Tyler Stewart
3a1afdb694 fix: update logo
update-logo

update-logo

update-logo

update-logo

update-logo

update-logo
2017-05-20 21:31:22 -06:00
Tyler Stewart
10127b32e5 chore(readme): move badges under description 2017-05-19 13:08:34 -06:00
Tyler Stewart
e1aad3e021 Merge pull request #16 from trs/fix-secure-check
Fix secure check
2017-05-19 13:01:35 -06:00
Tyler Stewart
a254e6c5f3 chore: update logo, generate png
master

master

master
2017-05-19 12:28:29 -06:00
Tyler Stewart
c46d6086ea fix: simplifiy secure check 2017-05-19 12:28:29 -06:00
Tyler Stewart
88f02cd498 Merge pull request #14 from trs/explicit-tls-support
feat: add explicit TLS support with AUTH
2017-05-15 21:38:44 -06:00
Tyler Stewart
2cc5d54d7f chore: add logo
explicit-tls-support

explicit-tls-support

explicit-tls-support

explicit-tls-support

explicit-tls-support
2017-05-15 21:35:56 -06:00
Tyler Stewart
f127d0e7b6 fix: correct user/pass tests 2017-05-15 15:55:34 -06:00
Tyler Stewart
13048a96bd docs(commands): fix command sytanx structure 2017-05-15 15:55:34 -06:00
Tyler Stewart
f6355e66c3 fix: correctly set _tls to false if not set
explicit-tls-support
2017-05-15 15:55:34 -06:00
Tyler Stewart
6e79e958cc fix: improve anonymous login
Only initiate anonymous login if username is anonymous
2017-05-15 15:55:34 -06:00
Tyler Stewart
db7d88f411 docs(readme): add explicit connections to features 2017-05-15 15:55:33 -06:00
Tyler Stewart
323ee62110 test: test explicit TLS 2017-05-15 15:55:33 -06:00
Tyler Stewart
1e446a7801 fix: add no_auth flag to secure commands 2017-05-15 15:55:33 -06:00
Tyler Stewart
977fbd4190 chore(package): fix username change 2017-05-15 15:55:33 -06:00
Tyler Stewart
d5d1b98b04 test: test new secure commands 2017-05-12 11:50:58 -06:00
Tyler Stewart
df0a4d640c fix: update secure checks 2017-05-12 11:50:43 -06:00
Tyler Stewart
73274191fe feat: add explicit tls support for active transfer
explicit-tls-support
2017-05-12 11:50:37 -06:00
Tyler Stewart
37c3da3a62 fix: correctly reference connection in client-error event 2017-05-12 11:32:54 -06:00
Tyler Stewart
9bece5f946 feat: add explicit TLS support with AUTH 2017-05-11 18:59:54 -06:00
Tyler Stewart
83947142df Merge pull request #13 from stewarttylerr/implicit-tls-feats
Implicit tls feats
2017-05-11 17:34:14 -06:00
Tyler Stewart
c54045e0b9 fix: correct ls and ep file stat formats
master

master

master

master
2017-05-11 16:48:08 -06:00
Tyler Stewart
cf71243729 fix: get dataSocket ip if available 2017-05-11 16:38:14 -06:00
Tyler Stewart
7fb43a5790 test: add test certs 2017-05-11 15:49:28 -06:00
Tyler Stewart
e99059125e feat(connection): add client-error events 2017-05-11 15:49:28 -06:00
Tyler Stewart
954e9a1252 feat(server): add greeting and implicit TLS 2017-05-11 15:45:28 -06:00
Tyler Stewart
2b9e163958 chore: exclude errors file from test coverage 2017-05-11 15:39:36 -06:00
Tyler Stewart
c6a49d2191 docs(readme): update readme readability 2017-05-11 15:39:14 -06:00
Tyler Stewart
14e5f87cc3 fix: allow error messages to be set via catch 2017-05-11 15:36:49 -06:00
Tyler Stewart
580b8d6eae Merge pull request #12 from stewarttylerr/fix-compatability-bugs
Fix compatability bugs
2017-05-05 18:29:00 -06:00
Tyler Stewart
a75d63df92 fix(fs): resolve paths correctly
Should solve win32 issues

fix-compatability-bugs

fix-compatability-bugs
2017-05-05 18:08:47 -06:00
Tyler Stewart
301ae110e8 test: update tests and directory structure 2017-05-05 18:08:30 -06:00
Tyler Stewart
4d69b48466 chore: update mocha reporter 2017-05-05 18:08:30 -06:00
Tyler Stewart
ec010697bb feat(commands): remove minimist command parser for basic parsing
Tokenizes command string based on spaces, concats remaining arguments

This allows filesystem commands to handle directories/files with spaces.

fix-compatability-bugs
2017-05-05 18:08:30 -06:00
Tyler Stewart
cf3d543f1a fix(commands): correctly clone command for log 2017-05-05 18:04:54 -06:00
Tyler Stewart
69bec2b01c fix(fs): normalize fs paths
- Attempting to fix compatability on windows
2017-05-04 17:43:46 -06:00
Tyler Stewart
2eac41d127 test: update test setup
master
2017-05-04 17:43:41 -06:00
Tyler Stewart
eb32f93fc6 feat: close server on SIGINT (ctrl+c) 2017-05-04 17:42:47 -06:00
Tyler Stewart
095423606e fix(find-port): stop check at 65535 2017-05-04 17:42:10 -06:00
Tyler Stewart
61cf1bda39 feat(connection): add helper get for socket remote address 2017-05-04 17:40:37 -06:00
Tyler Stewart
75f847ed5d feat(commands): obfuscate password from logs 2017-05-04 17:40:01 -06:00
Tyler Stewart
ad4b32fc13 chore: add .env to github for tests 2017-05-04 17:39:15 -06:00
Tyler Stewart
be3c57bed0 Merge pull request #10 from stewarttylerr/sandbotorg-master
Sandbotorg master
2017-04-27 13:27:46 -06:00
Tyler Stewart
dc7dd1075c test(passive): merge master 2017-04-27 13:22:57 -06:00
salper
543e6cc1cc chore(readme): fix grammar 2017-04-27 13:22:39 -06:00
salper
5c1f8f7a65 fix: plug QUIT command
master
2017-04-27 13:19:29 -06:00
Tyler Stewart
557995a1a9 test(travis): add env variables 2017-04-27 13:17:01 -06:00
Tyler Stewart
45eca5afe0 test(passive): fix test 2017-04-27 12:49:55 -06:00
Tyler Stewart
695e594d97 Merge pull request #6 from stewarttylerr/migate-to-moment
feat: migrate to moment from date-fns, fix ls format
2017-03-31 17:14:44 -06:00
Tyler Stewart
97b55fc92c feat: migrate to moment from date-fns, fix ls format
Date-fns is great, but too early for use
2017-03-31 17:12:57 -06:00
Tyler Stewart
577066850b fix: improve getting current directory 2017-03-30 12:26:04 -06:00
Tyler Stewart
0ec989cf1e docs: update login event for new root option 2017-03-29 10:20:22 -06:00
Tyler Stewart
568833e216 Merge pull request #4 from stewarttylerr/set-fs-root
feat(fs): allow default file system root to be set
2017-03-29 10:15:33 -06:00
Tyler Stewart
6b0c06e588 fix: update tests 2017-03-29 10:13:32 -06:00
Tyler Stewart
acd485a571 test: more tests
set-fs-root
2017-03-28 14:27:40 -06:00
Tyler Stewart
2b2ca45673 test: update and add tests 2017-03-27 17:57:03 -06:00
Tyler Stewart
a62b6f9559 fix: resolve disconnectClient promise, linting 2017-03-27 17:51:10 -06:00
Tyler Stewart
84d54cbc2b fix(TYPE): correctly set encoding 2017-03-27 17:51:10 -06:00
Tyler Stewart
ef6134d91b fix: wrap fs calls with when, linting 2017-03-27 17:51:10 -06:00
Tyler Stewart
043d9369cc chore(readme): minor text fixes 2017-03-27 17:51:10 -06:00
Tyler Stewart
6b81748fd7 chore: minor text fixes 2017-03-27 17:51:10 -06:00
Tyler Stewart
0f4f5cdbd7 chore(readme): update api explainations
master
2017-03-27 17:51:10 -06:00
Tyler Stewart
0293752635 chore(readme): minor text fixes 2017-03-27 13:57:54 -06:00
Tyler Stewart
aa278105f9 chore: minor text fixes 2017-03-27 13:56:51 -06:00
Tyler Stewart
bbe0bf2942 chore(readme): update api explainations
master
2017-03-16 14:09:31 -06:00
Tyler Stewart
846df72e24 feat(fs): allow default file system root to be set
Enables users to only access portions of the file system (eg /home/user)
2017-03-13 13:29:15 -06:00
122 changed files with 5280 additions and 3333 deletions

61
.circleci/config.yml Normal file
View File

@@ -0,0 +1,61 @@
version: 2
jobs:
build:
docker:
- image: circleci/node:8
steps:
- checkout
- run:
name: Building...
command: npm install
- save_cache:
paths:
- node_modules
key: node_modules_{{ checksum package.json }}
lint:
docker:
- image: circleci/node:8
steps:
- checkout
- restore_cache:
key: node_modules_{{ checksum package.json }}
- run:
name: Linting...
command: npm run lint
test:
docker:
- image: circleci/node:8
steps:
- checkout
- restore_cache:
key: node_modules_{{ checksum package.json }}
- run:
name: Testing...
command: npm run test
publish:
branches:
only: master
docker:
- image: circleci/node:8
steps:
- checkout
- restore_cache:
key: node_modules_{{ checksum package.json }}
- run:
name: Publishing...
command: npx semantic-release
workflows:
version: 2
main:
jobs:
- build
- lint:
requires:
- build
- test:
requires:
- lint
- publish:
requires:
- test

2
.config/.eslintignore Normal file
View File

@@ -0,0 +1,2 @@
node_modules/*
config/*

15
.config/.eslintrc.json Normal file
View File

@@ -0,0 +1,15 @@
{
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true,
"jest": true
},
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module",
"ecmaFeatures": {
"impliedStrict": true
}
}
}

View File

@@ -1,6 +1,3 @@
# Editor Config - generated by Confit. This file will NOT be re-overwritten by Confit
# Feel free to customise it further.
# http://editorconfig.org
root = true
[*]

View File

@@ -1,9 +0,0 @@
# START_CONFIT_GENERATED_CONTENT
# Common folders to ignore
node_modules/*
bower_components/*
# Config folder (optional - you might want to lint this...)
config/*
# END_CONFIT_GENERATED_CONTENT

1
.github/.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
yarn.lock binary

2
.github/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
.vscode

View File

@@ -136,6 +136,9 @@ Command | Description
Command | Description
:------ | :----------
<pre>npm run verify</pre> | Verify code style and syntax<ul><li>Verifies source *and test code* aginst customisable rules (unlike Webpack loaders)</li></ul>
<pre>npm run verify:js</pre> | Verify Javascript code style and syntax
<pre>npm run verify:js:fix</pre> | Verify Javascript code style and syntax and fix any errors that can be fixed automatically
<pre>npm run verify:js:watch</pre> | Verify Javascript code style and syntax and watch files for changes
<pre>npm run verify:watch</pre> | Runs verify task whenever JS or CSS code is changed

6
.gitignore vendored
View File

@@ -1,6 +0,0 @@
node_modules/
dist/
reports/
.env
npm-debug.log

View File

@@ -1,12 +0,0 @@
language: node_js
node_js:
- "6"
install: npm install
script:
- npm run verify:js
- npm run test:coverage
after_success:
- if [ $TRAVIS_BRANCH = 'master' ]; then npm run semantic-release; fi

22
LICENSE
View File

@@ -1,9 +1,21 @@
ftp-srv Copyright (c) 2017 Tyler Stewart
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Copyright (c) 2018 Tyler Stewart
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

175
README.md
View File

@@ -1,162 +1,35 @@
# ftp-srv [![npm version](https://badge.fury.io/js/ftp-srv.svg)](https://badge.fury.io/js/ftp-srv) [![Build Status](https://travis-ci.org/stewarttylerr/ftp-srv.svg?branch=master)](https://travis-ci.org/stewarttylerr/ftp-srv) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
<p align="center">
<a href="https://github.com/trs/ftp-srv">
<img alt="ftp-srv" src="logo.png" width="600px" />
</a>
</p>
<!--[RM_DESCRIPTION]-->
> Modern, extensible FTP Server
<p align="center">
Modern, extensible FTP Server
</p>
<!--[]-->
<p align="center">
<a href="https://www.npmjs.com/package/ftp-srv">
<img alt="npm" src="https://img.shields.io/npm/dm/ftp-srv.svg?style=for-the-badge" />
</a>
- [Features](#features)
- [Install](#install)
- [Usage](#usage)
- [Contributing](#contributing)
- [License](#license)
<a href="https://circleci.com/gh/trs/ftp-srv">
<img alt="circleci" src="https://img.shields.io/circleci/project/github/trs/ftp-srv.svg?style=for-the-badge" />
</a>
## Features
- Supports passive and active connections
- Extensible [file system](#file-system)
<a href="https://coveralls.io/github/trs/ftp-srv?branch=master">
<img alt="coveralls" src="https://img.shields.io/coveralls/github/trs/ftp-srv.svg?style=for-the-badge" />
</a>
</p>
## Install
---
`npm install ftp-srv --save`
> Looking for v2? Check the [v2](#v2) branch.
`yarn add ftp-srv`
# Installation
## Usage
- [Options](#options)
- [Events](#events)
- [File System](#file-system)
```js
const FtpSvr = require('ftp-srv');
const ftpServer = new FtpSvr([url], { [options] ... });
ftpServer.on('...', (data, resolve, reject) => { ... })
ftpServer.listen()
.then(() => { ... });
```
$ yarn install
```
### Options
__url__ : `ftp://127.0.0.1:21`
> Host and port to listen on and make passive connections to.
Set the hostname to "0.0.0.0" to fetch the external IP automatically: `ftp://0.0.0.0:21`
__pasv_range__ : `22`
> Minimum port or range to use for passive connections.
Provide either a starting integer (`1000`) or a range (`1000-2000`).
__anonymous__ : `false`
> Set whether a valid username or password combination is required.
If true, will not require the `PASS` command to be sent for login.
__blacklist__ : `[]`
> Commands listed will not be allowed.
`['RMD', 'RNFR', 'RNTO']`
__whitelist__ : `[]`
> If set, no other commands are allowed except for those explicitly listed.
`['USER', 'PASS', 'PWD']`
__file_format__ : `ls`
> Format to use for [file stat](https://nodejs.org/api/fs.html#fs_class_fs_stats) responses (such as with the `LIST` command).
Possible values:
`ls` : [bin/ls format](https://cr.yp.to/ftp/list/binls.html)
`ep` : [Easily Parsed LIST format](https://cr.yp.to/ftp/list/eplf.html)
`function` : pass in your own format function, returning a string:
`function (fileStats) { ... }`
__log__ : `bunyan`
> A [bunyan logger](https://github.com/trentm/node-bunyan) instance.
### Events
All events emit the same structure: `({data object}, resolve, reject)`
__login__ : `{connection, username, password}`
> Occurs after `PASV` (or `USER` if `options.anonymous`)
```
resolve({
fs, // [optional] custom file system class
cwd, // [optional] initial working directory (if not using custom file system),
blacklist, // [optional] commands to forbid for this connection only
whitelist // [optional] if set, only these commands are allowed for this connection only
})
```
### File System
The file system can be overridden to use your own custom class. This an allow for interacting with files without actually writing them.
*Anytime a [file stat](https://nodejs.org/api/fs.html#fs_class_fs_stats) object is used, it must have added `name` property with the file's name.*
#### Functions
`currentDirectory()`
> Returns a string of the current working directory
> Used in: `PWD`
`get(fileName)`
> Returns a file stat object of file or directory
> Used in: `STAT`, `SIZE`, `RNFR`, `MDTM`
`list(path)`
> Returns array of file and directory stat objects
> Used in `LIST`, `STAT`
`chdir(path)`
> Returns new directory relative to cwd
> Used in `CWD`, `CDUP`
`mkdir(path)`
> Return a path to a newly created directory
> Used in `MKD`
`write(fileName, options)`
> Returns a writable stream
Options:
`append` if true, append to existing file
> Used in `STOR`, `APPE`
`read(fileName)`
> Returns a readable stream
> Used in `RETR`
`delete(path)`
> Delete a file or directory
> Used in `DELE`
`rename(from, to)`
> Rename a file or directory
> Used in `RNFR`, `RNTO`
`chmod(path)`
> Modify a file or directory's permissions
> Used in `SITE CHMOD`
`getUniqueName()`
> Return a unique file name to write to
> Used in `STOU`
<!--[RM_CONTRIBUTING]-->
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md).
<!--[]-->
<!--[RM_LICENSE]-->
## License
This software is licensed under the MIT Licence. See [LICENSE](LICENSE).
<!--[]-->

View File

@@ -1,43 +0,0 @@
'use strict';
module.exports = {
types: [
{value: 'feat', name: 'feat: A new feature'},
{value: 'fix', name: 'fix: A bug fix'},
{value: 'docs', name: 'docs: Documentation only changes'},
{value: 'style', name: 'style: Changes that do not affect the meaning of the code\n (white-space, formatting, missing semi-colons, etc)'},
{value: 'refactor', name: 'refactor: A code change that neither fixes a bug nor adds a feature'},
{value: 'perf', name: 'perf: A code change that improves performance'},
{value: 'test', name: 'test: Adding missing tests'},
{value: 'chore', name: 'chore: Changes to the build process or auxiliary tools\n and libraries such as documentation generation'},
{value: 'revert', name: 'revert: Revert to a commit'},
{value: 'WIP', name: 'WIP: Work in progress'}
],
scopes: [
{name: 'accounts'},
{name: 'admin'},
{name: 'exampleScope'},
{name: 'changeMe'}
],
// it needs to match the value for field type. Eg.: 'fix'
/*
scopeOverrides: {
fix: [
{name: 'merge'},
{name: 'style'},
{name: 'e2eTest'},
{name: 'unitTest'}
]
},
*/
allowCustomScopes: true,
allowBreakingChanges: ['feat', 'fix'],
// Appends the branch name to the footer of the commit. Useful for tracking commits after branches have been merged
appendBranchNameToCommitMessage: true
};

View File

@@ -1,34 +0,0 @@
// Use JS to support loading of threshold data from external file
var coverageConfig = {
instrumentation: {
root: 'src/'
},
check: require('./thresholds.json'),
reporting: {
print: 'both',
dir: 'reports/coverage/',
reports: [
'cobertura',
'html',
'lcovonly',
'html',
'json'
],
'report-config': {
cobertura: {
file: 'cobertura/coverage.xml'
},
json: {
file: 'json/coverage.json'
},
lcovonly: {
file: 'lcov/lcov.info'
},
text: {
file: null
}
}
}
};
module.exports = coverageConfig;

View File

@@ -1,4 +0,0 @@
test/**/*.spec.js
--reporter list
--no-timeouts
--ui bdd

View File

@@ -1,14 +0,0 @@
{
"global": {
"statements": 70,
"branches": 60,
"functions": 80,
"lines": 80
},
"each": {
"statements": 0,
"branches": 0,
"functions": 0,
"lines": 0
}
}

View File

@@ -1,60 +0,0 @@
# START_CONFIT_GENERATED_CONTENT
confit:
extends: &confit-extends
- plugin:node/recommended
plugins: &confit-plugins
- node
env: &confit-env
commonjs: true # For Webpack, CommonJS
node: true
mocha: true
es6: true
globals: &confit-globals {}
parser: &confit-parser espree
parserOptions: &confit-parserOptions
ecmaVersion: 6
sourceType: module
ecmaFeatures:
globalReturn: false
impliedStrict: true
jsx: false
# END_CONFIT_GENERATED_CONTENT
# Customise this section to meet your needs...
extends: *confit-extends
# Uncomment this next line if you need to add more items to the array, and remove the "*confit-extends" from the line above
# <<: *confit-extends
plugins: *confit-plugins
# Uncomment this next line if you need to add more items to the array, and remove the "*confit-plugins" from the line above
# <<: *confit-extends
env:
<<: *confit-env
globals:
<<: *confit-globals
parser: *confit-parser
parserOptions:
<<: *confit-parserOptions
rules:
max-len:
- warn
- 200 # Line Length
node/no-unpublished-require:
- 2
- allowModules:
- chai
- dotenv
- ftp
- sinon
- sinon-as-promised

View File

@@ -1,48 +0,0 @@
generator-confit:
app:
_version: f02196cc5cb7941ca46ec46d23bd6aef0dfcaca0
buildProfile: Latest
copyrightOwner: Tyler Stewart
license: MIT
projectType: node
publicRepository: true
repositoryType: GitHub
paths:
_version: 7f33e41600b34cd6867478d8f2b3d6b2bbd42508
config:
configDir: config/
input:
srcDir: src/
unitTestDir: test/
output:
prodDir: dist/
reportDir: reports/
buildJS:
_version: df428a706d926204228c5d9ebdbd7b49908926d9
framework: []
frameworkScripts: []
outputFormat: ES6
sourceFormat: ES6
entryPoint:
_version: de20402bf85c703080ef6daf21e35325a3b9d604
entryPoints:
main:
- src/index.js
testUnit:
_version: 4472a6d59b434226f463992d3c1914c77a6a115d
testDependencies: []
verify:
_version: 30ae86c5022840a01fc08833e238a82c683fa1c7
jsCodingStandard: eslint
documentation:
_version: b1658da3278b16d1982212f5e8bc05348af20e0b
generateDocs: false
release:
_version: 47f220593935b502abf17cb34a396f692e453c49
checkCodeCoverage: true
commitMessageFormat: Conventional
useSemantic: true
sampleApp:
_version: 00c0a2c6fc0ed17fcccce2d548d35896121e58ba
createSampleApp: false
zzfinish: {}

11
examples/basic.js Normal file
View File

@@ -0,0 +1,11 @@
/* eslint no-console: 0 */
const FtpSrv = require('../src');
const server = new FtpSrv();
server.listen(8880)
.then(() => {
console.log('listening');
})
.catch(err => {
console.log('err', err)
})

BIN
logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

19
logo/generate.js Normal file
View File

@@ -0,0 +1,19 @@
const puppeteer = require('puppeteer');
(async function () {
const logoPath = `file://${process.cwd()}/logo/logo.html`;
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(logoPath);
await page.setViewport({
width: 600,
height: 250,
deviceScaleFactor: 2
});
await page.screenshot({
path: 'logo.png',
omitBackground: true
});
await browser.close();
})();

68
logo/logo.html Normal file
View File

@@ -0,0 +1,68 @@
<!doctype html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Overpass+Mono:700" rel="stylesheet">
<style>
body {
padding: 0;
margin: 0;
display: flex;
height: 100vh;
flex-direction: row;
justify-content: center;
}
div {
display: flex;
flex-direction: column;
justify-content: center;
width: 100vw;
}
h1 {
display: flex;
flex-direction: column;
align-self: center;
text-align: center;
margin: 0;
padding: 0px;
width: 75vw;
font-size: 68px;
font-family: 'Overpass Mono', monospace;
font-weight: bold;
line-height: 0.8em;
letter-spacing: -3px;
color: #fff;
-webkit-font-smoothing: antialiased;
-webkit-text-stroke: 1px #0063B1;
text-shadow:
3px 3px 0 #0063B1,
-1px -1px 0 #0063B1,
1px -1px 0 #0063B1,
-1px 1px 0 #0063B1,
1px 1px 0 #0063B1;
}
h1 > span {
display: block;
padding: 0;
margin: 0;
padding-top: 6px;
}
h1 > hr {
padding: 0;
margin: 0;
margin-top: 22px;
border: 1px solid #0063B1;
border-radius: 50%;
}
</style>
</head>
<body>
<div>
<h1>
<span>ftp</span>
<hr />
<span>srv</span>
</h1>
</div>
</body>
</html>

View File

@@ -1,6 +1,6 @@
{
"name": "ftp-srv",
"version": "0.0.0",
"version": "0.0.0-development",
"description": "Modern, extensible FTP Server",
"keywords": [
"ftp",
@@ -8,74 +8,29 @@
"ftp-srv",
"ftp-svr",
"ftpd",
"ftpserver",
"server"
],
"license": "MIT",
"main": "src/index.js",
"repository": {
"type": "git",
"url": "https://github.com/stewarttylerr/ftp-srv"
"url": "https://github.com/trs/ftp-srv"
},
"scripts": {
"pre-release": "npm-run-all verify test:coverage build ",
"build": "cross-env NODE_ENV=production npm run clean:prod",
"clean:prod": "rimraf dist/",
"commitmsg": "cz-customizable-ghooks",
"dev": "cross-env NODE_ENV=development npm run verify:watch",
"prepush": "npm-run-all verify test:coverage --silent",
"semantic-release": "semantic-release pre && npm publish && semantic-release post",
"start": "npm run dev",
"test": "npm run test:unit",
"test:check-coverage": "cross-env NODE_ENV=test istanbul check-coverage reports/coverage/coverage.json --config config/testUnit/istanbul.js",
"test:coverage": "npm-run-all test:unit:once test:check-coverage --silent",
"test:unit": "chokidar 'src/**/*.js' 'test/**/*.js' -c 'npm run test:unit:once' --initial --silent",
"test:unit:once": "cross-env NODE_ENV=test istanbul cover --config config/testUnit/istanbul.js _mocha -- --opts config/testUnit/mocha.opts",
"upload-coverage": "cat reports/coverage/lcov/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
"verify": "npm run verify:js --silent",
"verify:js": "eslint -c config/verify/.eslintrc \"src/**/*.js\" \"test/**/*.js\" \"config/**/*.js\" && echo ✅ verify:js success",
"verify:js:fix": "eslint --fix -c config/verify/.eslintrc \"src/**/*.js\" \"test/**/*.js\" \"config/**/*.js\" && echo ✅ verify:js:fix success",
"verify:js:watch": "chokidar 'src/**/*.js' 'test/**/*.js' 'config/**/*.js' -c 'npm run verify:js:fix' --initial --silent",
"verify:watch": "npm run verify:js:watch --silent"
},
"config": {
"commitizen": {
"path": "node_modules/cz-customizable"
},
"cz-customizable": {
"config": "config/release/commitMessageConfig.js"
}
"test": "jest ./src/**/*.test.js --verbose",
"lint": "eslint -c .config/.eslintrc.json \"src/**/*.js\" \"logo/**/*.js\" \"examples/**/*.js\""
},
"dependencies": {
"bunyan": "^1.8.5",
"date-fns": "^1.28.0",
"lodash": "^4.17.4",
"minimist-string": "^1.0.2",
"uuid": "^3.0.1",
"when": "^3.7.8"
"bee-queue": "^1.2.2",
"signale": "^1.1.0",
"z": "^1.0.8"
},
"devDependencies": {
"chai": "^3.5.0",
"chokidar-cli": "1.2.0",
"coveralls": "2.11.15",
"cross-env": "3.1.4",
"cz-customizable": "4.0.0",
"cz-customizable-ghooks": "1.5.0",
"dotenv": "^4.0.0",
"eslint": "3.14.1",
"eslint-config-google": "0.7.1",
"eslint-plugin-node": "3.0.5",
"ftp": "^0.3.10",
"husky": "0.13.1",
"istanbul": "0.4.5",
"mocha": "3.2.0",
"npm-run-all": "4.0.1",
"rimraf": "2.5.4",
"semantic-release": "^6.3.2",
"sinon": "^1.17.7",
"sinon-as-promised": "^4.0.2"
"eslint": "^4.18.2",
"jest": "^22.4.2",
"semantic-release": "^15.0.2"
},
"engines": {
"node": ">=6.x",
"npm": ">=3.9.5"
"node": ">=8.x"
}
}

84
src-old/Client.js Normal file
View File

@@ -0,0 +1,84 @@
const net = require('net');
const Queue = require('./Queue');
const {getCommandHandler} = require('./commands');
class Client extends net.Socket {
constructor(id, socket) {
super();
socket && Object.assign(this, socket);
this.id = id;
this.commandQueue = new Queue({
[Queue.QUEUE_TYPES.IN]: () => {},
[Queue.QUEUE_TYPES.OUT]: () => {}
});
this.dataQueue = new Queue();
this.resetSession();
super.on('data', data => this._onData(data));
}
resetSession() {
this.session = {
encoding: 'utf8',
transferType: 'binary'
};
}
setSession(key, value) {
this.session[key] = value;
}
getSession(key) {
return this.session[key];
}
send(message) {
// this.sendQueue.enqueue(message);
}
get closed() {
return this.closing || super.destroyed;
}
close() {
if (super.destroyed) return;
this.closing = true;
super.destroy();
}
_onData(data) {
if (this.closed) return;
const commands = data
.toString(this.getSession('encoding'))
.split('\r\n')
.map(command => command.trim())
.filter(command => !!command);
this.commandQueue.enqueue(Queue.QUEUE_TYPES.IN, ...commands);
}
// async _processCommand(command) {
// this.emit('command', {command});
// const commandHandler = getCommandHandler(this, command);
// if (typeof commandHandler === 'string') {
// return this.send(commandHandler);
// }
// await commandHandler(this, command);
// }
// async _processSend(message) {
// await new Promise((resolve, reject) => {
// super.write(`${message}\r\n`, err => {
// if (err) reject(err);
// else resolve();
// });
// });
// }
}
module.exports = Client;

View File

@@ -0,0 +1,33 @@
class ConnectionManager {
constructor() {
this._connections = {};
}
add(id, client) {
this._connections[id] = client;
return true;
}
remove(id) {
if (!this._connections.hasOwnProperty(id)) return false;
delete this._connections[id];
return true;
}
invoke(method, ...args) {
const invokeResults = Object.values(this._connections).map(connection => {
if (typeof connection[method] !== 'function') return undefined;
return connection[method](...args);
});
return Promise.all(invokeResults);
}
iterate() {
console.log('iterate', iterate)
const connections = Object.entires(this._connections);
console.log('connections', connections)
return connections
}
}
module.exports = ConnectionManager;

40
src-old/Queue.js Normal file
View File

@@ -0,0 +1,40 @@
const QUEUE_TYPES = {
IN: Symbol('in'),
OUT: Symbol('out')
}
class Queue {
constructor(handlers = {}) {
this.items = {};
this.handlers = {};
for (const type of Object.values(QUEUE_TYPES)) {
this.items[type] = [];
this.handlers[type] = handlers[type];
}
}
enqueue(type, ...items) {
if (!this.items[type]) return;
items = items.map(item => {
if (!Array.isArray(item)) return [item];
return item;
});
this.items[type].push(...items);
}
tryDequeue(type) {
if (!this.items[type]) return;
if (!this.items[type].length) return;
if (!this.handlers[type]) return;
const item = this.items[type].shift();
const method = this.handlers[type];
return method(...item);
}
}
Queue.QUEUE_TYPES = QUEUE_TYPES;
module.exports = Queue;

0
src-old/Queue.test.js Normal file
View File

75
src-old/Server.js Normal file
View File

@@ -0,0 +1,75 @@
const net = require('net');
const path = require('path');
const {fork} = require('child_process');
const Queue = require('bee-queue');
const Client = require('./Client');
const ConnectionManager = require('./ConnectionManager');
const {idGenerator} = require('./utils/idGenerator');
const message = require('./const/message');
class Server extends net.Server {
constructor() {
super({pauseOnConnect: true});
this.connectionManager = new ConnectionManager();
this.clientIDGenerator = idGenerator(1);
this.receiveQueue = new Queue('receive');
this.sendQueue = new Queue('send');
this.on('connection', socket => this._onConnection(socket));
}
async send(client, data) {
const job = await this.sendQueue.createJob({
id: client.id,
data
})
.timeout(30000)
.save();
}
async close() {
await this.connectionManager.invoke('close');
await new Promise(resolve => super.close(() => resolve()));
return this;
}
async listen(port) {
// const processor = path.resolve(__dirname, './commands/processor.js');
// this.commandProcess = fork(processor, {
// stdio: 'pipe'
// });
// this.commandProcess.on('message', (message) => {
// console.log('got', message)
// });
// this.commandProcess.on('error', (err) => {
// console.log('error', err)
// });
// this.commandProcess.once('exit', (code) => {
// console.log('exit', code)
// });
// this.commandProcess.once('close', (code) => {
// console.log('close', code)
// });
this.commandProcess.send('server', this);
await new Promise(resolve => super.listen(port, () => resolve()));
return this;
}
_onConnection(socket) {
const id = this.clientIDGenerator.next().value;
const client = new Client(id, socket);
client.once('close', () => this.connectionManager.remove(client.id));
this.connectionManager.add(id, client);
this.emit('client', client);
// client.send(message.GREETING)
// .then(() => client.resume())
// .catch(() => client.close());
}
}
module.exports = Server;

41
src-old/Server.test.js Normal file
View File

@@ -0,0 +1,41 @@
const net = require('net');
const Server = require('./Server');
const {getUsablePort} = require('./utils/getUsablePort');
let PORT;
beforeEach(async () => {
PORT = await getUsablePort(8000);
});
test('expects server to start listening', done => {
const server = new Server();
server.once('listening', () => server.close());
server.once('close', () => done());
server.listen(PORT);
});
test('expects server to accept a client', done => {
const server = new Server();
server.once('client', client => {
expect(client.id).toBeGreaterThan(0);
server.close();
});
server.once('close', () => done());
server.listen(PORT);
net.createConnection(PORT);
});
test('expects server to send greeting on client connection', done => {
const server = new Server();
server.once('client', client => {
expect(client.id).toBeGreaterThan(0);
});
server.once('close', () => done());
server.listen(PORT);
const connection = net.createConnection(PORT);
connection.once('data', () => server.close());
});

39
src-old/commands/index.js Normal file
View File

@@ -0,0 +1,39 @@
const registry = require('./registry');
const message = require('../const/message');
function parseCommand(rawCommand) {
const strippedRawCommand = rawCommand.replace(/"/g, '');
const [directive, ...args] = strippedRawCommand.split(' ');
const params = args.reduce(({arg, flags}, param) => {
if (/^-{1,2}[a-zA-Z0-9_]+/.test(param)) flags.push(param);
else arg.push(param);
return {arg, flags};
}, {arg: [], flags: []});
const command = {
directive: String(directive).trim().toLocaleUpperCase(),
arg: params.arg.length ? params.arg.join(' ') : null,
flags: params.flags,
// raw: rawCommand
};
return command;
}
async function getCommandHandler(client, command) {
command = parseCommand(command);
if (!registry.hasOwnProperty(command.directive)) return message.UNSUPPORTED_COMMAND;
const commandRegister = registry[command.directive];
const commandFlags = commandRegister.flags ? commandRegister.flags : {};
if (!commandFlags.no_auth && !client.authenticated) {
return message.COMMAND_REQUIRES_AUTHENTICATION;
}
return commandRegister.handle;
}
module.exports = {
getCommandHandler,
parseCommand
};

23
src-old/commands/processor.js Executable file
View File

@@ -0,0 +1,23 @@
process.once('message', (initMsg, server) => {
if (initMsg !== 'server') {
return process.exit(-1);
}
process.on('message', (msg, ...args) => {
});
processQueues(server);
});
async function processQueues(server) {
process.send('processQueues');
const iterable = server.connectionManager.iterate();
process.send('interable');
for (const [id, client] of iterable) {
process.send('process', id);
}
process.send('/processQueues');
return processQueues(server);
}

View File

@@ -0,0 +1,4 @@
module.exports = {
USER: require('./user'),
PASS: require('./pass')
};

View File

@@ -0,0 +1,20 @@
const message = require('../../const/message');
module.exports = {
directive: 'PASS',
handler: async function (client, command) {
if (!client.getSession('username')) return client.send(message.BAD_COMMAND_SEQUENCE);
if (client.authenticated) return client.send(message.SUPERFLUOUS_COMMAND);
if (!command.arg) return client.send(message.SYNTAX_ERROR_ARGS);
// TODO: 332 : require account name (ACCT)
// TODO: do login
await client.send(message.AUTHENTICATED);
},
args: ['<password>'],
description: 'Authenticate client session',
flags: {
no_auth: true
}
};

View File

@@ -0,0 +1,21 @@
const message = require('../../const/message');
module.exports = {
directive: 'USER',
handler: async function (client, command) {
if (client.getSession('username')) return client.send(message.USERNAME_SET_ALREADY);
if (client.authenticated) return client.send(message.USER_AUTHENTICATED);
if (!client.arg) return client.send(message.SYNTAX_ERROR_ARGS);
this.setSession('username', command.arg);
// TODO: allow anonymous logins
await this.reply(message.AWAITING_PASSWORD);
},
args: ['<username>'],
description: 'Set client session username',
flags: {
no_auth: true
}
};

12
src-old/const/message.js Normal file
View File

@@ -0,0 +1,12 @@
module.exports = {
SUPERFLUOUS_COMMAND: '202 Superfluous command',
GREETING: '220 Greetings',
AUTHENTICATED: '230 User authenticated successfully',
AWAITING_PASSWORD: '331 Username okay, awaiting password',
SYNTAX_ERROR_ARGS: '501 Syntax error in arguments',
UNSUPPORTED_COMMAND: '502 Command not supported',
BAD_COMMAND_SEQUENCE: '503 Bad sequence of commands',
USERNAME_SET_ALREADY: '530 Username already set',
COMMAND_REQUIRES_AUTHENTICATION: '530 Username already set',
AUTHENTICATED_FAILED: '530 Authentication failed',
};

4
src-old/index.js Normal file
View File

@@ -0,0 +1,4 @@
const Server = require('./Server');
module.exports = Server;
module.exports.FtpSrv = Server;

View File

@@ -0,0 +1,39 @@
const net = require('net');
const PORT_MAX = 65535;
function getUsablePort(portStart = 21, portStop = PORT_MAX) {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.maxConnections = 0;
const cleanUpServer = () => {
server.removeAllListeners();
server.unref();
};
let currentPort = portStart;
server.on('error', err => {
if (currentPort < PORT_MAX && currentPort < portStop) {
server.listen(++currentPort);
} else {
server.close(() => {
cleanUpServer();
reject(err);
});
}
});
server.on('listening', () => {
const {port} = server.address();
server.close(() => {
cleanUpServer();
resolve(port);
})
});
server.listen(currentPort);
});
}
module.exports = {
getUsablePort
};

View File

@@ -0,0 +1,6 @@
const {getUsablePort} = require('./getUsablePort');
test('expects an available port to be found', async () => {
const port = await getUsablePort();
expect(port).toBeGreaterThan(0);
});

View File

@@ -0,0 +1,6 @@
function* idGenerator(start) {
let i = start;
while (true) yield i++;
}
module.exports = {idGenerator};

View File

@@ -0,0 +1,8 @@
const {idGenerator} = require('./idGenerator');
test('expects ids to be generated', () => {
const id = idGenerator(1);
expect(id.next().value).toBe(1);
expect(id.next().value).toBe(2);
expect(id.next().value).toBe(3);
});

16
src/client/index.js Normal file
View File

@@ -0,0 +1,16 @@
const net = require('net');
class Client extends net.Socket {
constructor() {
super();
}
send() {
}
close() {
}
}
module.exports = Client;

View File

@@ -1,47 +0,0 @@
const _ = require('lodash');
const when = require('when');
const REGISTRY = require('./registry');
class FtpCommands {
constructor(connection) {
this.connection = connection;
this.previousCommand = {};
this.blacklist = _.get(this.connection, 'server.options.blacklist', []).map(cmd => _.upperCase(cmd));
this.whitelist = _.get(this.connection, 'server.options.whitelist', []).map(cmd => _.upperCase(cmd));
}
handle(command) {
const log = this.connection.log.child({command});
log.trace('Handle command');
if (!REGISTRY.hasOwnProperty(command.directive)) {
return this.connection.reply(402, 'Command not allowed');
}
if (_.includes(this.blacklist, command.directive)) {
return this.connection.reply(502, 'Command blacklisted');
}
if (this.whitelist.length > 0 && !_.includes(this.whitelist, command.directive)) {
return this.connection.reply(502, 'Command not whitelisted');
}
const commandRegister = REGISTRY[command.directive];
const commandFlags = _.get(commandRegister, 'flags', {});
if (!commandFlags.no_auth && !this.connection.authenticated) {
return this.connection.reply(530, 'Command requires authentication');
}
if (!commandRegister.handler) {
return this.connection.reply(502, 'Handler not set on command');
}
const handler = commandRegister.handler.bind(this.connection);
return when.try(handler, { log, command, previous_command: this.previousCommand })
.finally(() => {
this.previousCommand = _.clone(command);
});
}
}
module.exports = FtpCommands;

View File

@@ -1,14 +0,0 @@
module.exports = {
directive: 'ABOR',
handler: function () {
return this.connector.waitForConnection()
.then(socket => {
return this.reply(426, {socket})
.then(() => this.connector.end());
})
.catch(() => {})
.then(() => this.reply(226));
},
syntax: '{{cmd}}',
description: 'Abort an active file transfer'
};

View File

@@ -1,11 +0,0 @@
module.exports = {
directive: 'ALLO',
handler: function () {
return this.reply(202);
},
syntax: '{{cmd}}',
description: 'Allocate sufficient disk space to receive a file',
flags: {
obsolete: true
}
};

View File

@@ -1,10 +0,0 @@
const stor = require('./stor').handler;
module.exports = {
directive: 'APPE',
handler: function (args) {
return stor.call(this, args);
},
syntax: '{{cmd}} [path]',
description: 'Append to a file'
}

View File

@@ -1,27 +0,0 @@
const _ = require('lodash');
module.exports = {
directive: 'AUTH',
handler: function ({command} = {}) {
const method = _.upperCase(command._[1]);
switch (method) {
case 'TLS': return handleTLS.call(this);
case 'SSL': return handleSSL.call(this);
default: return this.reply(504);
}
},
syntax: '{{cmd}} [type]',
description: 'Set authentication mechanism',
flags: {
no_auth: true
}
}
function handleTLS() {
return this.reply(504);
}
function handleSSL() {
return this.reply(504);
}

View File

@@ -1,11 +0,0 @@
const cwd = require('./cwd').handler;
module.exports = {
directive: ['CDUP', 'XCUP'],
handler: function(args) {
args.command._ = [args.command._[0], '..'];
return cwd.call(this, args);
},
syntax: '{{cmd}}',
description: 'Change to Parent Directory'
}

View File

@@ -1,22 +0,0 @@
const when = require('when');
const escapePath = require('../../helpers/escape-path');
module.exports = {
directive: ['CWD', 'XCWD'],
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.chdir) return this.reply(402, 'Not supported by file system');
return when(this.fs.chdir(command._[1]))
.then(cwd => {
const path = cwd ? `"${escapePath(cwd)}"` : undefined;
return this.reply(250, path);
})
.catch(err => {
log.error(err);
return this.reply(550, err.message);
});
},
syntax: '{{cmd}}[path]',
description: 'Change working directory'
}

View File

@@ -1,20 +0,0 @@
const when = require('when');
module.exports = {
directive: 'DELE',
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.delete) return this.reply(402, 'Not supported by file system');
return when(this.fs.delete(command._[1]))
.then(() => {
return this.reply(250);
})
.catch(err => {
log.error(err);
return this.reply(550);
});
},
syntax: '{{cmd}} [path]',
description: 'Delete file'
}

View File

@@ -1,21 +0,0 @@
const _ = require('lodash');
module.exports = {
directive: 'FEAT',
handler: function () {
const registry = require('../registry');
const features = Object.keys(registry)
.reduce((feats, cmd) => {
const feat = _.get(registry[cmd], 'flags.feat', null);
if (feat) return _.concat(feats, feat);
return feats;
}, [])
.map(feat => ` ${feat}`);
return this.reply(211, 'Extensions supported', ...features, 'END');
},
syntax: '{{cmd}}',
description: 'Get the feature list implemented by the server',
flags: {
no_auth: true
}
}

View File

@@ -1,24 +0,0 @@
const _ = require('lodash');
module.exports = {
directive: 'HELP',
handler: function ({command} = {}) {
const registry = require('../registry');
const directive = _.upperCase(command._[1]);
if (directive) {
if (!registry.hasOwnProperty(directive)) return this.reply(502, `Unknown command ${directive}.`);
const {syntax, description} = registry[directive];
const reply = _.concat([syntax.replace('{{cmd}}', directive), description]);
return this.reply(214, ...reply);
} else {
const supportedCommands = _.chunk(Object.keys(registry), 5).map(chunk => chunk.join('\t'));
return this.reply(211, 'Supported commands:', ...supportedCommands, 'Use "HELP [command]" for syntax help.');
}
},
syntax: '{{cmd}} [command(optional)]',
description: 'Returns usage documentation on a command if specified, else a general help document is returned',
flags: {
no_auth: true
}
}

View File

@@ -1,60 +0,0 @@
const _ = require('lodash');
const when = require('when');
const getFileStat = require('../../helpers/file-stat');
// http://cr.yp.to/ftp/list.html
// http://cr.yp.to/ftp/list/eplf.html
module.exports = {
directive: 'LIST',
handler: function ({log, command, previous_command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.list) return this.reply(402, 'Not supported by file system');
const simple = command.directive === 'NLST';
let dataSocket;
const directory = command._[1] || '.';
return this.connector.waitForConnection()
.then(socket => {
this.commandSocket.pause();
dataSocket = socket;
})
.then(() => when(this.fs.list(directory)))
.then(files => {
const getFileMessage = (file) => {
if (simple) return file.name;
return getFileStat(file, _.get(this, 'server.options.file_format', 'ls'));
};
const fileList = files.map(file => {
const message = getFileMessage(file);
return {
raw: true,
message,
socket: dataSocket
};
})
return this.reply(150)
.then(() => {
if (fileList.length) return this.reply({}, ...fileList);
});
})
.then(() => {
return this.reply(226, 'Transfer OK');
})
.catch(when.TimeoutError, err => {
log.error(err);
return this.reply(425, 'No connection established');
})
.catch(err => {
log.error(err);
return this.reply(err.code || 451, err.message || 'No directory');
})
.finally(() => {
this.connector.end();
this.commandSocket.resume();
});
},
syntax: '{{cmd}} [path(optional)]',
description: 'Returns information of a file or directory if specified, else information of the current working directory is returned'
}

View File

@@ -1,25 +0,0 @@
const when = require('when');
const format = require('date-fns/format');
module.exports = {
directive: 'MDTM',
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.get) return this.reply(402, 'Not supported by file system');
return when(this.fs.get(command._[1]))
.then(fileStat => {
const modificationTime = format(fileStat.mtime, 'YYYYMMDDHHmmss.SSS');
return this.reply(213, modificationTime)
})
.catch(err => {
log.error(err);
return this.reply(550);
});
},
syntax: '{{cmd}} [path]',
description: 'Return the last-modified time of a specified file',
flags: {
feat: 'MDTM'
}
}

View File

@@ -1,22 +0,0 @@
const when = require('when');
const escapePath = require('../../helpers/escape-path');
module.exports = {
directive: ['MKD', 'XMKD'],
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.mkdir) return this.reply(402, 'Not supported by file system');
return when(this.fs.mkdir(command._[1]))
.then(dir => {
const path = dir ? `"${escapePath(dir)}"` : undefined;
return this.reply(257, path);
})
.catch(err => {
log.error(err);
return this.reply(550);
});
},
syntax: '{{cmd}}[path]',
description: 'Make directory'
}

View File

@@ -1,11 +0,0 @@
module.exports = {
directive: 'MODE',
handler: function ({command} = {}) {
return this.reply(/^S$/i.test(command._[1]) ? 200 : 504);
},
syntax: '{{cmd}} [mode]',
description: 'Sets the transfer mode (Stream, Block, or Compressed)',
flags: {
obsolete: true
}
}

View File

@@ -1,10 +0,0 @@
const list = require('./list').handler;
module.exports = {
directive: 'NLST',
handler: function (args) {
return list.call(this, args);
},
syntax: '{{cmd}} [path(optional)]',
description: 'Returns a list of file names in a specified directory'
}

View File

@@ -1,11 +0,0 @@
module.exports = {
directive: 'NOOP',
handler: function () {
return this.reply(200);
},
syntax: '{{cmd}}',
description: 'No operation',
flags: {
no_auth: true
}
}

View File

@@ -1,8 +0,0 @@
module.exports = {
directive: 'OPTS',
handler: function () {
return this.reply(501);
},
syntax: '{{cmd}}',
description: 'Select options for a feature'
}

View File

@@ -1,27 +0,0 @@
const _ = require('lodash');
module.exports = {
directive: 'PASS',
handler: function ({log, command} = {}) {
if (!this.username) return this.reply(503);
if (this.username && this.authenticated &&
_.get(this, 'server.options.anonymous') === true) return this.reply(230);
// 332 : require account name (ACCT)
const password = command._[1];
return this.login(this.username, password)
.then(() => {
return this.reply(230);
})
.catch(err => {
log.error(err);
return this.reply(530, err.message || 'Authentication failed');
});
},
syntax: '{{cmd}} [password]',
description: 'Authentication password',
flags: {
no_auth: true
}
}

View File

@@ -1,20 +0,0 @@
const PassiveConnector = require('../../connector/passive');
module.exports = {
directive: 'PASV',
handler: function ({command} = {}) {
this.connector = new PassiveConnector(this);
return this.connector.setupServer()
.then(server => {
const address = this.server.url.hostname;
const {port} = server.address();
const host = address.replace(/\./g, ',');
const portByte1 = port / 256 | 0;
const portByte2 = port % 256;
return this.reply(227, `PASV OK (${host},${portByte1},${portByte2})`);
});
},
syntax: '{{cmd}}',
description: 'Initiate passive mode'
}

View File

@@ -1,21 +0,0 @@
const ActiveConnector = require('../../connector/active');
module.exports = {
directive: 'PORT',
handler: function ({command} = {}) {
this.connector = new ActiveConnector(this);
const rawConnection = command._[1].split(',');
if (rawConnection.length !== 6) return this.reply(425);
const ip = rawConnection.slice(0, 4).join('.');
const portBytes = rawConnection.slice(4).map(p => parseInt(p));
const port = portBytes[0] * 256 + portBytes[1];
return this.connector.setupConnection(ip, port)
.then(socket => {
return this.reply(200);
})
},
syntax: '{{cmd}} [x,x,x,x,y,y]',
description: 'Specifies an address and port to which the server should connect'
}

View File

@@ -1,22 +0,0 @@
const when = require('when');
const escapePath = require('../../helpers/escape-path');
module.exports = {
directive: ['PWD', 'XPWD'],
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.currentDirectory) return this.reply(402, 'Not supported by file system');
return when(this.fs.currentDirectory())
.then(cwd => {
const path = cwd ? `"${escapePath(cwd)}"` : undefined;
return this.reply(257, path);
})
.catch(err => {
log.error(err);
return this.reply(550, err.message);
})
},
syntax: '{{cmd}}',
description: 'Print current working directory'
}

View File

@@ -1,11 +0,0 @@
module.exports = {
directive: 'QUIT',
handler: function () {
return this.close(221);
},
syntax: '{{cmd}}',
description: 'Disconnect',
flags: {
no_auth: true
}
}

View File

@@ -1,41 +0,0 @@
const when = require('when');
module.exports = {
directive: 'RETR',
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.read) return this.reply(402, 'Not supported by file system');
let dataSocket;
return this.connector.waitForConnection()
.then(socket => {
this.commandSocket.pause();
dataSocket = socket;
})
.then(() => when(this.fs.read(command._[1])))
.then(stream => {
return when.promise((resolve, reject) => {
dataSocket.on('error', err => stream.emit('error', err));
stream.on('data', data => dataSocket.write(data, this.encoding));
stream.on('end', () => resolve(this.reply(226)));
stream.on('error', err => reject(err));
this.reply(150).then(() => dataSocket.resume());
});
})
.catch(when.TimeoutError, err => {
log.error(err);
return this.reply(425, 'No connection established');
})
.catch(err => {
log.error(err);
return this.reply(551);
})
.finally(() => {
this.connector.end();
this.commandSocket.resume();
})
},
syntax: '{{cmd}} [path]',
description: 'Retrieve a copy of the file'
}

View File

@@ -1,10 +0,0 @@
const dele = require('./dele').handler;
module.exports = {
directive: ['RMD', 'XRMD'],
handler: function (args) {
return dele.call(this, args);
},
syntax: '{{cmd}} [path]',
description: 'Remove a directory'
}

View File

@@ -1,22 +0,0 @@
const when = require('when');
module.exports = {
directive: 'RNFR',
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.get) return this.reply(402, 'Not supported by file system');
const fileName = command._[1];
return when(this.fs.get(fileName))
.then(() => {
this.renameFrom = fileName;
return this.reply(350);
})
.catch(err => {
log.error(err);
return this.reply(550);
});
},
syntax: '{{cmd}} [name]',
description: 'Rename from'
};

View File

@@ -1,28 +0,0 @@
const when = require('when');
module.exports = {
directive: 'RNTO',
handler: function ({log, command} = {}) {
if (!this.renameFrom) return this.reply(503);
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.rename) return this.reply(402, 'Not supported by file system');
const from = this.renameFrom;
const to = command._[1];
return when(this.fs.rename(from, to))
.then(() => {
return this.reply(250);
})
.catch(err => {
log.error(err);
return this.reply(550);
})
.finally(() => {
delete this.renameFrom;
})
},
syntax: '{{cmd}} [name]',
description: 'Rename to'
}

View File

@@ -1,14 +0,0 @@
module.exports = function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.chmod) return this.reply(402, 'Not supported by file system');
const [, mode, fileName] = command._;
return this.fs.chmod(fileName, parseInt(mode, 8))
.then(() => {
return this.reply(200);
})
.catch(err => {
log.error(err);
return this.reply(500);
})
};

View File

@@ -1,23 +0,0 @@
const _ = require('lodash');
const when = require('when');
module.exports = {
directive: 'SITE',
handler: function ({log, command} = {}) {
const registry = require('./registry');
let [, subverb, ...subparameters] = command._;
subverb = _.upperCase(subverb);
const subLog = log.child({subverb});
if (!registry.hasOwnProperty(subverb)) return this.reply(502);
const subCommand = {
_: [subverb, ...subparameters],
directive: subverb
}
const handler = registry[subverb].handler.bind(this);
return when.try(handler, { log: subLog, command: subCommand });
},
syntax: '{{cmd}} [subVerb] [subParams]',
description: 'Sends site specific commands to remote server'
}

View File

@@ -1,5 +0,0 @@
module.exports = {
CHMOD: {
handler: require('./chmod')
}
};

View File

@@ -1,23 +0,0 @@
const when = require('when');
module.exports = {
directive: 'SIZE',
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.get) return this.reply(402, 'Not supported by file system');
return when(this.fs.get(command._[1]))
.then(fileStat => {
return this.reply(213, {message: fileStat.size});
})
.catch(err => {
log.error(err);
return this.reply(550);
});
},
syntax: '{{cmd}} [path]',
description: 'Return the size of a file',
flags: {
feat: 'SIZE'
}
}

View File

@@ -1,42 +0,0 @@
const _ = require('lodash');
const when = require('when');
const getFileStat = require('../../helpers/file-stat');
module.exports = {
directive: 'STAT',
handler: function (args = {}) {
const {log, command} = args;
const path = command._[1];
if (path) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.get) return this.reply(402, 'Not supported by file system');
return when(this.fs.get(path))
.then(stat => {
if (stat.isDirectory()) {
return when(this.fs.list(path))
.then(files => {
const fileList = files.map(file => {
const message = getFileStat(file, _.get(this, 'server.options.file_format', 'ls'));
return {
raw: true,
message
};
})
return this.reply(213, 'Status begin', ...fileList, 'Status end');
})
} else {
return this.reply(212, getFileStat(stat, _.get(this, 'server.options.file_format', 'ls')))
}
})
.catch(err => {
log.error(err);
return this.reply(450);
})
} else {
return this.reply(211, 'Status OK');
}
},
syntax: '{{cmd}} [path(optional)]',
description: 'Returns the current status'
}

View File

@@ -1,44 +0,0 @@
const when = require('when');
module.exports = {
directive: 'STOR',
handler: function ({log, command} = {}) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.write) return this.reply(402, 'Not supported by file system');
const append = command.directive === 'APPE';
const fileName = command._[1];
let dataSocket;
return this.connector.waitForConnection()
.then(socket => {
this.commandSocket.pause();
dataSocket = socket;
})
.then(() => when(this.fs.write(fileName, {append})))
.then(stream => {
return when.promise((resolve, reject) => {
stream.on('error', err => dataSocket.emit('error', err));
dataSocket.on('end', () => stream.end(() => resolve(this.reply(226, fileName))));
dataSocket.on('error', err => reject(err));
dataSocket.on('data', data => stream.write(data, this.encoding));
this.reply(150).then(() => dataSocket.resume());
});
})
.catch(when.TimeoutError, err => {
log.error(err);
return this.reply(425, 'No connection established');
})
.catch(err => {
log.error(err);
return this.reply(553);
})
.finally(() => {
this.connector.end();
this.commandSocket.resume();
});
},
syntax: '{{cmd}} [path]',
description: 'Store data as a file at the server site'
}

View File

@@ -1,20 +0,0 @@
const stor = require('./stor').handler;
module.exports = {
directive: 'STOU',
handler: function (args) {
if (!this.fs) return this.reply(550, 'File system not instantiated');
if (!this.fs.get || !this.fs.getUniqueName) return this.reply(402, 'Not supported by file system');
const fileName = args.command._[1];
return this.fs.get(fileName)
.catch(() => fileName) // does not exist, name is unique
.then(() => this.fs.getUniqueName()) // exists, must create new unique name
.then(name => {
args.command._[1] = name;
return stor.call(this, args);
});
},
syntax: '{{cmd}}',
description: 'Store file uniquely'
};

View File

@@ -1,11 +0,0 @@
module.exports = {
directive: 'STRU',
handler: function ({command} = {}) {
return this.reply(/^F$/i.test(command._[1]) ? 200 : 504);
},
syntax: '{{cmd}} [structure]',
description: 'Set file transfer structure',
flags: {
obsolete: true
}
}

View File

@@ -1,11 +0,0 @@
module.exports = {
directive: 'SYST',
handler: function () {
return this.reply(215);
},
syntax: '{{cmd}}',
description: 'Return system type',
flags: {
no_auth: true
}
}

View File

@@ -1,20 +0,0 @@
const _ = require('lodash');
module.exports = {
directive: 'TYPE',
handler: function ({command} = {}) {
const encoding = _.upperCase(command._[1]);
switch (encoding) {
case 'A':
this.encoding = 'utf-8';
case 'I':
case 'L':
this.encoding = 'binary';
return this.reply(200);
default:
return this.reply(501);
}
},
syntax: '{{cmd}} [mode]',
description: 'Set the transfer mode, binary (I) or utf-8 (A)'
}

View File

@@ -1,23 +0,0 @@
module.exports = {
directive: 'USER',
handler: function ({log, command} = {}) {
if (this.username) return this.reply(530, 'Username already set');
this.username = command._[1];
if (this.server.options.anonymous === true) {
return this.login(this.username, '@anonymous')
.then(() => {
return this.reply(230);
})
.catch(err => {
log.error(err);
return this.reply(530, err || 'Authentication failed');
});
}
return this.reply(331);
},
syntax: '{{cmd}} [username]',
description: 'Authentication username',
flags: {
no_auth: true
}
}

View File

@@ -1,43 +0,0 @@
const commands = [
require('./registration/abor'),
require('./registration/allo'),
require('./registration/appe'),
require('./registration/auth'),
require('./registration/cdup'),
require('./registration/cwd'),
require('./registration/dele'),
require('./registration/feat'),
require('./registration/help'),
require('./registration/list'),
require('./registration/mdtm'),
require('./registration/mkd'),
require('./registration/mode'),
require('./registration/nlst'),
require('./registration/noop'),
require('./registration/opts'),
require('./registration/pass'),
require('./registration/pasv'),
require('./registration/port'),
require('./registration/pwd'),
require('./registration/retr'),
require('./registration/rmd'),
require('./registration/rnfr'),
require('./registration/rnto'),
require('./registration/site'),
require('./registration/size'),
require('./registration/stat'),
require('./registration/stor'),
require('./registration/stou'),
require('./registration/stru'),
require('./registration/syst'),
require('./registration/type'),
require('./registration/user')
];
const registry = commands.reduce((result, cmd) => {
const aliases = Array.isArray(cmd.directive) ? cmd.directive : [cmd.directive];
aliases.forEach(alias => result[alias] = cmd);
return result;
}, {});
module.exports = registry;

View File

@@ -1,121 +0,0 @@
const _ = require('lodash');
const uuid = require('uuid');
const when = require('when');
const sequence = require('when/sequence');
const parseCommandString = require('minimist-string');
const net = require('net');
const BaseConnector = require('./connector/base');
const FileSystem = require('./fs');
const Commands = require('./commands');
const errors = require('./errors');
const DEFAULT_MESSAGE = require('./messages');
class FtpConnection {
constructor(server, options) {
this.server = server;
this.commandSocket = options.socket;
this.id = uuid.v4();
this.log = options.log.child({id: this.id});
this.commands = new Commands(this);
this.encoding = 'utf-8';
this.connector = new BaseConnector(this);
this.commandSocket.on('error', err => {
this.server.server.emit('error', {connection: this, error: err});
});
this.commandSocket.on('data', data => {
const messages = _.compact(data.toString('utf-8').split('\r\n'));
const handleMessage = (message) => {
const command = parseCommandString(message);
command.directive = _.upperCase(command._[0]);
return this.commands.handle(command);
};
return sequence(messages.map(message => handleMessage.bind(this, message)));
});
this.commandSocket.on('timeout', () => {});
this.commandSocket.on('close', () => {
if (this.connector) this.connector.end();
if (this.commandSocket && !this.commandSocket.destroyed) this.commandSocket.destroy();
});
}
close(code = 421, message = 'Closing connection') {
return when(() => {
if (code) return this.reply(code, message);
})
.then(() => {
if (this.commandSocket) this.commandSocket.end();
});
}
login(username, password) {
return when.try(() => {
const loginListeners = this.server.listeners('login');
if (!loginListeners || !loginListeners.length) {
if (!this.server.options.anoymous) throw new errors.GeneralError('No "login" listener setup', 500);
} else {
return this.server.emit('login', {connection: this, username, password});
}
})
.then(({fs, cwd, blacklist = [], whitelist = []} = {}) => {
this.authenticated = true;
this.commands.blacklist = _.concat(this.commands.blacklist, blacklist);
this.commands.whitelist = _.concat(this.commands.whitelist, whitelist);
this.fs = fs || new FileSystem(this, {cwd});
});
}
reply(options = {}, ...letters) {
const satisfyParameters = () => {
if (typeof options === 'number') options = {code: options}; // allow passing in code as first param
if (!Array.isArray(letters)) letters = [letters];
if (!letters.length) letters = [{}];
return when.map(letters, (promise, index) => {
return when(promise)
.then(letter => {
if (!letter) letter = {};
else if (typeof letter === 'string') letter = {message: letter}; // allow passing in message as first param
if (!letter.socket) letter.socket = options.socket ? options.socket : this.commandSocket;
if (!letter.message) letter.message = DEFAULT_MESSAGE[options.code] || 'No information';
if (!letter.encoding) letter.encoding = this.encoding;
return when(letter.message) // allow passing in a promise as a message
.then(message => {
letter.message = message;
return letter;
})
});
});
}
const processLetter = (letter, index) => {
return when.promise((resolve, reject) => {
const seperator = !options.hasOwnProperty('eol') ?
(letters.length - 1 === index ? ' ' : '-') :
(options.eol ? ' ' : '-');
const packet = !letter.raw ? _.compact([letter.code || options.code, letter.message]).join(seperator) : letter.message;
if (letter.socket && letter.socket.writable) {
this.log.trace({port: letter.socket.address().port, packet}, 'Reply');
letter.socket.write(packet + '\r\n', letter.encoding, err => {
if (err) {
this.log.error(err);
return reject(err);
}
resolve();
});
} else reject(new errors.SocketError('Socket not writable'));
});
}
return satisfyParameters()
.then(letters => sequence(letters.map((letter, index) => processLetter.bind(this, letter, index))))
.catch(err => {
this.log.error(err);
});
}
}
module.exports = FtpConnection;

View File

@@ -1,36 +0,0 @@
const net = require('net');
const when = require('when');
const Connector = require('./base');
class Active extends Connector {
constructor(connection) {
super(connection);
this.type = 'active';
}
waitForConnection({timeout = 5000, delay = 250} = {}) {
return when.iterate(
() => {},
() => this.dataSocket && this.dataSocket.connected,
() => when().delay(delay)
).timeout(timeout)
.then(() => this.dataSocket);
}
setupConnection(host, port) {
const closeExistingServer = () => this.dataSocket ?
when(this.dataSocket.destroy()) :
when.resolve()
return closeExistingServer()
.then(() => {
this.dataSocket = new net.Socket();
this.dataSocket.setEncoding(this.encoding);
this.dataSocket.connect({ host, port }, () => {
this.dataSocket.pause();
this.dataSocket.connected = true;
});
});
}
}
module.exports = Active;

View File

@@ -1,27 +0,0 @@
const when = require('when');
const errors = require('../errors');
class Connector {
constructor(connection) {
this.connection = connection;
this.server = connection.server;
this.log = connection.log;
this.dataSocket = null;
this.dataServer = null;
this.type = false;
}
waitForConnection() {
return when.reject(new errors.ConnectorError('No connector setup, send PASV or PORT'));
}
end() {
if (this.dataSocket) this.dataSocket.end();
if (this.dataServer) this.dataServer.close();
this.dataSocket = null;
this.dataServer = null;
this.type = false;
}
}
module.exports = Connector;

View File

@@ -1,84 +0,0 @@
const net = require('net');
const when = require('when');
const Connector = require('./base');
const findPort = require('../helpers/find-port');
const errors = require('../errors');
class Passive extends Connector {
constructor(connection) {
super(connection);
this.type = 'passive';
}
waitForConnection({timeout = 5000, delay = 250} = {}) {
if (!this.dataServer) {
return when.reject(new errors.ConnectorError('Passive server not setup'));
}
return when.iterate(
() => {},
() => this.dataServer && this.dataServer.listening && this.dataSocket && this.dataSocket.connected,
() => when().delay(delay)
).timeout(timeout)
.then(() => this.dataSocket);
}
setupServer() {
const closeExistingServer = () => this.dataServer ?
when.promise(resolve => this.dataServer.close(() => resolve())) :
when.resolve()
return closeExistingServer()
.then(() => this.getPort())
.then(port => {
this.dataSocket = null;
this.dataServer = net.createServer({pauseOnConnect: true});
this.dataServer.maxConnections = 1;
this.dataServer.on('connection', socket => {
if (this.connection.commandSocket.remoteAddress !== socket.remoteAddress) {
this.log.error({
pasv_connection: socket.remoteAddress,
cmd_connection: this.connection.commandSocket.remoteAddress
}, 'Connecting addresses do not match');
socket.destroy();
return this.connection.reply(550, 'Remote addresses do not match')
.finally(() => this.connection.close());
}
this.log.debug({port}, 'Passive connection fulfilled.');
this.dataSocket = socket;
this.dataSocket.connected = true;
this.dataSocket.setEncoding(this.connection.encoding);
this.dataSocket.on('close', () => {
this.log.debug('Passive connection closed');
this.end();
});
});
this.dataServer.on('close', () => {
this.log.debug('Passive server closed');
this.dataServer = null;
});
return when.promise((resolve, reject) => {
this.dataServer.listen(port, err => {
if (err) reject(err);
else {
this.log.info({port}, 'Passive connection listening');
resolve(this.dataServer);
}
});
});
});
}
getPort() {
if (this.server.options.pasv_range) {
const [min, max] = typeof this.server.options.pasv_range === 'string' ?
this.server.options.pasv_range.split('-').map(v => v ? parseInt(v) : v) :
[this.server.options.pasv_range];
return findPort(min, max);
} else return undefined;
};
}
module.exports = Passive;

View File

@@ -1,44 +0,0 @@
class GeneralError extends Error {
constructor(message, code = 400) {
super();
this.code = code;
this.name = 'GeneralError';
this.message = message;
}
}
class SocketError extends Error {
constructor(message, code = 500) {
super();
this.code = code;
this.name = 'SocketError';
this.message = message;
}
}
class FileSystemError extends Error {
constructor(message, code = 400) {
super();
this.code = code;
this.name = 'FileSystemError';
this.message = message;
}
}
class ConnectorError extends Error {
constructor(message, code = 400) {
super();
this.code = code;
this.name = 'ConnectorError';
this.message = message;
}
}
module.exports = {
SocketError,
FileSystemError,
ConnectorError,
GeneralError
};

106
src/fs.js
View File

@@ -1,106 +0,0 @@
const _ = require('lodash');
const nodePath = require('path');
const uuid = require('uuid');
const when = require('when');
const whenNode = require('when/node');
const syncFs = require('fs');
const fs = whenNode.liftAll(syncFs);
const errors = require('./errors');
class FileSystem {
constructor(connection, {
cwd = '/'
} = {}) {
this.connection = connection;
this.cwd = cwd;
}
currentDirectory() {
return this.cwd;
}
get(fileName) {
const path = nodePath.resolve(this.cwd, fileName);
return fs.stat(path)
.then(stat => _.set(stat, 'name', fileName));
}
list(path = '.') {
path = nodePath.resolve(this.cwd, path);
return fs.readdir(path)
.then(fileNames => {
return when.map(fileNames, fileName => {
const filePath = nodePath.join(path, fileName);
return fs.access(filePath, syncFs.constants.F_OK)
.then(() => {
return fs.stat(filePath)
.then(stat => _.set(stat, 'name', fileName));
})
.catch(() => null);
});
})
.then(_.compact);
}
chdir(path = '.') {
path = nodePath.resolve(this.cwd, path);
return fs.stat(path)
.tap(stat => {
if (!stat.isDirectory()) throw new errors.FileSystemError('Not a valid directory');
})
.then(() => {
this.cwd = path;
return this.cwd;
});
}
write(fileName, {append = false} = {}) {
const path = nodePath.resolve(this.cwd, fileName);
const stream = syncFs.createWriteStream(path, {flags: !append ? 'w+' : 'a+'});
stream.on('error', () => fs.unlink(path));
return stream;
}
read(fileName) {
const path = nodePath.resolve(this.cwd, fileName);
return fs.stat(path)
.tap(stat => {
if (stat.isDirectory()) throw new errors.FileSystemError('Cannot read a directory');
})
.then(() => {
const stream = syncFs.createReadStream(path, {flags: 'r'});
return stream;
});
}
delete(path) {
path = nodePath.resolve(this.cwd, path);
return fs.stat(path)
.then(stat => {
if (stat.isDirectory()) return fs.rmdir(path);
else return fs.unlink(path);
})
}
mkdir(path) {
path = nodePath.resolve(this.cwd, path);
return fs.mkdir(path)
.then(() => path);
}
rename(from, to) {
const fromPath = nodePath.resolve(this.cwd, from);
const toPath = nodePath.resolve(this.cwd, to);
return fs.rename(fromPath, toPath);
}
chmod(path, mode) {
path = nodePath.resolve(this.cwd, path);
return fs.chmod(path, mode);
}
getUniqueName() {
return uuid.v4().replace(/\W/g, '');
}
}
module.exports = FileSystem;

View File

@@ -1,4 +0,0 @@
module.exports = function (path) {
return path
.replace(/"/g, '""');
}

View File

@@ -1,52 +0,0 @@
const _ = require('lodash');
const format = require('date-fns/format');
const errors = require('../errors');
module.exports = function (fileStat, format = 'ls') {
if (typeof format === 'function') return format(fileStat);
const formats = {
'ls': ls,
'ep': ep
};
if (!formats.hasOwnProperty(format)) {
throw new errors.FileSystemError('Bad file stat formatter');
}
return formats[format](fileStat);
}
function ls(fileStat) {
return [
fileStat.mode !== null
? [
fileStat.isDirectory() ? 'd' : '-',
400 & fileStat.mode ? 'r' : '-',
200 & fileStat.mode ? 'w' : '-',
100 & fileStat.mode ? 'x' : '-',
40 & fileStat.mode ? 'r' : '-',
20 & fileStat.mode ? 'w' : '-',
10 & fileStat.mode ? 'x' : '-',
4 & fileStat.mode ? 'r' : '-',
2 & fileStat.mode ? 'w' : '-',
1 & fileStat.mode ? 'x' : '-'
].join('')
: fileStat.isDirectory() ? 'drwxr-xr-x' : '-rwxr-xr-x',
'1',
fileStat.uid,
fileStat.gid,
_.padStart(fileStat.size, 12),
_.padStart(format(fileStat.mtime, 'MMM DD HH:mm'), 12),
fileStat.name
].join(' ');
}
function ep(fileStat) {
const facts = [
fileStat.dev && fileStat.ino ? `i${fileStat.dev.toString(16)}.${fileStat.ino.toString(16)}` : null,
fileStat.size ? `s${fileStat.size}` : null,
fileStat.mtime ? `m${format(fileStat.mtime, 'X')}` : null,
fileStat.mode ? `up${fileStat.mode.toString(8).substr(fileStat.mode.toString(8).length - 3)}` : null,
fileStat.isDirectory() ? 'r' : '/'
].join(',');
return `+${facts}\t${fileStat.name}`;
}

View File

@@ -1,27 +0,0 @@
const net = require('net');
const when = require('when');
const errors = require('../errors');
module.exports = function (min = 22, max = undefined) {
return when.promise((resolve, reject) => {
let port = min;
let portCheckServer = net.createServer();
portCheckServer.maxConnections = 0;
portCheckServer.on('error', () => {
if (!max || port < max) {
port = port + 1;
portCheckServer.listen(port);
} else {
reject(new errors.GeneralError('Unable to find open port', 500));
}
})
portCheckServer.on('listening', () => {
const {port} = portCheckServer.address();
portCheckServer.close(() => {
portCheckServer = null;
resolve(port);
});
});
portCheckServer.listen(port);
});
};

View File

@@ -1,25 +0,0 @@
const http = require('http');
const when = require('when');
const errors = require('../errors');
const IP_WEBSITE = 'http://api.ipify.org/';
module.exports = function (hostname) {
return when.promise((resolve, reject) => {
if (!hostname || hostname === '0.0.0.0') {
let ip = '';
http.get(IP_WEBSITE, response => {
if (response.statusCode !== 200) {
return reject(new errors.GeneralError('Unable to resolve hostname', response.statusCode));
}
response.setEncoding('utf-8');
response.on('data', chunk => {
ip += chunk;
});
response.on('end', () => {
resolve(ip);
});
});
} else resolve(hostname);
})
}

View File

@@ -1,109 +0,0 @@
const _ = require('lodash');
const when = require('when');
const nodeUrl = require('url');
const buyan = require('bunyan');
const net = require('net');
const Connection = require('./connection');
const resolveHost = require('./helpers/resolve-host');
class FtpServer {
constructor(url, options = {}) {
this.options = _.merge({
log: buyan.createLogger({name: 'ftp-srv'}),
anonymous: false,
pasv_range: 22,
file_format: 'ls',
blacklist: [],
whitelist: []
}, options);
this.connections = {};
this.log = this.options.log;
this.url = nodeUrl.parse(url || 'ftp://127.0.0.1:21');
this.server = net.createServer({pauseOnConnect: true}, socket => {
let connection = new Connection(this, {log: this.log, socket});
this.connections[connection.id] = connection;
socket.on('close', () => this.disconnectClient(connection.id));
const greeting = this.getGreetingMessage();
const features = this.getFeaturesMessage();
return connection.reply(220, greeting, features)
.finally(() => socket.resume());
});
this.server.on('error', err => {
this.log.error(err);
});
this.on = this.server.on.bind(this.server);
this.listeners = this.server.listeners.bind(this.server);
}
listen() {
return resolveHost(this.url.hostname)
.then(hostname => {
this.url.hostname = hostname;
return when.promise((resolve, reject) => {
this.server.listen(this.url.port, err => {
if (err) return reject(err);
this.log.info({port: this.url.port}, 'Listening');
resolve();
});
});
});
}
emit(action, ...data) {
const defer = when.defer();
const params = _.concat(data, [defer.resolve, defer.reject]);
this.server.emit(action, ...params);
return defer.promise;
}
getGreetingMessage() {
return null;
}
getFeaturesMessage() {
let features = [];
if (this.options.anonymous) features.push('a');
if (features.length) {
features.unshift('Features:');
features.push('.')
}
return features.length ? features.join(' ') : 'Ready';
}
setGreeting(gretting) {
if (typeof greeting === 'string') {
this.options.greeting = greeting;
} else {
gretting.then(greeting => {
this.options.gretting = greeting;
})
}
}
disconnectClient(id) {
return when.promise((resolve, reject) => {
const client = this.connections[id];
if (!client) return resolve();
delete this.connections[id];
return client.close(0);
});
}
close() {
this.server.maxConnections = 0;
return when.map(Object.keys(this.connections), id => this.disconnectClient(id))
.then(() => when.promise((resolve, reject) => {
this.server.close(err => {
if (err) return reject(err);
resolve();
});
}));
}
}
module.exports = FtpServer;

View File

@@ -1,56 +0,0 @@
module.exports = {
// 100 - 199 :: Remarks
100: 'The requested action is being initiated',
110: 'Restart marker reply',
120: 'Service ready in %s minutes',
125: 'Data connection already open; transfer starting',
150: 'File status okay; about to open data connection',
// 200 - 399 :: Acceptance
/// 200 - 299 :: Positive Completion Replies
/// These type of replies indicate that the requested action was taken and that the server is awaiting another command.
200: 'The requested action has been successfully completed',
202: 'Superfluous command',
211: 'System status, or system help reply',
212: 'Directory status',
213: 'File status',
214: 'Help message', // On how to use the server or the meaning of a particular non-standard command. This reply is useful only to the human user.
215: 'UNIX Type: L8', // NAME system type. Where NAME is an official system name from the list in the Assigned Numbers document.
220: 'Service ready for new user',
221: 'Service closing control connection', // Logged out if appropriate.
225: 'Data connection open; no transfer in progress',
226: 'Closing data connection', // Requested file action successful (for example, file transfer or file abort).
227: 'Entering Passive Mode', // (h1,h2,h3,h4,p1,p2).
230: 'User logged in, proceed',
234: 'Honored',
250: 'Requested file action okay, completed',
257: '\'%s\' created',
/// 300 - 399 :: Positive Intermediate Replies
/// These types of replies indicate that the requested action was taken and that the server is awaiting further information to complete the request.
331: 'Username okay, awaiting password',
332: 'Need account for login',
350: 'Requested file action pending further information',
// 400 - 599 :: Rejection
/// 400 - 499 :: Transient Negative Completion Replies
/// These types of replies indicate that the command was not accepted; the requested action was not taken.
/// However, the error is temporary and the action may be requested again.
421: 'Service not available, closing control connection', // This may be a reply to any command if the service knows it must shut down.
425: 'Unable to open data connection',
426: 'Connection closed; transfer aborted',
450: 'Requested file action not taken', // File unavailable (e.g., file busy).
451: 'Requested action aborted. Local error in processing',
452: 'Requested action not taken. Insufficient storage',
/// 500 - 599 :: Permanent Negative Completion Replies
/// These types of replies indicate that the command was not accepted; the requested action was not taken.
/// The FTP client is "discouraged" from repeating the same exact request.
500: 'Syntax error', // Can close connection
501: 'Syntax error in parameters or arguments',
502: 'Command not supported',
503: 'Bad sequence of commands',
504: 'Command parameter not supported',
530: 'Not logged in', // Permission Denied, Can close connection
532: 'Need account for storing files',
550: 'Requested action not taken. File unavailable', // (e.g., file not found, no access).
551: 'Requested action aborted. Page type unknown',
552: 'Requested file action aborted. Exceeded storage allocation', // (for current directory or dataset).
553: 'Requested action not taken. File name not allowed'
};

90
src/server/index.js Normal file
View File

@@ -0,0 +1,90 @@
const net = require('net');
const Queue = require('bee-queue');
const {Signale} = require('signale');
const {matches} = require('z');
const KeyValueStore = require('../utils/keyValueStore');
const {setAsyncTimeout} = require('../utils/setAsyncTimeout')
const {setupWorkers} = require('../workers');
const LISTEN_RETRY_MAX = 2;
const LISTEN_RETRY_DELAY = 1500;
class Server extends net.Server {
constructor({
host = '0.0.0.0',
port = 21,
log = {}
} = {}) {
super({
pauseOnConnect: true
});
this.log = new Signale(Object.assign({
scope: 'ftp-srv',
}, log));
this.debugLog = this.log.scope('debug');
this.debugLog.config({
displayTimestamp: true
})
this.receiveQueue = new Queue('receive');
this.sendQueue = new Queue('send');
this.workers = new KeyValueStore();
this.options = new KeyValueStore({
host,
port
});
}
async listen() {
const workers = await setupWorkers();
this.workers.sets(workers);
const port = this.options.get('port');
const host = this.options.get('host');
const tryListen = (retryCount = 1) =>
new Promise((resolve, reject) => {
super.once('error', reject);
super.once('listening', resolve);
super.listen(port, host);
})
.catch(err => matches(err)(
(e = {code: 'EADDRINUSE'}) => {
if (retryCount > LISTEN_RETRY_MAX) throw e;
this.log.error({
message: `Port (${port}) in use, retrying...`,
suffix: `${retryCount} / ${LISTEN_RETRY_MAX}`
});
return setAsyncTimeout(() => tryListen(++retryCount), LISTEN_RETRY_DELAY);
},
(e) => {
throw e;
}
))
.catch(async e => {
await this.close();
throw e;
});
await tryListen();
return this;
}
async close() {
const tryClose = () => new Promise((resolve) => {
super.close(err => {
if (err) {
this.debugLog.error(err);
}
resolve();
});
});
await tryClose();
}
}
module.exports = Server;

23
src/server/index.test.js Normal file
View File

@@ -0,0 +1,23 @@
const Server = require('./');
describe('Server', function () {
let server;
beforeAll(function () {
server = new Server({
port: 8880
});
});
afterAll(async function () {
const value = await server.close();
console.log(value)
});
describe('.listen', function () {
it('# listens', async function () {
await server.listen();
});
});
});

View File

@@ -0,0 +1,27 @@
class KeyValueStore {
constructor(initial = {}) {
this.reset();
this.sets(initial);
}
reset() {
this.values = {};
}
get(key) {
if (!this.values || !this.values[key]) return undefined;
return this.values[key];
}
set(key, value) {
if (!this.values) this.reset();
this.values[key] = value;
}
sets(values) {
for (const [key, value] of Object.entries(values)) {
this.set(key, value)
}
}
}
module.exports = KeyValueStore;

View File

@@ -0,0 +1,12 @@
function setAsyncTimeout(method, timeout, ...args) {
return new Promise(resolve => {
setTimeout(async () => {
const result = await method(...args);
resolve(result)
}, timeout);
});
}
module.exports = {
setAsyncTimeout
};

View File

View File

19
src/workers/index.js Normal file
View File

@@ -0,0 +1,19 @@
const path = require('path');
const {fork} = require('child_process');
async function setupWorkers() {
const commandWorkerPath = path.resolve(__dirname, './command/index.js');
const dataWorkerPath = path.resolve(__dirname, './data/index.js');
const commandWorker = fork(commandWorkerPath, [], {});
const dataWorker = fork(dataWorkerPath, [], {});
return {
command: commandWorker,
data: dataWorker
}
}
module.exports = {
setupWorkers
};

0
src/workers/worker.js Normal file
View File

View File

@@ -1,30 +0,0 @@
const when = require('when');
const {expect} = require('chai');
const sinon = require('sinon')
const CMD = 'ALLO';
describe(CMD, done => {
let sandbox;
const mockClient = {
reply: () => when.resolve()
};
const CMDFN = require(`../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);
beforeEach(() => {
sandbox = sinon.sandbox.create();
sandbox.spy(mockClient, 'reply');
});
afterEach(() => {
sandbox.restore();
});
it('// successful', done => {
CMDFN()
.then(() => {
expect(mockClient.reply.args[0][0]).to.equal(202)
done();
})
.catch(done);
})
});

Some files were not shown because too many files have changed in this diff Show More