sync/lib/database.js

595 lines
16 KiB
JavaScript
Raw Normal View History

2013-08-12 14:34:57 +00:00
var mysql = require("mysql");
var bcrypt = require("bcrypt");
var $util = require("./utilities");
2013-08-18 01:22:34 +00:00
var Logger = require("./logger");
2014-01-22 23:11:26 +00:00
var Config = require("./config");
2014-02-01 18:41:06 +00:00
var Server = require("./server");
var tables = require("./database/tables");
2014-05-21 02:30:14 +00:00
var net = require("net");
var util = require("./utilities");
2013-06-03 22:37:30 +00:00
2013-12-12 22:28:30 +00:00
var pool = null;
var global_ipbans = {};
2014-01-22 23:11:26 +00:00
module.exports.init = function () {
2013-12-12 22:28:30 +00:00
pool = mysql.createPool({
2014-01-22 23:11:26 +00:00
host: Config.get("mysql.server"),
user: Config.get("mysql.user"),
password: Config.get("mysql.password"),
database: Config.get("mysql.database"),
multipleStatements: true,
charset: "UTF8MB4_GENERAL_CI" // Needed for emoji and other non-BMP unicode
2013-08-12 14:34:57 +00:00
});
2013-06-03 22:37:30 +00:00
2013-08-12 14:34:57 +00:00
// Test the connection
2013-12-12 22:28:30 +00:00
pool.getConnection(function (err, conn) {
2013-08-12 14:34:57 +00:00
if(err) {
Logger.errlog.log("! DB connection failed");
2014-03-09 16:42:45 +00:00
Logger.errlog.log(err);
return;
2013-10-09 23:10:26 +00:00
} else {
tables.init(module.exports.query, function (err) {
if (err) {
return;
}
require("./database/update").checkVersion();
module.exports.loadAnnouncement();
});
2013-12-12 22:28:30 +00:00
// Refresh global IP bans
2013-12-14 02:39:21 +00:00
module.exports.listGlobalBans();
2013-08-12 14:34:57 +00:00
}
});
2013-08-12 14:58:21 +00:00
2013-12-12 22:28:30 +00:00
global_ipbans = {};
2013-12-12 23:09:49 +00:00
module.exports.users = require("./database/accounts");
2013-12-14 00:52:13 +00:00
module.exports.channels = require("./database/channels");
2013-08-12 14:34:57 +00:00
};
2013-12-14 02:39:21 +00:00
/**
* Execute a database query
*/
2013-12-12 22:28:30 +00:00
module.exports.query = function (query, sub, callback) {
2013-08-12 14:34:57 +00:00
// 2nd argument is optional
2013-12-14 02:39:21 +00:00
if (typeof sub === "function") {
2013-08-12 14:34:57 +00:00
callback = sub;
sub = false;
}
2013-12-14 02:39:21 +00:00
if (typeof callback !== "function") {
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
2013-12-12 22:28:30 +00:00
pool.getConnection(function (err, conn) {
2013-12-14 02:39:21 +00:00
if (err) {
Logger.errlog.log("! DB connection failed: " + err);
2013-08-12 14:34:57 +00:00
callback("Database failure", null);
} else {
function cback(err, res) {
2013-12-14 02:39:21 +00:00
if (err) {
Logger.errlog.log("! DB query failed: " + query);
2013-12-14 02:39:21 +00:00
if (sub) {
Logger.errlog.log("Substitutions: " + sub);
2013-12-14 02:39:21 +00:00
}
Logger.errlog.log(err);
2013-08-12 14:34:57 +00:00
callback("Database failure", null);
} else {
callback(null, res);
}
2014-01-22 05:29:26 +00:00
conn.release();
2013-06-03 22:37:30 +00:00
}
2013-12-14 02:39:21 +00:00
if (sub) {
2013-08-12 14:34:57 +00:00
conn.query(query, sub, cback);
2013-08-18 17:21:34 +00:00
} else {
2013-08-12 14:34:57 +00:00
conn.query(query, cback);
}
}
});
};
2013-08-21 00:56:03 +00:00
2013-12-27 03:15:54 +00:00
/**
* Dummy function to be used as a callback when none is provided
*/
2013-08-21 00:56:03 +00:00
function blackHole() {
}
2013-08-12 14:58:21 +00:00
/* REGION global bans */
2013-12-14 02:39:21 +00:00
/**
* Check if an IP address is globally banned
*/
2013-12-12 22:28:30 +00:00
module.exports.isGlobalIPBanned = function (ip, callback) {
2014-05-21 02:30:14 +00:00
var range = util.getIPRange(ip);
var wrange = util.getWideIPRange(ip);
2013-12-12 22:28:30 +00:00
var banned = ip in global_ipbans ||
2014-05-21 02:30:14 +00:00
range in global_ipbans ||
wrange in global_ipbans;
2014-05-21 02:30:14 +00:00
if (callback) {
callback(null, banned);
}
return banned;
2013-08-12 14:34:57 +00:00
};
2013-06-18 03:57:29 +00:00
2013-12-14 02:39:21 +00:00
/**
* Retrieve all global bans from the database.
* Cache locally in global_bans
*/
module.exports.listGlobalBans = function (callback) {
if (typeof callback !== "function") {
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
2013-08-13 03:23:10 +00:00
2013-12-12 22:28:30 +00:00
module.exports.query("SELECT * FROM global_bans WHERE 1", function (err, res) {
2013-12-14 02:39:21 +00:00
if (err) {
2013-08-12 14:58:21 +00:00
callback(err, null);
return;
}
2013-12-12 22:28:30 +00:00
global_ipbans = {};
2013-12-14 02:39:21 +00:00
for (var i = 0; i < res.length; i++) {
global_ipbans[res[i].ip] = res[i];
2013-08-12 14:58:21 +00:00
}
2013-12-12 22:28:30 +00:00
callback(null, global_ipbans);
2013-08-12 14:58:21 +00:00
});
};
2013-12-14 02:39:21 +00:00
/**
* Globally ban by IP
*/
module.exports.globalBanIP = function (ip, reason, callback) {
if (typeof callback !== "function") {
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
2013-08-13 03:23:10 +00:00
2013-12-14 02:39:21 +00:00
var query = "INSERT INTO global_bans (ip, reason) VALUES (?, ?)" +
" ON DUPLICATE KEY UPDATE reason=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [ip, reason, reason], function (err, res) {
2013-08-12 14:58:21 +00:00
if(err) {
callback(err, null);
return;
}
2013-12-14 02:39:21 +00:00
module.exports.listGlobalBans();
2013-08-12 14:58:21 +00:00
callback(null, res);
});
};
2013-12-14 02:39:21 +00:00
/**
* Remove a global IP ban
*/
module.exports.globalUnbanIP = function (ip, callback) {
if (typeof callback !== "function") {
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
2013-08-13 03:23:10 +00:00
2013-08-12 14:58:21 +00:00
var query = "DELETE FROM global_bans WHERE ip=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [ip], function (err, res) {
2013-08-12 14:58:21 +00:00
if(err) {
callback(err, null);
return;
}
2013-12-14 02:39:21 +00:00
module.exports.listGlobalBans();
2013-08-12 14:58:21 +00:00
callback(null, res);
});
};
/* END REGION */
/* password recovery */
2014-02-01 19:03:08 +00:00
/**
* Deletes recovery rows older than the given time
*/
module.exports.cleanOldPasswordResets = function (callback) {
if (typeof callback === "undefined") {
callback = blackHole;
}
var query = "DELETE FROM aliases WHERE time < ?";
module.exports.query(query, [Date.now() - 24*60*60*1000], callback);
};
module.exports.addPasswordReset = function (data, cb) {
if (typeof cb !== "function") {
cb = blackHole;
}
var ip = data.ip || "";
var name = data.name;
var email = data.email;
var hash = data.hash;
var expire = data.expire;
if (!name || !hash) {
cb("Internal error: Must provide name and hash to insert a new password reset", null);
return;
}
module.exports.query("INSERT INTO `password_reset` (`ip`, `name`, `email`, `hash`, `expire`) " +
"VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE ip=?, hash=?, email=?, expire=?",
[ip, name, email, hash, expire, ip, hash, email, expire], cb);
};
2014-02-01 19:03:08 +00:00
module.exports.lookupPasswordReset = function (hash, cb) {
if (typeof cb !== "function") {
return;
}
module.exports.query("SELECT * FROM `password_reset` WHERE hash=?", [hash],
function (err, rows) {
if (err) {
cb(err, null);
} else if (rows.length === 0) {
cb("Invalid password reset link", null);
} else {
cb(null, rows[0]);
}
});
};
module.exports.deletePasswordReset = function (hash) {
module.exports.query("DELETE FROM `password_reset` WHERE hash=?", [hash]);
};
2013-12-14 02:39:21 +00:00
/*
2013-12-12 22:28:30 +00:00
module.exports.genPasswordReset = function (ip, name, email, callback) {
if(typeof callback !== "function")
callback = blackHole;
var query = "SELECT email FROM registrations WHERE uname=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [name], function (err, res) {
if(err) {
callback(err, null);
return;
}
if(res.length == 0) {
callback("Provided username does not exist", null);
return;
}
if(res[0].email != email) {
callback("Provided email does not match user's email", null);
return;
}
var hash = hashlib.sha256($util.randomSalt(32) + name);
var expire = Date.now() + 24*60*60*1000;
query = "INSERT INTO password_reset " +
"(ip, name, hash, email, expire) VALUES (?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE hash=?, expire=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [ip, name, hash, email, expire, hash, expire],
function (err, res) {
if(err) {
callback(err, null);
return;
}
callback(null, hash);
});
});
};
2013-12-12 22:28:30 +00:00
module.exports.recoverUserPassword = function (hash, callback) {
if(typeof callback !== "function")
callback = blackHole;
var query = "SELECT * FROM password_reset WHERE hash=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [hash], function (err, res) {
if(err) {
callback(err, null);
return;
}
2013-09-03 17:49:02 +00:00
if(res.length == 0) {
callback("Invalid password reset link", null);
return;
}
if(Date.now() > res[0].expire) {
2013-12-12 22:28:30 +00:00
module.exports.query("DELETE FROM password_reset WHERE hash=?", [hash]);
callback("Link expired. Password resets are valid for 24hr",
null);
return;
}
var name = res[0].name;
2013-12-12 22:28:30 +00:00
resetUserPassword(res[0].name, function (err, pw) {
if(err) {
callback(err, null);
return;
}
2013-12-12 22:28:30 +00:00
module.exports.query("DELETE FROM password_reset WHERE hash=?", [hash]);
callback(null, {
name: name,
pw: pw
});
});
});
};
2013-12-12 22:28:30 +00:00
module.exports.resetUserPassword = function (name, callback) {
if(typeof callback !== "function")
callback = blackHole;
var pwChars = "abcdefghijkmnopqrstuvwxyz023456789";
var pw = "";
for(var i = 0; i < 10; i++)
pw += pwChars[parseInt(Math.random() * 33)];
bcrypt.hash(pw, 10, function (err, data) {
if(err) {
Logger.errlog.log("bcrypt error: " + err);
callback("Password reset failure", null);
return;
}
var query = "UPDATE registrations SET pw=? WHERE uname=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [data, name], function (err, res) {
if(err) {
callback(err, null);
return;
}
callback(null, pw);
});
});
};
2013-12-14 02:39:21 +00:00
*/
/* user playlists */
2013-12-14 02:39:21 +00:00
/**
* Retrieve all of a user's playlists
*/
2013-12-12 22:28:30 +00:00
module.exports.listUserPlaylists = function (name, callback) {
2013-12-14 02:39:21 +00:00
if (typeof callback !== "function") {
return;
2013-12-14 02:39:21 +00:00
}
2013-12-14 02:39:21 +00:00
var query = "SELECT name, count, duration FROM user_playlists WHERE user=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [name], callback);
};
2013-12-14 02:39:21 +00:00
/**
* Retrieve a user playlist by (user, name) pair
*/
2013-12-12 22:28:30 +00:00
module.exports.getUserPlaylist = function (username, plname, callback) {
2013-12-14 02:39:21 +00:00
if (typeof callback !== "function") {
return;
2013-12-14 02:39:21 +00:00
}
var query = "SELECT contents FROM user_playlists WHERE " +
"user=? AND name=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [username, plname], function (err, res) {
2013-12-14 02:39:21 +00:00
if (err) {
callback(err, null);
return;
}
2013-12-14 02:39:21 +00:00
if (res.length == 0) {
callback("Playlist does not exist", null);
return;
}
var pl = null;
try {
pl = JSON.parse(res[0].contents);
} catch(e) {
callback("Malformed playlist JSON", null);
return;
}
callback(null, pl);
});
};
2013-12-14 02:39:21 +00:00
/**
* Saves a user playlist. Overwrites if the playlist keyed by
* (user, name) already exists
*/
module.exports.saveUserPlaylist = function (pl, username, plname, callback) {
if (typeof callback !== "function") {
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
var tmp = [], time = 0;
for(var i in pl) {
var e = {
id: pl[i].media.id,
title: pl[i].media.title,
seconds: pl[i].media.seconds || 0,
type: pl[i].media.type,
meta: {
codec: pl[i].media.meta.codec,
bitrate: pl[i].media.meta.bitrate
}
};
time += pl[i].media.seconds || 0;
tmp.push(e);
}
var count = tmp.length;
var plText = JSON.stringify(tmp);
var query = "INSERT INTO user_playlists VALUES (?, ?, ?, ?, ?) " +
2013-12-14 02:39:21 +00:00
"ON DUPLICATE KEY UPDATE contents=?, count=?, duration=?";
var params = [username, plname, plText, count, time,
plText, count, time];
2013-12-12 22:28:30 +00:00
module.exports.query(query, params, callback);
};
2013-12-14 02:39:21 +00:00
/**
* Deletes a user playlist
*/
module.exports.deleteUserPlaylist = function (username, plname, callback) {
if (typeof callback !== "function") {
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
var query = "DELETE FROM user_playlists WHERE user=? AND name=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [username, plname], callback);
};
/* aliases */
2013-12-14 02:39:21 +00:00
/**
* Records a user or guest login in the aliases table
*/
2013-12-12 22:28:30 +00:00
module.exports.recordVisit = function (ip, name, callback) {
2013-12-14 02:39:21 +00:00
if (typeof callback !== "function") {
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
var time = Date.now();
var query = "DELETE FROM aliases WHERE ip=? AND name=?;" +
"INSERT INTO aliases VALUES (NULL, ?, ?, ?)";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [ip, name, ip, name, time], callback);
};
2013-12-14 02:39:21 +00:00
/**
* Deletes alias rows older than the given time
*/
2013-12-12 22:28:30 +00:00
module.exports.cleanOldAliases = function (expiration, callback) {
2013-12-14 02:39:21 +00:00
if (typeof callback === "undefined") {
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
var query = "DELETE FROM aliases WHERE time < ?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [Date.now() - expiration], callback);
};
2013-12-14 02:39:21 +00:00
/**
* Retrieves a list of aliases for an IP address
*/
module.exports.getAliases = function (ip, callback) {
if (typeof callback !== "function") {
return;
2013-12-14 02:39:21 +00:00
}
var query = "SELECT name,time FROM aliases WHERE ip";
2013-12-14 02:39:21 +00:00
// if the ip parameter is a /24 range, we want to match accordingly
2014-05-21 02:30:14 +00:00
if (ip.match(/^\d+\.\d+\.\d+$/) || ip.match(/^\d+\.\d+$/)) {
2013-08-18 22:58:16 +00:00
query += " LIKE ?";
ip += ".%";
2014-05-21 02:30:14 +00:00
} else if (ip.match(/^(?:[0-9a-f]{4}:){3}[0-9a-f]{4}$/) ||
ip.match(/^(?:[0-9a-f]{4}:){2}[0-9a-f]{4}$/)) {
query += " LIKE ?";
ip += ":%";
2013-08-18 22:58:16 +00:00
} else {
query += "=?";
}
query += " ORDER BY time DESC LIMIT 5";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [ip], function (err, res) {
var names = null;
if(!err) {
2013-12-14 02:39:21 +00:00
names = res.map(function (row) { return row.name; });
}
callback(err, names);
});
};
2013-12-14 02:39:21 +00:00
/**
* Retrieves a list of IPs that a name as logged in from
*/
module.exports.getIPs = function (name, callback) {
if (typeof callback !== "function") {
return;
2013-12-14 02:39:21 +00:00
}
var query = "SELECT ip FROM aliases WHERE name=?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [name], function (err, res) {
var ips = null;
if(!err) {
2013-12-14 02:39:21 +00:00
ips = res.map(function (row) { return row.ip; });
}
callback(err, ips);
});
};
/* END REGION */
2013-08-15 22:44:22 +00:00
/* REGION stats */
2013-12-14 02:39:21 +00:00
module.exports.addStatPoint = function (time, ucount, ccount, mem, callback) {
if (typeof callback !== "function") {
2013-08-17 23:44:48 +00:00
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
2013-08-17 23:44:48 +00:00
var query = "INSERT INTO stats VALUES (?, ?, ?, ?)";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [time, ucount, ccount, mem], callback);
2013-08-17 23:44:48 +00:00
};
2013-12-12 22:28:30 +00:00
module.exports.pruneStats = function (before, callback) {
2013-12-14 02:39:21 +00:00
if (typeof callback !== "function") {
2013-08-17 23:44:48 +00:00
callback = blackHole;
2013-12-14 02:39:21 +00:00
}
2013-08-17 23:44:48 +00:00
var query = "DELETE FROM stats WHERE time < ?";
2013-12-12 22:28:30 +00:00
module.exports.query(query, [before], callback);
2013-08-17 23:44:48 +00:00
};
2013-12-12 22:28:30 +00:00
module.exports.listStats = function (callback) {
2013-12-14 02:39:21 +00:00
if (typeof callback !== "function") {
return;
2013-12-14 02:39:21 +00:00
}
var query = "SELECT * FROM stats ORDER BY time ASC";
2013-12-12 22:28:30 +00:00
module.exports.query(query, callback);
};
2013-08-15 22:44:22 +00:00
/* END REGION */
2014-02-01 18:41:06 +00:00
/* Misc */
module.exports.loadAnnouncement = function () {
var query = "SELECT * FROM `meta` WHERE `key`='announcement'";
module.exports.query(query, function (err, rows) {
if (err) {
return;
}
if (rows.length === 0) {
return;
}
var announcement = rows[0].value;
try {
announcement = JSON.parse(announcement);
} catch (e) {
Logger.errlog.log("Invalid announcement data in database: " +
announcement.value);
module.exports.clearAnnouncement();
return;
}
var sv = Server.getServer();
sv.announcement = announcement;
for (var id in sv.ioServers) {
sv.ioServers[id].sockets.emit("announcement", announcement);
2014-02-01 18:41:06 +00:00
}
});
};
module.exports.setAnnouncement = function (data) {
var query = "INSERT INTO `meta` (`key`, `value`) VALUES ('announcement', ?) " +
"ON DUPLICATE KEY UPDATE `value`=?";
var repl = JSON.stringify(data);
module.exports.query(query, [repl, repl]);
};
module.exports.clearAnnouncement = function () {
module.exports.query("DELETE FROM `meta` WHERE `key`='announcement'");
};