Start working on refactoring server

This commit is contained in:
calzoneman 2013-07-15 18:57:33 -04:00
parent 4cf0f76733
commit bf8fef29cf
3 changed files with 700 additions and 754 deletions

257
api.js
View File

@ -9,47 +9,46 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Auth = require("./auth.js");
var Server = require("./server.js");
var Logger = require("./logger.js");
var Auth = require("./auth");
var Logger = require("./logger");
var apilog = new Logger.Logger("api.log");
var Database = require("./database.js");
var Config = require("./config.js");
var ActionLog = require("./actionlog.js");
var Config = require("./config");
var ActionLog = require("./actionlog");
var fs = require("fs");
var plainHandlers = {
"readlog" : handleReadLog
};
var jsonHandlers = {
"channeldata": handleChannelData,
"listloaded" : handleChannelList,
"login" : handleLogin,
"register" : handleRegister,
"changepass" : handlePasswordChange,
"resetpass" : handlePasswordReset,
"recoverpw" : handlePasswordRecover,
"setprofile" : handleProfileChange,
"getprofile" : handleProfileGet,
"setemail" : handleEmailChange,
"admreports" : handleAdmReports,
"readactionlog" : handleReadActionLog
};
function getClientIP(req) {
var ip;
function getIP(req) {
var raw = req.connection.remoteAddress;
var forward = req.header("x-forwarded-for");
if(Config.REVERSE_PROXY && forward) {
ip = forward.split(",")[0];
}
if(!ip) {
ip = req.connection.remoteAddress;
}
var ip = forward.split(",")[0];
Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return ip;
}
return raw;
}
function handle(path, req, res) {
module.exports = function (Server) {
return {
plainHandlers: {
"readlog" : this.handleReadLog
},
jsonHandlers: {
"channeldata" : this.handleChannelData,
"listloaded" : this.handleChannelList,
"login" : this.handleLogin,
"register" : this.handleRegister,
"changepass" : this.handlePasswordChange,
"resetpass" : this.handlePasswordReset,
"recoverpw" : this.handlePasswordRecover,
"setprofile" : this.handleProfileChange,
"getprofile" : this.handleProfileGet,
"setemail" : this.handleEmailChange,
"admreports" : this.handleAdmReports,
"readactionlog" : this.handleReadActionLog
},
handle: function (path, req, res) {
var parts = path.split("/");
var last = parts[parts.length - 1];
var params = {};
@ -76,28 +75,27 @@ function handle(path, req, res) {
if(parts[0] == "json") {
res.callback = params.callback || false;
if(!(parts[1] in jsonHandlers)) {
if(!(parts[1] in this.jsonHandlers)) {
res.end(JSON.stringify({
error: "Unknown endpoint: " + parts[1]
}, null, 4));
return;
}
jsonHandlers[parts[1]](params, req, res);
this.jsonHandlers[parts[1]](params, req, res);
}
else if(parts[0] == "plain") {
if(!(parts[1] in plainHandlers)) {
if(!(parts[1] in this.plainHandlers)) {
res.send(404);
return;
}
plainHandlers[parts[1]](params, req, res);
this.plainHandlers[parts[1]](params, req, res);
}
else {
res.send(400);
}
}
exports.handle = handle;
},
function sendJSON(res, obj) {
sendJSON: function (res, obj) {
var response = JSON.stringify(obj, null, 4);
if(res.callback) {
response = res.callback + "(" + response + ")";
@ -107,9 +105,9 @@ function sendJSON(res, obj) {
res.setHeader("Content-Type", "application/json");
res.setHeader("Content-Length", len);
res.end(response);
}
},
function sendPlain(res, str) {
sendPlain: function (res, str) {
if(res.callback) {
str = res.callback + "('" + str + "')";
}
@ -118,9 +116,9 @@ function sendPlain(res, str) {
res.setHeader("Content-Type", "text/plain");
res.setHeader("Content-Length", len);
res.end(response);
}
},
function handleChannelData(params, req, res) {
handleChannelData: function (params, req, res) {
var clist = params.channel || "";
clist = clist.split(",");
var data = [];
@ -129,9 +127,10 @@ function handleChannelData(params, req, res) {
if(!cname.match(/^[a-zA-Z0-9-_]+$/)) {
continue;
}
var d = {
name: cname,
loaded: Server.getChannel(cname) !== undefined
loaded: Server.channelLoaded(cname)
};
if(d.loaded) {
@ -153,12 +152,12 @@ function handleChannelData(params, req, res) {
data.push(d);
}
sendJSON(res, data);
}
this.sendJSON(res, data);
},
function handleChannelList(params, req, res) {
handleChannelList: function (params, req, res) {
if(params.filter == "public") {
var all = Server.getAllChannels();
var all = Server.channels;
var clist = [];
for(var key in all) {
if(all[key].opts.show_public) {
@ -176,27 +175,27 @@ function handleChannelList(params, req, res) {
return;
}
var clist = [];
for(var key in Server.getAllChannels()) {
for(var key in Server.channels) {
clist.push(key);
}
handleChannelData({channel: clist.join(",")}, req, res);
}
},
function handleLogin(params, req, res) {
handleLogin: function (params, req, res) {
var session = params.session || "";
var name = params.name || "";
var pw = params.pw || "";
if(pw == "" && session == "") {
if(!Auth.isRegistered(name)) {
sendJSON(res, {
this.sendJSON(res, {
success: true,
session: ""
});
return;
}
else {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "That username is already taken"
});
@ -206,27 +205,27 @@ function handleLogin(params, req, res) {
var row = Auth.login(name, pw, session);
if(row) {
ActionLog.record(getClientIP(req), name, "login-success");
sendJSON(res, {
ActionLog.record(getIP(req), name, "login-success");
this.sendJSON(res, {
success: true,
session: row.session_hash
});
}
else {
ActionLog.record(getClientIP(req), name, "login-failure");
sendJSON(res, {
ActionLog.record(getIP(req), name, "login-failure");
this.sendJSON(res, {
error: "Invalid username/password",
success: false
});
}
}
},
function handlePasswordChange(params, req, res) {
handlePasswordChange: function (params, req, res) {
var name = params.name || "";
var oldpw = params.oldpw || "";
var newpw = params.newpw || "";
if(oldpw == "" || newpw == "") {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Old password and new password cannot be empty"
});
@ -234,34 +233,34 @@ function handlePasswordChange(params, req, res) {
}
var row = Auth.login(name, oldpw);
if(row) {
ActionLog.record(getClientIP(req), name, "password-change");
ActionLog.record(getIP(req), name, "password-change");
var success = Auth.setUserPassword(name, newpw);
sendJSON(res, {
this.sendJSON(res, {
success: success,
error: success ? "" : "Change password failed",
session: row.session_hash
});
}
else {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Invalid username/password"
});
}
}
},
function handlePasswordReset(params, req, res) {
handlePasswordReset: function (params, req, res) {
var name = params.name || "";
var email = unescape(params.email || "");
var ip = getClientIP(req);
var ip = getIP(req);
var hash = false;
try {
hash = Database.generatePasswordReset(ip, name, email);
hash = Server.db.generatePasswordReset(ip, name, email);
ActionLog.record(ip, name, "password-reset-generate", email);
}
catch(e) {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: e
});
@ -269,14 +268,14 @@ function handlePasswordReset(params, req, res) {
}
if(!Config.MAIL) {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "This server does not have email enabled. Contact an administrator"
});
return;
}
if(!email) {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "You don't have a recovery email address set. Contact an administrator"
});
@ -306,13 +305,13 @@ function handlePasswordReset(params, req, res) {
Config.MAIL.sendMail(mail, function(err, response) {
if(err) {
Logger.errlog.log("Mail fail: " + err);
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Email failed. Contact an admin if this persists."
});
}
else {
sendJSON(res, {
this.sendJSON(res, {
success: true
});
@ -321,15 +320,15 @@ function handlePasswordReset(params, req, res) {
}
}
});
}
},
function handlePasswordRecover(params, req, res) {
handlePasswordRecover: function (params, req, res) {
var hash = params.hash || "";
var ip = getClientIP(req);
var ip = getIP(req);
try {
var info = Database.recoverPassword(hash);
sendJSON(res, {
var info = Server.db.recoverPassword(hash);
this.sendJSON(res, {
success: true,
name: info[0],
pw: info[1]
@ -340,34 +339,33 @@ function handlePasswordRecover(params, req, res) {
}
catch(e) {
ActionLog.record(ip, name, "password-recover-failure");
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: e
});
}
},
}
function handleProfileGet(params, req, res) {
handleProfileGet: function (params, req, res) {
var name = params.name || "";
try {
var prof = Database.getProfile(name);
sendJSON(res, {
var prof = Server.db.getProfile(name);
this.sendJSON(res, {
success: true,
profile_image: prof.profile_image,
profile_text: prof.profile_text
});
}
catch(e) {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: e
});
}
}
},
function handleProfileChange(params, req, res) {
handleProfileChange: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var session = params.session || "";
@ -376,24 +374,24 @@ function handleProfileChange(params, req, res) {
var row = Auth.login(name, pw, session);
if(!row) {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Invalid login"
});
return;
}
var result = Database.setProfile(name, {
var result = Server.db.setProfile(name, {
image: img,
text: text
});
sendJSON(res, {
this.sendJSON(res, {
success: result,
error: result ? "" : "Internal error. Contact an administrator"
});
var all = Server.getAllChannels();
var all = Server.channels;
for(var n in all) {
var chan = all[n];
for(var i = 0; i < chan.users.length; i++) {
@ -407,14 +405,17 @@ function handleProfileChange(params, req, res) {
}
}
}
}
},
function handleEmailChange(params, req, res) {
handleEmailChange: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var email = unescape(params.email) || "";
// perhaps my email regex isn't perfect, but there's no freaking way
// I'm implementing this monstrosity:
// <http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html>
if(!email.match(/^[a-z0-9_\.]+@[a-z0-9_\.]+[a-z]+$/)) {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Invalid email"
});
@ -422,7 +423,7 @@ function handleEmailChange(params, req, res) {
}
if(email.match(/.*@(localhost|127\.0\.0\.1)/i)) {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Nice try, but no."
});
@ -430,7 +431,7 @@ function handleEmailChange(params, req, res) {
}
if(pw == "") {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Password cannot be empty"
});
@ -438,29 +439,29 @@ function handleEmailChange(params, req, res) {
}
var row = Auth.login(name, pw);
if(row) {
var success = Database.setUserEmail(name, email);
ActionLog.record(getClientIP(req), name, "email-update", email);
sendJSON(res, {
var success = Server.db.setUserEmail(name, email);
ActionLog.record(getIP(req), name, "email-update", email);
this.sendJSON(res, {
success: success,
error: success ? "" : "Email update failed",
session: row.session_hash
});
}
else {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Invalid username/password"
});
}
}
},
function handleRegister(params, req, res) {
handleRegister: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
if(ActionLog.tooManyRegistrations(getClientIP(req))) {
ActionLog.record(getClientIP(req), name, "register-failure",
if(ActionLog.tooManyRegistrations(getIP(req))) {
ActionLog.record(getIP(req), name, "register-failure",
"Too many recent registrations from this IP");
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Your IP address has registered several accounts in "+
"the past 48 hours. Please wait a while or ask an "+
@ -470,25 +471,25 @@ function handleRegister(params, req, res) {
}
if(pw == "") {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "You must provide a password"
});
return;
}
else if(Auth.isRegistered(name)) {
ActionLog.record(getClientIP(req), name, "register-failure",
ActionLog.record(getIP(req), name, "register-failure",
"Name taken");
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "That username is already taken"
});
return false;
}
else if(!Auth.validateName(name)) {
ActionLog.record(getClientIP(req), name, "register-failure",
ActionLog.record(getIP(req), name, "register-failure",
"Invalid name");
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Invalid username. Usernames must be 1-20 characters long and consist only of alphanumeric characters and underscores"
});
@ -496,29 +497,29 @@ function handleRegister(params, req, res) {
else {
var session = Auth.register(name, pw);
if(session) {
ActionLog.record(getClientIP(req), name, "register-success");
Logger.syslog.log(getClientIP(req) + " registered " + name);
sendJSON(res, {
ActionLog.record(getIP(req), name, "register-success");
Logger.syslog.log(getIP(req) + " registered " + name);
this.sendJSON(res, {
success: true,
session: session
});
}
else {
sendJSON(res, {
this.sendJSON(res, {
success: false,
error: "Registration error. Contact an admin for assistance."
});
}
}
}
},
function handleAdmReports(params, req, res) {
sendJSON(res, {
handleAdmReports: function (params, req, res) {
this.sendJSON(res, {
error: "Not implemented"
});
}
},
function handleReadActionLog(params, req, res) {
handleReadActionLog: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var session = params.session || "";
@ -529,11 +530,11 @@ function handleReadActionLog(params, req, res) {
}
var actions = ActionLog.readLog();
sendJSON(res, actions);
}
this.sendJSON(res, actions);
},
// Helper function
function pipeLast(res, file, len) {
pipeLast: function (res, file, len) {
fs.stat(file, function(err, data) {
if(err) {
res.send(500);
@ -546,9 +547,9 @@ function pipeLast(res, file, len) {
var end = data.size - 1;
fs.createReadStream(file, {start: start, end: end}).pipe(res);
});
}
},
function handleReadLog(params, req, res) {
handleReadLog: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var session = params.session || "";
@ -561,16 +562,16 @@ function handleReadLog(params, req, res) {
var type = params.type || "";
if(type == "sys") {
pipeLast(res, "sys.log", 1024*1024);
this.pipeLast(res, "sys.log", 1024*1024);
}
else if(type == "err") {
pipeLast(res, "error.log", 1024*1024);
this.pipeLast(res, "error.log", 1024*1024);
}
else if(type == "channel") {
var chan = params.channel || "";
fs.exists("chanlogs/" + chan + ".log", function(exists) {
if(exists) {
pipeLast(res, "chanlogs/" + chan + ".log", 1024*1024);
this.pipeLast(res, "chanlogs/" + chan + ".log", 1024*1024);
}
else {
res.send(404);
@ -581,3 +582,5 @@ function handleReadLog(params, req, res) {
res.send(400);
}
}
};
}

View File

@ -9,10 +9,10 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
exports.MYSQL_SERVER = "";
exports.MYSQL_DB = "";
exports.MYSQL_USER = "";
exports.MYSQL_PASSWORD = "";
exports.MYSQL_SERVER = "localhost";
exports.MYSQL_DB = "syncdevel";
exports.MYSQL_USER = "syncdevel";
exports.MYSQL_PASSWORD = "tacky";
exports.IO_PORT = 1337; // Socket.IO port, DO NOT USE PORT 80.
exports.WEBSERVER_PORT = 8080; // Webserver port. Binding port 80 requires root permissions
exports.MAX_PER_IP = 10;

309
server.js
View File

@ -1,226 +1,169 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const VERSION = "2.0.5";
var fs = require("fs");
var Logger = require("./logger.js");
Logger.syslog.log("Starting CyTube v" + VERSION);
var Config = require("./config.js");
var express = require("express");
var API = require("./api.js");
var NWS = require("./notwebsocket");
var Config = require("./config");
var Logger = require("./logger");
var Channel = require("./channel");
var User = require("./user");
var app = express();
app.get("/r/:channel(*)", function(req, res, next) {
var param = req.params.channel;
if(!param.match(/^[a-zA-Z0-9-_]+$/)) {
res.redirect("/" + param);
}
else {
res.sendfile(__dirname + "/www/channel.html");
}
});
const VERSION = "2.1.0";
app.get("/api/:apireq(*)", function(req, res, next) {
API.handle(req.url.substring(5), req, res);
});
function getClientIP(req) {
var ip = false;
function getIP(req) {
var raw = req.connection.remoteAddress;
var forward = req.header("x-forwarded-for");
if(Config.REVERSE_PROXY && forward) {
ip = forward.split(",")[0];
Logger.syslog.log("/" + ip + " is proxied by /" + raw);
var ip = forward.split(",")[0];
Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return ip;
}
return raw;
}
app.get("/nws/connect", function(req, res, next) {
var socket = NWS.newConnection(req, res);
var ip = getClientIP(req);
if(Database.checkGlobalBan(ip)) {
Logger.syslog.log("Disconnecting " + ip + " - bant");
socket.emit("kick", {
reason: "You're globally banned!"
});
socket.disconnect(true);
return;
}
socket.on("disconnect", function() {
exports.clients[ip]--;
});
if(!(ip in exports.clients)) {
exports.clients[ip] = 1;
}
else {
exports.clients[ip]++;
}
if(exports.clients[ip] > Config.MAX_PER_IP) {
socket.emit("kick", {
reason: "Too many connections from your IP address"
});
socket.disconnect(true);
return;
}
var user = new User(socket, ip);
Logger.syslog.log("Accepted connection from /" + user.ip);
});
app.get("/nws/:hash/:str", function(req, res, next) {
NWS.msgReceived(req, res);
});
app.get("/:thing(*)", function(req, res, next) {
res.sendfile(__dirname + "/www/" + req.params.thing);
});
app.use(function(err, req, res, next) {
if(404 == err.status) {
res.statusCode = 404;
res.send("Page not found");
}
else {
next(err);
}
});
//app.use(express.static(__dirname + "/www"));
var httpserv = app.listen(Config.WEBSERVER_PORT);
var ioserv = express().listen(Config.IO_PORT);
exports.io = require("socket.io").listen(ioserv);
exports.io.set("log level", 1);
var User = require("./user.js").User;
var Database = require("./database.js");
Database.setup(Config);
Database.init();
var channels = {};
exports.clients = {};
fs.exists("chandump", function(exists) {
if(!exists) {
fs.mkdir("chandump", function(err) {
if(err)
Logger.errlog.log(err);
});
}
});
fs.exists("chanlogs", function(exists) {
if(!exists) {
fs.mkdir("chanlogs", function(err) {
if(err)
Logger.errlog.log(err);
});
}
});
function getSocketIP(socket) {
var raw = socket.handshake.address.address;
if(Config.REVERSE_PROXY) {
if(typeof socket.handshake.headers["x-forwarded-for"] == "string") {
var ip = socket.handshake.headers["x-forwarded-for"].split(",")[0];
Logger.syslog.log("/" + ip + " is proxied by /" + raw);
var ip = socket.handshake.headers["x-forwarded-for"]
.split(",")[0];
Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return ip;
}
}
return socket.handshake.address.address;
return raw;
}
exports.io.sockets.on("connection", function(socket) {
var Server = {
channels: [],
channelLoaded: function (name) {
for(var i in this.channels) {
if(this.channels[i].name == name)
return true;
}
return false;
},
getChannel: function (name) {
for(var i in this.channels) {
if(this.channels[i].name == name)
return this.channels[i];
}
var c = new Channel(name, this);
this.channels.push(c);
return c;
},
unloadChannel: function(chan) {
if(chan.registered)
chan.saveDump();
chan.playlist.die();
for(var i in this.channels) {
if(this.channels[i].name == chan.name) {
this.channels.splice(i, 1);
break;
}
}
for(var i in chan)
delete chan[i];
},
app: null,
io: null,
httpserv: null,
ioserv: null,
db: null,
ips: {},
init: function () {
this.app = express();
// channel path
this.app.get("/r/:channel(*)", function (req, res, next) {
var c = req.params.channel;
if(!c.match(/^[\w-_]+$/))
res.redirect("/" + c);
else
res.sendfile(__dirname + "/www/channel.html");
});
// api path
this.api = require("./api")(this);
this.app.get("/api/:apireq(*)", function (req, res, next) {
this.api.handle(req.url.substring(5), req, res);
});
// default path
this.app.get("/:thing(*)", function (req, res, next) {
res.sendfile(__dirname + "/www/" + req.params.thing);
});
// fallback
this.app.use(function (err, req, res, next) {
if(err.status == 404) {
res.send(404);
} else {
next(err);
}
});
// bind servers
this.httpserv = this.app.listen(Config.WEBSERVER_PORT);
this.ioserv = express().listen(Config.IO_PORT);
// init socket.io
this.io = require("socket.io").listen(this.ioserv);
this.io.set("log level", 1);
this.io.sockets.on("connection", function (socket) {
var ip = getSocketIP(socket);
if(Database.checkGlobalBan(ip)) {
Logger.syslog.log("Disconnecting " + ip + " - bant");
socket._ip = ip;
if(this.db.checkGlobalBan(ip)) {
Logger.syslog.log("Disconnecting " + ip + " - gbanned");
socket.emit("kick", {
reason: "You're globally banned!"
reason: "You're globally banned."
});
socket.disconnect(true);
return;
}
socket.on("disconnect", function () {
exports.clients[ip]--;
this.ips[ip]--;
});
if(!(ip in exports.clients)) {
exports.clients[ip] = 1;
}
else {
exports.clients[ip]++;
}
if(exports.clients[ip] > Config.MAX_PER_IP) {
if(!(ip in this.ips))
this.ips[ip] = 0;
this.ips[ip]++;
if(this.ips[ip] > Config.MAX_PER_IP) {
socket.emit("kick", {
reason: "Too many connections from your IP address"
});
socket.disconnect(true);
return;
}
var user = new User(socket, ip);
Logger.syslog.log("Accepted connection from /" + user.ip);
// finally a valid user
Logger.syslog.log("Accepted socket from /" + socket._ip);
new User(socket, this);
});
// init database
this.db = require("./database");
this.db.setup(Config);
this.db.init();
},
shutdown: function () {
Logger.syslog.log("Unloading channels");
for(var i in this.channels) {
if(this.channels[i].registered)
this.channels[i].saveDump();
}
Logger.syslog.log("Goodbye");
process.exit(0);
}
};
Logger.syslog.log("Starting CyTube v" + VERSION);
Server.init();
if(!Config.DEBUG) {
process.on("uncaughtException", function (err) {
Logger.errlog.log("[SEVERE] Uncaught Exception: " + err);
Logger.errlog.log(err.stack);
});
process.on("exit", shutdown);
process.on("SIGINT", shutdown);
}
function shutdown() {
Logger.syslog.log("Unloading channels...");
for(var name in channels) {
if(channels[name].registered)
channels[name].saveDump();
}
Logger.syslog.log("Shutting Down");
process.exit(0);
}
exports.getChannel = function (name) {
return channels[name];
}
exports.getAllChannels = function () {
return channels;
}
var Channel = require("./channel.js").Channel;
exports.createChannel = function (name) {
var chan = new Channel(name);
channels[name] = chan;
return chan;
}
exports.getOrCreateChannel = function (name) {
var chan = exports.getChannel(name);
if(chan !== undefined && chan.name !== undefined)
return chan;
else if(chan !== undefined && chan.name === undefined) {
Logger.errlog.log("Empty channel still loaded: ", name);
delete channels[name];
}
return exports.createChannel(name);
}
exports.unload = function(chan) {
if(chan.registered) {
chan.saveDump();
}
chan.playlist.die();
delete channels[chan.name];
for(var i in chan)
delete chan[i];
process.on("exit", Server.shutdown);
process.on("SIGINT", Server.shutdown);
}