This repository has been archived by the owner on Jul 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.js
383 lines (304 loc) · 9.88 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// config
var port = 8080;
var peersPath = "/tmp/peers"; // needs to exist already
// modules
var express = require("express");
var fs = require("fs");
var glob = require("glob");
var _ = require("underscore");
var crypto = require("crypto");
// validation
var ValidationError = function (result) {
this._result = result;
};
ValidationError.prototype = new Error();
ValidationError.prototype.getResult = function () {
return this._result;
};
function normalizeString(str) {
return _.isString(str) ? str.trim().replace(/\s+/g, " ") : str;
}
function getData(req) {
return _.extend({}, req.body, req.params);
}
function validate(constraints) {
return function (req, res, next) {
var invalid = [];
var unknown = [];
var missing = [];
var result = {
hasErrors: false
};
var data = getData(req);
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})?$/,
email: /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/,
nickname: /^[-a-zA-Z0-9_ äöüÄÖÜß]{1,64}$/,
mac: /^([a-fA-F0-9]{12}|([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2})$/,
coords: /^(-?[0-9]{1,3}(\.[0-9]{1,15})? -?[0-9]{1,3}(\.[0-9]{1,15})?)?$/
};
var tokenConstraint = {
token: /^[a-f0-9]{16}/
};
var constraintsWithToken = _.extend({}, constraints, tokenConstraint);
var NodeEntryAlreadyExistsError = function (hostname) {
this._hostname = hostname;
};
NodeEntryAlreadyExistsError.prototype = new Error();
NodeEntryAlreadyExistsError.prototype.getHostname = function () {
return this._hostname;
};
var MacEntryAlreadyExistsError = function (mac) {
this._mac = mac;
};
MacEntryAlreadyExistsError.prototype = new Error();
MacEntryAlreadyExistsError.prototype.getMac = function () {
return this._mac;
};
var KeyEntryAlreadyExistsError = function (key) {
this._key = key;
};
KeyEntryAlreadyExistsError.prototype = new Error();
KeyEntryAlreadyExistsError.prototype.getKey = function () {
return this._key;
};
var NodeNotFoundError = function (token) {
this._token = token;
};
NodeNotFoundError.prototype = new Error();
NodeNotFoundError.prototype.getToken = function () {
return this._token;
};
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 findNodeFiles(pattern) {
return glob.sync(peersPath + "/" + pattern);
}
function generateToken() {
return crypto.randomBytes(8).toString("hex");
}
function isDuplicate(pattern, token) {
var files = findNodeFiles(pattern);
if (files.length === 0) {
return false;
}
if (files.length > 1 || !token) {
return true;
}
var file = files[0];
return file.substring(file.length - token.length, file.length) !== token;
}
function checkNoDuplicates(hostname, mac, key, token) {
if (isDuplicate(hostname.toLowerCase() + "@*@*@*", token)) {
return new NodeEntryAlreadyExistsError(hostname);
}
if (isDuplicate("*@" + mac.toLowerCase() + "@*@*", token)) {
return new MacEntryAlreadyExistsError(mac);
}
if (key) {
if (isDuplicate("*@*@" + key.toLowerCase() + "@*", token)) {
return new KeyEntryAlreadyExistsError(key);
}
}
return null;
}
function createNodeFile(req, res, next) {
var postData = getData(req);
var hostname = normalizeString(postData.hostname);
var key = normalizeString(postData.key);
var email = normalizeString(postData.email);
var nickname = normalizeString(postData.nickname);
var mac = normalizeMac(normalizeString(postData.mac));
var coords = normalizeString(postData.coords);
var token = normalizeString(postData.token);
var isUpdate = !!token;
if (!token) {
token = generateToken();
}
var filename = peersPath + "/" + hostname + "@" + mac + "@" + key + "@" + token;
var data = "";
data += "# Knotenname: " + hostname + "\n";
data += "# Ansprechpartner: " + nickname + "\n";
data += "# Kontakt: " + email + "\n";
data += "# Koordinaten: " + coords + "\n";
data += "# MAC: " + mac + "\n";
data += "# Token: " + token + "\n";
if (key) {
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 e;
if (isUpdate) {
var files = findNodeFiles("*@*@*@" + token);
if (files.length !== 1) {
return next(new NodeNotFoundError(token));
}
e = checkNoDuplicates(hostname, mac, key, token);
if (e) {
return errorHandler(e);
}
var file = files[0];
fs.unlinkSync(file);
} else {
e = checkNoDuplicates(hostname, mac, key, null);
if (e) {
return errorHandler(e);
}
}
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(_.defaults({ status: "success", token: token }, postData)));
}
function getNodeData(req, res, next) {
var token = normalizeString(getData(req).token);
var files = findNodeFiles("*@*@*@" + token);
if (files.length !== 1) {
return next(new NodeNotFoundError(token));
}
var file = files[0];
var lines = fs.readFileSync(file).toString();
var data = {};
_.each(lines.split("\n"), function (line) {
var linePrefixes = {
hostname: "# Knotenname: ",
nickname: "# Ansprechpartner: ",
email: "# Kontakt: ",
coords: "# Koordinaten: ",
mac: "# MAC: ",
token: "# Token: "
};
var match = _.reduce(linePrefixes, function (match, prefix, key) {
if (!_.isEmpty(match)) {
return match;
}
if (line.substring(0, prefix.length) === prefix) {
match[key] = normalizeString(line.substr(prefix.length));
return match;
}
return {};
}, {});
if (_.isEmpty(match) && line.substring(0, 5) === "key \"") {
match.key = normalizeString(line.split("\"")[1]);
}
_.each(match, function (value, key) {
data[key] = value;
});
});
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(data));
}
app.post("/api/node", validate(constraints), createNodeFile);
app.put("/api/node/:token", validate(constraintsWithToken), createNodeFile);
app.get("/api/node/:token", validate(tokenConstraint), getNodeData);
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 instanceof MacEntryAlreadyExistsError) {
return respondWithJson(res, 409, {
status: "error",
type: "MacEntryAlreadyExistsError",
mac: err.getMac()
});
}
else if (err instanceof KeyEntryAlreadyExistsError) {
return respondWithJson(res, 409, {
status: "error",
type: "KeyEntryAlreadyExistsError",
key: err.getKey()
});
}
else if (err instanceof NodeNotFoundError) {
return respondWithJson(res, 404, {
status: "error",
type: "NodeNotFoundError",
token: err.getToken()
});
}
else if (_.isObject(err)) {
console.trace("Internal error:", JSON.stringify(err));
return respondWithJson(res, 500, {
status: "error",
type: "internal"
});
}
else {
return next();
}
});
app.listen(port);