forked from calzoneman/sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
409 lines (361 loc) · 12.7 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
const VERSION = require("../package.json").version;
var singleton = null;
var Config = require("./config");
var Promise = require("bluebird");
import * as ChannelStore from './channel-storage/channelstore';
import { EventEmitter } from 'events';
import { LoggerFactory } from '@calzoneman/jsli';
const LOGGER = LoggerFactory.getLogger('server');
module.exports = {
init: function () {
LOGGER.info("Starting CyTube v%s", VERSION);
var chanlogpath = path.join(__dirname, "../chanlogs");
fs.exists(chanlogpath, function (exists) {
exists || fs.mkdirSync(chanlogpath);
});
var chandumppath = path.join(__dirname, "../chandump");
fs.exists(chandumppath, function (exists) {
exists || fs.mkdirSync(chandumppath);
});
var gdvttpath = path.join(__dirname, "../google-drive-subtitles");
fs.exists(gdvttpath, function (exists) {
exists || fs.mkdirSync(gdvttpath);
});
singleton = new Server();
return singleton;
},
getServer: function () {
return singleton;
}
};
var path = require("path");
var fs = require("fs");
var http = require("http");
var https = require("https");
var express = require("express");
var Channel = require("./channel/channel");
var db = require("./database");
var Flags = require("./flags");
var sio = require("socket.io");
import LocalChannelIndex from './web/localchannelindex';
import { PartitionChannelIndex } from './partition/partitionchannelindex';
import IOConfiguration from './configuration/ioconfig';
import WebConfiguration from './configuration/webconfig';
import NullClusterClient from './io/cluster/nullclusterclient';
import session from './session';
import { LegacyModule } from './legacymodule';
import { PartitionModule } from './partition/partitionmodule';
import * as Switches from './switches';
var Server = function () {
var self = this;
self.channels = [],
self.express = null;
self.db = null;
self.api = null;
self.announcement = null;
self.infogetter = null;
self.servers = {};
// backend init
var initModule;
if (Config.get("new-backend")) {
if (Config.get("dual-backend")) {
Switches.setActive(Switches.DUAL_BACKEND, true);
}
const BackendModule = require('./backend/backendmodule').BackendModule;
initModule = this.initModule = new BackendModule();
} else if (Config.get('enable-partition')) {
initModule = this.initModule = new PartitionModule();
self.partitionDecider = initModule.getPartitionDecider();
} else {
initModule = this.initModule = new LegacyModule();
}
// database init ------------------------------------------------------
var Database = require("./database");
self.db = Database;
self.db.init();
ChannelStore.init();
// webserver init -----------------------------------------------------
const ioConfig = IOConfiguration.fromOldConfig(Config);
const webConfig = WebConfiguration.fromOldConfig(Config);
const clusterClient = initModule.getClusterClient();
var channelIndex;
if (Config.get("enable-partition")) {
channelIndex = new PartitionChannelIndex(
initModule.getRedisClientProvider().get()
);
} else {
channelIndex = new LocalChannelIndex();
}
self.express = express();
require("./web/webserver").init(self.express,
webConfig,
ioConfig,
clusterClient,
channelIndex,
session);
// http/https/sio server init -----------------------------------------
var key = "", cert = "", ca = undefined;
if (Config.get("https.enabled")) {
const certData = self.loadCertificateData();
key = certData.key;
cert = certData.cert;
ca = certData.ca;
}
var opts = {
key: key,
cert: cert,
passphrase: Config.get("https.passphrase"),
ca: ca,
ciphers: Config.get("https.ciphers"),
honorCipherOrder: true
};
Config.get("listen").forEach(function (bind) {
var id = bind.ip + ":" + bind.port;
if (id in self.servers) {
LOGGER.warn("Ignoring duplicate listen address %s", id);
return;
}
if (bind.https && Config.get("https.enabled")) {
self.servers[id] = https.createServer(opts, self.express)
.listen(bind.port, bind.ip);
self.servers[id].on("clientError", function (err, socket) {
try {
socket.destroy();
} catch (e) {
}
});
} else if (bind.http) {
self.servers[id] = self.express.listen(bind.port, bind.ip);
self.servers[id].on("clientError", function (err, socket) {
try {
socket.destroy();
} catch (e) {
}
});
}
});
require("./io/ioserver").init(self, webConfig);
// background tasks init ----------------------------------------------
require("./bgtask")(self);
// setuid
require("./setuid");
initModule.onReady();
};
Server.prototype = Object.create(EventEmitter.prototype);
Server.prototype.loadCertificateData = function loadCertificateData() {
const data = {
key: fs.readFileSync(path.resolve(__dirname, "..",
Config.get("https.keyfile"))),
cert: fs.readFileSync(path.resolve(__dirname, "..",
Config.get("https.certfile")))
};
if (Config.get("https.cafile")) {
data.ca = fs.readFileSync(path.resolve(__dirname, "..",
Config.get("https.cafile")));
}
return data;
};
Server.prototype.reloadCertificateData = function reloadCertificateData() {
const certData = this.loadCertificateData();
Object.keys(this.servers).forEach(key => {
const server = this.servers[key];
// TODO: Replace with actual node API
// once https://github.com/nodejs/node/issues/4464 is implemented.
if (server._sharedCreds) {
try {
server._sharedCreds.context.setCert(certData.cert);
server._sharedCreds.context.setKey(certData.key, Config.get("https.passphrase"));
LOGGER.info('Reloaded certificate data for %s', key);
} catch (error) {
LOGGER.error('Failed to reload certificate data for %s: %s', key, error.stack);
}
}
});
};
Server.prototype.getHTTPIP = function (req) {
var ip = req.ip;
if (ip === "127.0.0.1" || ip === "::1") {
var fwd = req.header("x-forwarded-for");
if (fwd && typeof fwd === "string") {
return fwd;
}
}
return ip;
};
Server.prototype.getSocketIP = function (socket) {
var raw = socket.handshake.address.address;
if (raw === "127.0.0.1" || raw === "::1") {
var fwd = socket.handshake.headers["x-forwarded-for"];
if (fwd && typeof fwd === "string") {
return fwd;
}
}
return raw;
};
Server.prototype.isChannelLoaded = function (name) {
name = name.toLowerCase();
for (var i = 0; i < this.channels.length; i++) {
if (this.channels[i].uniqueName == name)
return true;
}
return false;
};
Server.prototype.getChannel = function (name) {
var cname = name.toLowerCase();
if (this.partitionDecider &&
!this.partitionDecider.isChannelOnThisPartition(cname)) {
const error = new Error(`Channel '${cname}' is mapped to a different partition`);
error.code = 'EWRONGPART';
throw error;
}
var self = this;
for (var i = 0; i < self.channels.length; i++) {
if (self.channels[i].uniqueName === cname)
return self.channels[i];
}
var c = new Channel(name);
c.on("empty", function () {
self.unloadChannel(c);
});
c.waitFlag(Flags.C_ERROR, () => {
self.unloadChannel(c, { skipSave: true });
});
self.channels.push(c);
return c;
};
Server.prototype.unloadChannel = function (chan, options) {
if (chan.dead) {
return;
}
if (!options) {
options = {};
}
if (!options.skipSave) {
chan.saveState().catch(error => {
LOGGER.error(`Failed to save /r/${chan.name} for unload: ${error.stack}`);
});
}
chan.logger.log("[init] Channel shutting down");
chan.logger.close();
chan.notifyModules("unload", []);
Object.keys(chan.modules).forEach(function (k) {
chan.modules[k].dead = true;
/*
* Automatically clean up any timeouts/intervals assigned
* to properties of channel modules. Prevents a memory leak
* in case of forgetting to clear the timer on the "unload"
* module event.
*/
Object.keys(chan.modules[k]).forEach(function (prop) {
if (chan.modules[k][prop] && chan.modules[k][prop]._onTimeout) {
LOGGER.warn("Detected non-null timer when unloading " +
"module " + k + ": " + prop);
try {
clearTimeout(chan.modules[k][prop]);
clearInterval(chan.modules[k][prop]);
} catch (error) {
LOGGER.error(error.stack);
}
}
});
});
for (var i = 0; i < this.channels.length; i++) {
if (this.channels[i].uniqueName === chan.uniqueName) {
this.channels.splice(i, 1);
i--;
}
}
LOGGER.info("Unloaded channel " + chan.name);
chan.broadcastUsercount.cancel();
// Empty all outward references from the channel
var keys = Object.keys(chan);
for (var i in keys) {
if (keys[i] !== "refCounter") {
delete chan[keys[i]];
}
}
chan.dead = true;
};
Server.prototype.packChannelList = function (publicOnly, isAdmin) {
var channels = this.channels.filter(function (c) {
if (!publicOnly) {
return true;
}
return c.modules.options && c.modules.options.get("show_public");
});
var self = this;
return channels.map(function (c) {
return c.packInfo(isAdmin);
});
};
Server.prototype.announce = function (data) {
this.setAnnouncement(data);
if (data == null) {
db.clearAnnouncement();
} else {
db.setAnnouncement(data);
}
this.emit("announcement", data);
};
Server.prototype.setAnnouncement = function (data) {
if (data == null) {
this.announcement = null;
} else {
this.announcement = data;
sio.instance.emit("announcement", data);
}
};
Server.prototype.shutdown = function () {
LOGGER.info("Unloading channels");
Promise.map(this.channels, channel => {
try {
return channel.saveState().tap(() => {
LOGGER.info(`Saved /r/${channel.name}`);
}).catch(err => {
LOGGER.error(`Failed to save /r/${channel.name}: ${err.stack}`);
});
} catch (error) {
LOGGER.error(`Failed to save channel: ${error.stack}`);
}
}, { concurrency: 5 }).then(() => {
LOGGER.info("Goodbye");
process.exit(0);
}).catch(err => {
LOGGER.error(`Caught error while saving channels: ${err.stack}`);
process.exit(1);
});
};
Server.prototype.handlePartitionMapChange = function () {
const channels = Array.prototype.slice.call(this.channels);
Promise.map(channels, channel => {
if (channel.dead) {
return;
}
if (!this.partitionDecider.isChannelOnThisPartition(channel.uniqueName)) {
LOGGER.info("Partition changed for " + channel.uniqueName);
return channel.saveState().then(() => {
channel.broadcastAll("partitionChange",
this.partitionDecider.getPartitionForChannel(channel.uniqueName));
const users = Array.prototype.slice.call(channel.users);
users.forEach(u => {
try {
u.socket.disconnect();
} catch (error) {
}
});
this.unloadChannel(channel, { skipSave: true });
}).catch(error => {
LOGGER.error(`Failed to unload /r/${channel.name} for ` +
`partition map flip: ${error.stack}`);
});
}
}, { concurrency: 5 }).then(() => {
LOGGER.info("Partition reload complete");
});
};
Server.prototype.reloadPartitionMap = function () {
if (!Config.get("enable-partition")) {
return;
}
this.initModule.getPartitionMapReloader().reload();
};