forked from ashleybaldock/simlist
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
260 lines (229 loc) · 10.9 KB
/
server.js
File metadata and controls
260 lines (229 loc) · 10.9 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
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
//
// Simutrans Listing Server
//
//
// Copyright © 2011-2014 Timothy Baldock. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission from the author.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Configured by environment parameters
var header_image = process.env.HEADER_IMAGE || "simlogo.png";
var port = process.env.PORT || 80;
var ssl_port = process.env.SSL_PORT || 443;
var prune_interval = process.env.PRUNE_INTERVAL || 86400;
// Includes
const path = require('node:path');
var express = require('express');
var fs = require("fs");
var mustache = require('mustache');
var validator = require("validator");
var bodyParser = require('body-parser');
var listing = require('./lib/Listing.js');
var simutil = require('./lib/SimUtil.js');
var translator = require('./lib/Translator.js');
//var ListingProvider = require('./lib/MongoDBListingProvider.js').ListingProvider;
var ListingProvider = require('./lib/MemoryListingProvider.js').ListingProvider;
var app = express();
const certDir = `/etc/letsencrypt/live`;
const domain = `servers.simutrans-forum.de`;
const options = {
key: fs.readFileSync(`${certDir}/${domain}/privkey.pem`),
cert: fs.readFileSync(`${certDir}/${domain}/fullchain.pem`)
};
app.use(bodyParser());
app.set('trust proxy', true);
var translate = (new translator.Translator()).translate;
var available_formats = ["html", "csv"];
var templatefiles = [
"header.html",
"footer.html",
"announce.html",
"list.html"
];
var templates = {};
for (n in templatefiles) {
if (templatefiles.hasOwnProperty(n)) {
console.log("loading file: " + templatefiles[n] + "...");
templates[templatefiles[n]] = fs.readFileSync("templates/" + templatefiles[n], "utf8");
}
}
var listingProvider = new ListingProvider(function () {
// SSL Configuration ends
let https = require('https').Server(options, app);
https.listen(ssl_port, function () {
console.log('API server listening on port ' + ssl_port + ' (SSL Connection)');
});
// Normal HTTP configuration
let http = require('http').Server(app);
http.listen(port, function() {
console.log('API server listening on port ' + port);
});
});
app.use('/static', express.static(__dirname + '/public'));
app.get('/', function(req, res) { res.redirect(301, '/list'); });
// lestsencrypt challenge
app.get('/.well-known/acme-challenge/+*',(req, res) => {
const file = './acme/.well-known/acme-challenge/'+path.posix.basename(req.path);
console.log('acme challenge '+file);
res.download(file); // Set disposition and send it.
});
app.get('/announce', function(req, res) {
res.writeHead(405, {"Content-Type": "text/html", "Allow": "POST"});
res.write(mustache.render(templates["announce.html"], {}));
res.end();
});
app.post('/announce', function(req, res) {
// console.log("recieved announce from "+req.body.dns+" alt_dns "+req.body.alt_dns+" at IP "+req.ip);
if (!req.body.port) {
res.status(400).send("Bad Request - port field missing");
return;
}
if (!listing.validate_port(listing.parse_port(req.body.port))) {
res.status(400).send("Bad Request - port field invalid");
return;
}
if (!req.body.dns) {
res.status(400).send("Bad Request - DNS field missing");
return;
}
listing.validate_dns(listing.parse_dns(req.body.dns), listing.parse_dns(req.body.alt_dns), req.ip,
function () {
var new_listing = new listing.Listing(req.body.dns, req.body.port);
// console.log(JSON.stringify(req.body));
if (new_listing.name === "") { new_listing.name = new_listing.id; }
listingProvider.findById(new_listing.id, function (existing_listing) {
new_listing.update_from_object(existing_listing);
new_listing.update_from_body(req.body);
listingProvider.save(new_listing, function () {});
res.status(201).send(JSON.stringify(new_listing));
});
},
function () {
res.status(400).send("Bad Request - DNS field invalid");
}
);
});
app.get('/list', function(req, res) {
var urlbase, key;
// Process defaults
if (!req.query.format) { req.query.format = "html"; }
if (req.query.format === "html") {
res.writeHead(200, {"Content-Type": "text/html"});
// Write header
res.write(mustache.render(templates["header.html"],
{title: req.hostname + " - Server listing", translate: translate, headerimage: header_image}));
urlbase = "./list";
if (req.query.detail) {
urlbase = urlbase + "?detail=" + req.query.detail;
}
listingProvider.findAll(function (listings) {
var pakset_names = [];
var pakset_groups = {};
for (key in listings) {
if (listings.hasOwnProperty(key)) {
var item = listings[key];
var timings = simutil.get_times(item.date, item.aiv);
if (timings.overdue_by > prune_interval * 1000) {
listingProvider.removeById(item.id, function(removed) {
console.log("Pruned stale server with id: " + removed.id);
});
} else {
if (timings.overdue_by > item.aiv * 1000) {
item.st = 0;
}
var pakset_name = item.pak.split(" ")[0];
if (pakset_names.indexOf(pakset_name) < 0) {
pakset_names.push(pakset_name);
pakset_groups[pakset_name] = [];
}
pakset_groups[pakset_name].push({
detail: (key === req.query.detail),
data: item,
timing: timings
});
}
}
}
// Map paksets into output format for mustache
var paksets_mapped = [];
for (key in pakset_groups) {
paksets_mapped.push({name: key, items: pakset_groups[key]});
}
res.write(mustache.render(templates["list.html"],
{translate: translate, timeformat: simutil.format_time,
paksets: paksets_mapped}));
res.write(mustache.render(templates["footer.html"], {}));
res.end();
});
} else if (req.query.format === "csv") {
var response = "";
listingProvider.findAll(function (listings) {
for (key in listings) {
if (listings.hasOwnProperty(key)) {
var item = listings[key];
var timings = simutil.get_times(item.date, item.aiv);
if (timings.overdue_by > prune_interval * 1000) {
listingProvider.removeById(item.id, function(removed) {
console.log("Pruned stale server with id: " + removed.id);
});
} else {
if (timings.overdue_by > item.aiv * 1000) {
item.st = 0;
}
if (item.dns
&& item.port
// && item.name
// && item.rev
// && item.pak && item.pak !== "unknown") {
) {
var itname = "simutrans server";
if (item.name) {
itname = item.name;
}
// we return an alternative IP6 only for IP6 capable systems
var dns_name = item.dns;
var alt_dnsname = item.alt_dns;
if (!req.ip.match(/::ffff:/) ) {
// we have a real IP6 here, IPv4 start with "::ffff:" on a dualstack system
// thus we return and IP
if( validator.isIP(item.alt_dns,"6") ) {
dns_name = "["+item.alt_dns+"]";
alt_dnsname = item.dns;
}
else if( validator.isIP(item.dns,"6") ) {
dns_name = "["+item.dns+"]";
}
}
response = response
+ simutil.csv_escape(itname)
+ "," + simutil.csv_escape(dns_name
+ ":" + item.port)
+ "," + simutil.csv_escape(item.rev.toString())
+ "," + simutil.csv_escape(item.pak)
+ "," + simutil.csv_escape(item.st.toString());
// append alt_dns if there
if( validator.isIP(alt_dnsname,"6") ) {
response = response + ",[" + alt_dnsname + "]";
}
else if( validator.isIP(alt_dnsname,"4") ) {
response = response + "," + alt_dnsname;
}
response = response + "\n";
}
}
}
}
res.status(200).send(response);
});
} else {
res.status(501).send("501 Not Implemented - The specified output format is not supported, supported formats are: " + available_formats.toString());
}
});