forked from baldo/ffff
-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
200 lines (152 loc) · 4.58 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// config
var port = 8080;
var peersPath = "/tmp/peers"; // needs to exist already
// modules
var express = require("express");
var fs = require("fs");
// validation
var ValidationError = function (result) {
this._result = result;
};
ValidationError.prototype = new Error();
ValidationError.prototype.getResult = function () {
return this._result;
};
function normalizeString(str) {
return str.trim().replace(/\s+/g, " ");
}
function validate(constraints) {
return function (req, res, next) {
var invalid = [];
var unknown = [];
var missing = [];
var result = {
hasErrors: false
};
var data = req.body;
var key;
for (key in constraints) {
if (data[key] === null || data[key] === undefined) {
missing.push(key);
result.hasErrors = true;
}
}
for (key in data) {
if (data.hasOwnProperty(key)) {
var value = normalizeString(data[key]);
if (!constraints[key]) {
unknown.push(key);
result.hasErrors = true;
}
else if (!value.match(constraints[key])) {
invalid.push(key);
result.hasErrors = true;
}
}
}
result.missing = missing;
result.invalid = invalid;
result.unknown = unknown;
if (result.hasErrors) {
return next(new ValidationError(result));
}
return next();
}
}
// app / routes
var app = express();
app.use(express.bodyParser());
app.use("/", express.static(__dirname + "/static"));
app.get("/", function(req, res, next) {
fs.readFile("static/index.html", "utf8", function (err, body) {
if (err) return next(err);
res.writeHead(200, {"Content-Type": "text/html"});
res.end(body);
});
});
var constraints = {
hostname: /^[-a-zA-Z0-9_]{1,32}$/,
key: /^([a-fA-F0-9]{64})$/
};
var NodeEntryAlreadyExistsError = function (hostname) {
this._hostname = hostname;
};
NodeEntryAlreadyExistsError.prototype = new Error();
NodeEntryAlreadyExistsError.prototype.getHostname = function () {
return this._hostname;
};
function normalizeMac(mac) {
// parts only contains values at odd indexes
var parts = mac.toUpperCase().replace(/:/g, "").split(/([A-F0-9]{2})/);
var macParts = [];
for (var i = 1; i < parts.length; i += 2) {
macParts.push(parts[i]);
}
return macParts.join(":");
}
function createNodeFile(req, res, next) {
var hostname = normalizeString(req.body.hostname);
var key = normalizeString(req.body.key);
var filename = peersPath + "/" + key;
var data = "";
data += "# Knotenname: " + hostname + "\n";
data += "key \"" + key + "\";\n";
console.log("Creating new node file: " + filename);
console.log(data);
var errorHandler = function (err) {
console.log("Creation of new node file failed: " + filename + "\n");
return next(err);
}
// since node.js is single threaded we don't need a lock
var exists = true;
try {
exists = fs.existsSync(filename);
}
catch (err) {
return errorHandler(err);
}
if (exists) {
return errorHandler(new NodeEntryAlreadyExistsError(hostname));
}
try {
fs.writeFileSync(filename, data, "utf8");
}
catch (err) {
return errorHandler(err);
}
console.log("Created new node file: " + filename);
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify({ status: "success" }));
}
app.post("/api/node", validate(constraints), createNodeFile);
function respondWithJson(res, code, data) {
res.writeHead(code, {"Content-Type": "application/json"});
res.end(JSON.stringify(data));
}
app.use(function(err, req, res, next) {
if (err instanceof ValidationError) {
return respondWithJson(res, 400, {
status: "error",
type: "ValidationError",
validationResult: err.getResult()
});
}
else if (err instanceof NodeEntryAlreadyExistsError) {
return respondWithJson(res, 409, {
status: "error",
type: "NodeEntryAlreadyExistsError",
hostname: err.getHostname()
});
}
else if (err) {
console.log(JSON.stringify(err));
return respondWithJson(res, 500, {
status: "error",
type: "internal"
});
}
else {
return next();
}
});
app.listen(port , 'localhost' );