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

259
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. 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 Auth = require("./auth");
var Server = require("./server.js"); var Logger = require("./logger");
var Logger = require("./logger.js");
var apilog = new Logger.Logger("api.log"); var apilog = new Logger.Logger("api.log");
var Database = require("./database.js"); var Config = require("./config");
var Config = require("./config.js"); var ActionLog = require("./actionlog");
var ActionLog = require("./actionlog.js");
var fs = require("fs"); var fs = require("fs");
var plainHandlers = { function getIP(req) {
"readlog" : handleReadLog var raw = req.connection.remoteAddress;
};
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;
var forward = req.header("x-forwarded-for"); var forward = req.header("x-forwarded-for");
if(Config.REVERSE_PROXY && forward) { if(Config.REVERSE_PROXY && forward) {
ip = forward.split(",")[0]; var ip = forward.split(",")[0];
} Logger.syslog.log("REVPROXY " + raw + " => " + ip);
if(!ip) {
ip = req.connection.remoteAddress;
}
return 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 parts = path.split("/");
var last = parts[parts.length - 1]; var last = parts[parts.length - 1];
var params = {}; var params = {};
@ -76,28 +75,27 @@ function handle(path, req, res) {
if(parts[0] == "json") { if(parts[0] == "json") {
res.callback = params.callback || false; res.callback = params.callback || false;
if(!(parts[1] in jsonHandlers)) { if(!(parts[1] in this.jsonHandlers)) {
res.end(JSON.stringify({ res.end(JSON.stringify({
error: "Unknown endpoint: " + parts[1] error: "Unknown endpoint: " + parts[1]
}, null, 4)); }, null, 4));
return; return;
} }
jsonHandlers[parts[1]](params, req, res); this.jsonHandlers[parts[1]](params, req, res);
} }
else if(parts[0] == "plain") { else if(parts[0] == "plain") {
if(!(parts[1] in plainHandlers)) { if(!(parts[1] in this.plainHandlers)) {
res.send(404); res.send(404);
return; return;
} }
plainHandlers[parts[1]](params, req, res); this.plainHandlers[parts[1]](params, req, res);
} }
else { else {
res.send(400); res.send(400);
} }
} },
exports.handle = handle;
function sendJSON(res, obj) { sendJSON: function (res, obj) {
var response = JSON.stringify(obj, null, 4); var response = JSON.stringify(obj, null, 4);
if(res.callback) { if(res.callback) {
response = res.callback + "(" + response + ")"; response = res.callback + "(" + response + ")";
@ -107,9 +105,9 @@ function sendJSON(res, obj) {
res.setHeader("Content-Type", "application/json"); res.setHeader("Content-Type", "application/json");
res.setHeader("Content-Length", len); res.setHeader("Content-Length", len);
res.end(response); res.end(response);
} },
function sendPlain(res, str) { sendPlain: function (res, str) {
if(res.callback) { if(res.callback) {
str = res.callback + "('" + str + "')"; str = res.callback + "('" + str + "')";
} }
@ -118,9 +116,9 @@ function sendPlain(res, str) {
res.setHeader("Content-Type", "text/plain"); res.setHeader("Content-Type", "text/plain");
res.setHeader("Content-Length", len); res.setHeader("Content-Length", len);
res.end(response); res.end(response);
} },
function handleChannelData(params, req, res) { handleChannelData: function (params, req, res) {
var clist = params.channel || ""; var clist = params.channel || "";
clist = clist.split(","); clist = clist.split(",");
var data = []; var data = [];
@ -129,9 +127,10 @@ function handleChannelData(params, req, res) {
if(!cname.match(/^[a-zA-Z0-9-_]+$/)) { if(!cname.match(/^[a-zA-Z0-9-_]+$/)) {
continue; continue;
} }
var d = { var d = {
name: cname, name: cname,
loaded: Server.getChannel(cname) !== undefined loaded: Server.channelLoaded(cname)
}; };
if(d.loaded) { if(d.loaded) {
@ -153,12 +152,12 @@ function handleChannelData(params, req, res) {
data.push(d); data.push(d);
} }
sendJSON(res, data); this.sendJSON(res, data);
} },
function handleChannelList(params, req, res) { handleChannelList: function (params, req, res) {
if(params.filter == "public") { if(params.filter == "public") {
var all = Server.getAllChannels(); var all = Server.channels;
var clist = []; var clist = [];
for(var key in all) { for(var key in all) {
if(all[key].opts.show_public) { if(all[key].opts.show_public) {
@ -176,27 +175,27 @@ function handleChannelList(params, req, res) {
return; return;
} }
var clist = []; var clist = [];
for(var key in Server.getAllChannels()) { for(var key in Server.channels) {
clist.push(key); clist.push(key);
} }
handleChannelData({channel: clist.join(",")}, req, res); handleChannelData({channel: clist.join(",")}, req, res);
} },
function handleLogin(params, req, res) { handleLogin: function (params, req, res) {
var session = params.session || ""; var session = params.session || "";
var name = params.name || ""; var name = params.name || "";
var pw = params.pw || ""; var pw = params.pw || "";
if(pw == "" && session == "") { if(pw == "" && session == "") {
if(!Auth.isRegistered(name)) { if(!Auth.isRegistered(name)) {
sendJSON(res, { this.sendJSON(res, {
success: true, success: true,
session: "" session: ""
}); });
return; return;
} }
else { else {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "That username is already taken" error: "That username is already taken"
}); });
@ -206,27 +205,27 @@ function handleLogin(params, req, res) {
var row = Auth.login(name, pw, session); var row = Auth.login(name, pw, session);
if(row) { if(row) {
ActionLog.record(getClientIP(req), name, "login-success"); ActionLog.record(getIP(req), name, "login-success");
sendJSON(res, { this.sendJSON(res, {
success: true, success: true,
session: row.session_hash session: row.session_hash
}); });
} }
else { else {
ActionLog.record(getClientIP(req), name, "login-failure"); ActionLog.record(getIP(req), name, "login-failure");
sendJSON(res, { this.sendJSON(res, {
error: "Invalid username/password", error: "Invalid username/password",
success: false success: false
}); });
} }
} },
function handlePasswordChange(params, req, res) { handlePasswordChange: function (params, req, res) {
var name = params.name || ""; var name = params.name || "";
var oldpw = params.oldpw || ""; var oldpw = params.oldpw || "";
var newpw = params.newpw || ""; var newpw = params.newpw || "";
if(oldpw == "" || newpw == "") { if(oldpw == "" || newpw == "") {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Old password and new password cannot be empty" error: "Old password and new password cannot be empty"
}); });
@ -234,34 +233,34 @@ function handlePasswordChange(params, req, res) {
} }
var row = Auth.login(name, oldpw); var row = Auth.login(name, oldpw);
if(row) { if(row) {
ActionLog.record(getClientIP(req), name, "password-change"); ActionLog.record(getIP(req), name, "password-change");
var success = Auth.setUserPassword(name, newpw); var success = Auth.setUserPassword(name, newpw);
sendJSON(res, { this.sendJSON(res, {
success: success, success: success,
error: success ? "" : "Change password failed", error: success ? "" : "Change password failed",
session: row.session_hash session: row.session_hash
}); });
} }
else { else {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Invalid username/password" error: "Invalid username/password"
}); });
} }
} },
function handlePasswordReset(params, req, res) { handlePasswordReset: function (params, req, res) {
var name = params.name || ""; var name = params.name || "";
var email = unescape(params.email || ""); var email = unescape(params.email || "");
var ip = getClientIP(req); var ip = getIP(req);
var hash = false; var hash = false;
try { try {
hash = Database.generatePasswordReset(ip, name, email); hash = Server.db.generatePasswordReset(ip, name, email);
ActionLog.record(ip, name, "password-reset-generate", email); ActionLog.record(ip, name, "password-reset-generate", email);
} }
catch(e) { catch(e) {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: e error: e
}); });
@ -269,14 +268,14 @@ function handlePasswordReset(params, req, res) {
} }
if(!Config.MAIL) { if(!Config.MAIL) {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "This server does not have email enabled. Contact an administrator" error: "This server does not have email enabled. Contact an administrator"
}); });
return; return;
} }
if(!email) { if(!email) {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "You don't have a recovery email address set. Contact an administrator" 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) { Config.MAIL.sendMail(mail, function(err, response) {
if(err) { if(err) {
Logger.errlog.log("Mail fail: " + err); Logger.errlog.log("Mail fail: " + err);
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Email failed. Contact an admin if this persists." error: "Email failed. Contact an admin if this persists."
}); });
} }
else { else {
sendJSON(res, { this.sendJSON(res, {
success: true 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 hash = params.hash || "";
var ip = getClientIP(req); var ip = getIP(req);
try { try {
var info = Database.recoverPassword(hash); var info = Server.db.recoverPassword(hash);
sendJSON(res, { this.sendJSON(res, {
success: true, success: true,
name: info[0], name: info[0],
pw: info[1] pw: info[1]
@ -340,34 +339,33 @@ function handlePasswordRecover(params, req, res) {
} }
catch(e) { catch(e) {
ActionLog.record(ip, name, "password-recover-failure"); ActionLog.record(ip, name, "password-recover-failure");
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: e error: e
}); });
} }
},
} handleProfileGet: function (params, req, res) {
function handleProfileGet(params, req, res) {
var name = params.name || ""; var name = params.name || "";
try { try {
var prof = Database.getProfile(name); var prof = Server.db.getProfile(name);
sendJSON(res, { this.sendJSON(res, {
success: true, success: true,
profile_image: prof.profile_image, profile_image: prof.profile_image,
profile_text: prof.profile_text profile_text: prof.profile_text
}); });
} }
catch(e) { catch(e) {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: e error: e
}); });
} }
} },
function handleProfileChange(params, req, res) { handleProfileChange: function (params, req, res) {
var name = params.name || ""; var name = params.name || "";
var pw = params.pw || ""; var pw = params.pw || "";
var session = params.session || ""; var session = params.session || "";
@ -376,24 +374,24 @@ function handleProfileChange(params, req, res) {
var row = Auth.login(name, pw, session); var row = Auth.login(name, pw, session);
if(!row) { if(!row) {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Invalid login" error: "Invalid login"
}); });
return; return;
} }
var result = Database.setProfile(name, { var result = Server.db.setProfile(name, {
image: img, image: img,
text: text text: text
}); });
sendJSON(res, { this.sendJSON(res, {
success: result, success: result,
error: result ? "" : "Internal error. Contact an administrator" error: result ? "" : "Internal error. Contact an administrator"
}); });
var all = Server.getAllChannels(); var all = Server.channels;
for(var n in all) { for(var n in all) {
var chan = all[n]; var chan = all[n];
for(var i = 0; i < chan.users.length; i++) { 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 name = params.name || "";
var pw = params.pw || ""; var pw = params.pw || "";
var email = unescape(params.email) || ""; 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]+$/)) { if(!email.match(/^[a-z0-9_\.]+@[a-z0-9_\.]+[a-z]+$/)) {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Invalid email" error: "Invalid email"
}); });
@ -422,7 +423,7 @@ function handleEmailChange(params, req, res) {
} }
if(email.match(/.*@(localhost|127\.0\.0\.1)/i)) { if(email.match(/.*@(localhost|127\.0\.0\.1)/i)) {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Nice try, but no." error: "Nice try, but no."
}); });
@ -430,7 +431,7 @@ function handleEmailChange(params, req, res) {
} }
if(pw == "") { if(pw == "") {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Password cannot be empty" error: "Password cannot be empty"
}); });
@ -438,29 +439,29 @@ function handleEmailChange(params, req, res) {
} }
var row = Auth.login(name, pw); var row = Auth.login(name, pw);
if(row) { if(row) {
var success = Database.setUserEmail(name, email); var success = Server.db.setUserEmail(name, email);
ActionLog.record(getClientIP(req), name, "email-update", email); ActionLog.record(getIP(req), name, "email-update", email);
sendJSON(res, { this.sendJSON(res, {
success: success, success: success,
error: success ? "" : "Email update failed", error: success ? "" : "Email update failed",
session: row.session_hash session: row.session_hash
}); });
} }
else { else {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Invalid username/password" error: "Invalid username/password"
}); });
} }
} },
function handleRegister(params, req, res) { handleRegister: function (params, req, res) {
var name = params.name || ""; var name = params.name || "";
var pw = params.pw || ""; var pw = params.pw || "";
if(ActionLog.tooManyRegistrations(getClientIP(req))) { if(ActionLog.tooManyRegistrations(getIP(req))) {
ActionLog.record(getClientIP(req), name, "register-failure", ActionLog.record(getIP(req), name, "register-failure",
"Too many recent registrations from this IP"); "Too many recent registrations from this IP");
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Your IP address has registered several accounts in "+ error: "Your IP address has registered several accounts in "+
"the past 48 hours. Please wait a while or ask an "+ "the past 48 hours. Please wait a while or ask an "+
@ -470,25 +471,25 @@ function handleRegister(params, req, res) {
} }
if(pw == "") { if(pw == "") {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "You must provide a password" error: "You must provide a password"
}); });
return; return;
} }
else if(Auth.isRegistered(name)) { else if(Auth.isRegistered(name)) {
ActionLog.record(getClientIP(req), name, "register-failure", ActionLog.record(getIP(req), name, "register-failure",
"Name taken"); "Name taken");
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "That username is already taken" error: "That username is already taken"
}); });
return false; return false;
} }
else if(!Auth.validateName(name)) { else if(!Auth.validateName(name)) {
ActionLog.record(getClientIP(req), name, "register-failure", ActionLog.record(getIP(req), name, "register-failure",
"Invalid name"); "Invalid name");
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Invalid username. Usernames must be 1-20 characters long and consist only of alphanumeric characters and underscores" 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 { else {
var session = Auth.register(name, pw); var session = Auth.register(name, pw);
if(session) { if(session) {
ActionLog.record(getClientIP(req), name, "register-success"); ActionLog.record(getIP(req), name, "register-success");
Logger.syslog.log(getClientIP(req) + " registered " + name); Logger.syslog.log(getIP(req) + " registered " + name);
sendJSON(res, { this.sendJSON(res, {
success: true, success: true,
session: session session: session
}); });
} }
else { else {
sendJSON(res, { this.sendJSON(res, {
success: false, success: false,
error: "Registration error. Contact an admin for assistance." error: "Registration error. Contact an admin for assistance."
}); });
} }
} }
} },
function handleAdmReports(params, req, res) { handleAdmReports: function (params, req, res) {
sendJSON(res, { this.sendJSON(res, {
error: "Not implemented" error: "Not implemented"
}); });
} },
function handleReadActionLog(params, req, res) { handleReadActionLog: function (params, req, res) {
var name = params.name || ""; var name = params.name || "";
var pw = params.pw || ""; var pw = params.pw || "";
var session = params.session || ""; var session = params.session || "";
@ -529,11 +530,11 @@ function handleReadActionLog(params, req, res) {
} }
var actions = ActionLog.readLog(); var actions = ActionLog.readLog();
sendJSON(res, actions); this.sendJSON(res, actions);
} },
// Helper function // Helper function
function pipeLast(res, file, len) { pipeLast: function (res, file, len) {
fs.stat(file, function(err, data) { fs.stat(file, function(err, data) {
if(err) { if(err) {
res.send(500); res.send(500);
@ -546,9 +547,9 @@ function pipeLast(res, file, len) {
var end = data.size - 1; var end = data.size - 1;
fs.createReadStream(file, {start: start, end: end}).pipe(res); fs.createReadStream(file, {start: start, end: end}).pipe(res);
}); });
} },
function handleReadLog(params, req, res) { handleReadLog: function (params, req, res) {
var name = params.name || ""; var name = params.name || "";
var pw = params.pw || ""; var pw = params.pw || "";
var session = params.session || ""; var session = params.session || "";
@ -561,16 +562,16 @@ function handleReadLog(params, req, res) {
var type = params.type || ""; var type = params.type || "";
if(type == "sys") { if(type == "sys") {
pipeLast(res, "sys.log", 1024*1024); this.pipeLast(res, "sys.log", 1024*1024);
} }
else if(type == "err") { else if(type == "err") {
pipeLast(res, "error.log", 1024*1024); this.pipeLast(res, "error.log", 1024*1024);
} }
else if(type == "channel") { else if(type == "channel") {
var chan = params.channel || ""; var chan = params.channel || "";
fs.exists("chanlogs/" + chan + ".log", function(exists) { fs.exists("chanlogs/" + chan + ".log", function(exists) {
if(exists) { if(exists) {
pipeLast(res, "chanlogs/" + chan + ".log", 1024*1024); this.pipeLast(res, "chanlogs/" + chan + ".log", 1024*1024);
} }
else { else {
res.send(404); res.send(404);
@ -580,4 +581,6 @@ function handleReadLog(params, req, res) {
else { else {
res.send(400); 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. 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_SERVER = "localhost";
exports.MYSQL_DB = ""; exports.MYSQL_DB = "syncdevel";
exports.MYSQL_USER = ""; exports.MYSQL_USER = "syncdevel";
exports.MYSQL_PASSWORD = ""; exports.MYSQL_PASSWORD = "tacky";
exports.IO_PORT = 1337; // Socket.IO port, DO NOT USE PORT 80. 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.WEBSERVER_PORT = 8080; // Webserver port. Binding port 80 requires root permissions
exports.MAX_PER_IP = 10; exports.MAX_PER_IP = 10;

315
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 express = require("express");
var API = require("./api.js"); var Config = require("./config");
var NWS = require("./notwebsocket"); var Logger = require("./logger");
var Channel = require("./channel");
var User = require("./user");
var app = express(); const VERSION = "2.1.0";
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");
}
});
app.get("/api/:apireq(*)", function(req, res, next) { function getIP(req) {
API.handle(req.url.substring(5), req, res);
});
function getClientIP(req) {
var ip = false;
var raw = req.connection.remoteAddress; var raw = req.connection.remoteAddress;
var forward = req.header("x-forwarded-for"); var forward = req.header("x-forwarded-for");
if(Config.REVERSE_PROXY && forward) { if(Config.REVERSE_PROXY && forward) {
ip = forward.split(",")[0]; var ip = forward.split(",")[0];
Logger.syslog.log("/" + ip + " is proxied by /" + raw); Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return ip; return ip;
} }
return raw; 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) { function getSocketIP(socket) {
var raw = socket.handshake.address.address; var raw = socket.handshake.address.address;
if(Config.REVERSE_PROXY) { if(Config.REVERSE_PROXY) {
if(typeof socket.handshake.headers["x-forwarded-for"] == "string") { if(typeof socket.handshake.headers["x-forwarded-for"] == "string") {
var ip = socket.handshake.headers["x-forwarded-for"].split(",")[0]; var ip = socket.handshake.headers["x-forwarded-for"]
Logger.syslog.log("/" + ip + " is proxied by /" + raw); .split(",")[0];
Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return 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); var ip = getSocketIP(socket);
if(Database.checkGlobalBan(ip)) { socket._ip = ip;
Logger.syslog.log("Disconnecting " + ip + " - bant"); if(this.db.checkGlobalBan(ip)) {
Logger.syslog.log("Disconnecting " + ip + " - gbanned");
socket.emit("kick", { socket.emit("kick", {
reason: "You're globally banned!" reason: "You're globally banned."
}); });
socket.disconnect(true); socket.disconnect(true);
return; return;
} }
socket.on("disconnect", function() {
exports.clients[ip]--; socket.on("disconnect", function () {
this.ips[ip]--;
}); });
if(!(ip in exports.clients)) {
exports.clients[ip] = 1; if(!(ip in this.ips))
} this.ips[ip] = 0;
else { this.ips[ip]++;
exports.clients[ip]++;
} if(this.ips[ip] > Config.MAX_PER_IP) {
if(exports.clients[ip] > Config.MAX_PER_IP) {
socket.emit("kick", { socket.emit("kick", {
reason: "Too many connections from your IP address" reason: "Too many connections from your IP address"
}); });
socket.disconnect(true); socket.disconnect(true);
return; 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) { if(!Config.DEBUG) {
process.on("uncaughtException", function(err) { process.on("uncaughtException", function (err) {
Logger.errlog.log("[SEVERE] Uncaught Exception: " + err); Logger.errlog.log("[SEVERE] Uncaught Exception: " + err);
Logger.errlog.log(err.stack); Logger.errlog.log(err.stack);
}); });
process.on("exit", shutdown); process.on("exit", Server.shutdown);
process.on("SIGINT", shutdown); process.on("SIGINT", Server.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];
} }