-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
115 lines (98 loc) · 2.57 KB
/
Copy pathserver.js
File metadata and controls
115 lines (98 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* Idea from: https://github.com/zachflower/resume-server
* Sources: http://www.davidmclifton.com/2011/07/22/simple-telnet-server-in-node-js/
*/
/*
* require lib
*/
var net = require('net'),
figlet = require('figlet'),
sprintf = require("sprintf-js").sprintf,
vsprintf = require("sprintf-js").vsprintf,
wrap = require('word-wrap');
/*
* new implement of telnetServer
*/
var telnetServer = (function(){
var config = loadConfig(),
server = {},
sockets = [],
lastInput = "";
function loadConfig() {
try {
require.resolve('./config');
} catch(e) {
console.error("config.js file not found, use config-sample.js as a reference");
process.exit(e.code);
}
return require('./config');
}
function sendData(socket, data) {
socket.write(data);
socket.write("$ ");
}
function closeSocket(socket) {
var i = sockets.indexOf(socket);
if (i != -1) {
sockets.splice(i, 1);
}
}
function printHeader(socket) {
socket.write("\n" + config.last + "\n\n");
socket.write(figlet.textSync(config.motd));
socket.write("\n");
sendData(socket, "Type 'help' for more information.\n");
}
function initTriggers(socket) {
socket.on('data', function(data) {
receiveData(socket, data);
})
socket.on('end', function() {
closeSocket(socket);
})
}
function newSocket(socket) {
sockets.push(socket);
printHeader(socket);
initTriggers(socket);
}
function cleanInput(data) {
return data.toString().replace(/(\r\n|\n|\r)/gm,"").toLowerCase();
}
function receiveData(socket, data) {
var cleanData = cleanInput(data);
if (cleanData != '!!') {
lastInput = cleanData;
} else {
cleanData = lastInput;
}
parseCommand(socket, cleanData);
}
function parseCommand(socket, action) {
switch (action) {
case 'quit':
case 'exit':
socket.end('Goodbye!\n');
break;
case 'help':
var output = "";
output += "These shell commands are defined internally. Type 'help' to see this list.\n";
output += "Type 'help <command>' for more information about a particular command.\n";
output += "\n";
output += "Commands:\n";
sendData(socket, output);
break;
default:
sendData(socket, "error: " + action + ": command not found.\n");
break;
}
}
return {
"create" : function() {
server = net.createServer(newSocket);
server.listen(config.port);
}
}
}());
/* go */
telnetServer.create();