-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
87 lines (72 loc) · 2.66 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
var net = require('net');
var fs = require('fs');
var path = require('path');
var config = require('./config');
var startStopDaemon = require('start-stop-daemon');
startStopDaemon({logFile: config.logfile, errFile: config.error_logfile}, function() {
var policypath = path.resolve(__dirname, config.policyfile);
var policy = fs.readFileSync(policypath);
var command = '<policy-file-request/>';
var commandLength = command.length;
var connectionCount = 0;
var server = net.createServer(function (socket) {
socket.openedAt = new Date();
socket.connectionId = ++connectionCount;
socket.connectionRemoteAddress = socket.remoteAddress; // remember remote ip
logForConnection(socket, 'connected');
socket.setTimeout(config.timeout, function () {
logForConnection(socket, 'timeout');
socket.destroy();
});
socket.on('data', function (data) {
var message = 'received ';
if (config.log_request_data) {
message += escape(data.toString()) + ' - ';
}
message += data.toString().length + ' bytes - '
if (data.toString().slice(0, commandLength) === command) {
socket.end(policy);
message += 'OK';
} else {
socket.end();
message += 'BAD';
}
socket.destroy();
logForConnection(socket, message);
});
socket.on('close', function () {
logForConnection(socket, 'closed (handled in ' + (new Date() - socket.openedAt) + 'ms)');
});
socket.on('error', function (e) {
logForConnection(socket, 'error receiving data: ' + e);
socket.destroy();
});
});
server.on('error', function (e) {
if (e.code == 'EADDRINUSE') {
log("server error, address already in use: " + e);
} else {
log("server error: " + e);
}
});
server.on('close', function () {
log("socket policy server closing after handling " + connectionCount + " connections");
});
log('socket policy server binding to port ' + config.port + ' on ' + config.host + ' with policy file ' + policypath);
server.listen(config.port, config.host, function () {
log("successfully bound!");
});
function logForConnection(socket, message) {
log(socket.connectionId + ' - ' + socket.connectionRemoteAddress + ' - ' + message);
}
function log(message) {
if (!config.logging) {
return;
}
var t = (new Date()).toISOString();
console.log(t + ' - ' + message);
}
function escape(message) {
return message.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\x07\x1b\f\t\v/g, '?');
}
});