Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Create the database connection
- var db = mysql.createConnection({
- host: config.db_host,
- user: config.db_user,
- password: config.db_pass,
- database: config.db_name
- });
- if (db.connect(function() {
- // Make the database global
- global.db = db;
- var moment = require("moment"),
- colors = require("colors"),
- net = require("net"),
- fs = require("fs"),
- cluster = require("cluster"),
- session = require("./modules/session");
- /********************************************/
- /* COMMOM METHODS */
- /********************************************/
- var methods = {
- log: function() {
- // only shot the message if we are in debug mode
- if (config.debug) {
- // get the current moment in time
- var now = moment();
- // add the date and time
- arguments[0] = "[" + now.format("DD-MM-YYYY HH:mm:ss") + "] " + arguments[0];
- // apply the new arguments to the console log method
- console.log.apply(console, arguments);
- }
- },
- respond: function(socket, data, callback) {
- // Prepare the data
- data = JSON.stringify(data);
- data += "\r\n";
- // Send the data
- socket.write(data, "utf8", callback);
- }
- }
- /********************************************/
- /* MASTER THREAT */
- /********************************************/
- if (cluster.isMaster) {
- // Variable declaration
- var cpu, cmds, worker;
- var os = require("os");
- // Master command handlers
- cmds = {
- // Broadcast handler
- bc: function(data) {
- // Declare the worker variable
- var worker;
- for (var id in cluster.workers) {
- // send the data to all workers
- cluster.workers[id].send({
- cmd: "bc",
- data: data
- });
- }
- },
- // Server kill method
- kill: function() {
- // Soft-kill the workers
- for (var id in cluster.workers) {
- cluster.workers[id].kill();
- }
- // Close the master process
- process.exit(0);
- }
- };
- // Get the the available system cores
- // so we know how many workers we
- // are able to fork.
- cores = os.cpus();
- cluster.on("fork", function(worker) {
- methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Forking..", ("" + worker.process.pid).padLeft(5, "0"));
- });
- cluster.on("online", function(worker) {
- methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Online and ready to listen", ("" + worker.process.pid).padLeft(5, "0"));
- });
- cluster.on("listening", function(worker, address) {
- methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Listening to %s:%d", ("" + worker.process.pid).padLeft(5, "0"), address.address, address.port);
- });
- cluster.on("disconnect", function(worker) {
- methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Disconnected", ("" + worker.process.pid).padLeft(5, "0"));
- });
- cluster.on('exit', function(worker, code, signal) {
- // Get the exit code
- var code = worker.process.exitCode;
- if (code != 0) {
- // Log the crash and spawn a replacement worker
- methods.log("[WKR:" + "%s".cyan + "] [" + "ERROR".red + "] Crashed (exit code: %d). Spawning a replacement worker", ("" + worker.process.pid).padLeft(5, "0"), worker.process.exitCode);
- cluster.fork();
- }
- });
- // Loop trough the cores
- // and fork the threats
- for (var i = 0; i < cores.length; i++) {
- // Fork the worker
- worker = cluster.fork();
- // Create a message event so we
- // can receive data from the worker
- worker.on("message", function(msg) {
- // Get the command from the
- // message and validate it.
- if ((msg.cmd) && msg.cmd in cmds) {
- // Call the requested command and pass
- // the message data.
- cmds[msg.cmd].call(this, msg.data || null);
- }
- });
- }
- }
- /********************************************/
- /* WORKER THREAT */
- /********************************************/
- if (cluster.isWorker) {
- // Worker command handlers
- var cmds = {
- // Client authentication handler
- auth: function(data) {
- // Prepare the response data
- var response = {
- cmd: "auth",
- error: false,
- data: {}
- };
- // Expand the current scope
- var self = this;
- // Check if the username and password are set
- if (data.username && data.password) {
- // Check if this is a valid user
- db.query("SELECT id, firstname, lastname, online_at FROM user WHERE username = ? AND password = ? LIMIT 1", [data.username, data.password], function(error, result){
- // Create the new user session
- session.create(function(id){
- // Map the user data to the session
- session.set(id, { user: result}, function(){
- // The mapping is complete, and the user session is created
- methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Session: %s created", ("" + process.pid).padLeft(5, "0"), id);
- // Now send the auth response to the device
- response.data = {
- session: id,
- user: result[0]
- };
- // Convert the response to string and send it to the device
- methods.respond(self, response);
- });
- });
- });
- } else {
- response.error = {
- code: 1
- };
- // Send the response to the device
- methods.respond(this, response);
- }
- },
- wall: function(data) {
- // Prepare the response data
- var response = {
- cmd: "wall",
- error: false,
- data: {}
- };
- // Expand the current scope
- var self = this;
- // Check if we have a session id
- if (data && "session" in data) {
- // Get the user from the session id
- session.get(data.session, function(result){
- // Declare the result size boundairies
- data.offset = data.offset || 0;
- data.limit = data.limit || 50;
- // Run the user select query
- db.query("SELECT id, firstname, lastname, online_at FROM user LIMIT ?, ?", [data.offset, data.limit], function(error, result){
- if(!error && result) {
- // Bind the result data to the response
- response.data = result;
- //Convert the response to JSON and send it to the devices
- methods.respond(self, response);
- }
- });
- });
- } else {
- response.error = {
- code: 1
- };
- methods.respond(this, response);
- }
- },
- // This is the chat handler. We will send
- // the chat message to the destination socket or
- // store it in the database for future synchronization.
- chat: function(data) {
- // Prepare the response data
- var response = {
- cmd: "wall",
- error: false,
- data: {}
- };
- // Expand the current scope
- var self = this;
- this.write(data.msg);
- },
- create: function(data) {
- // Prepare the response data
- var response = {
- cmd: "create",
- error: false,
- data: {}
- };
- // Expand the current scope
- var self = this;
- if(!data || !("session" in data)) {
- response.error = {
- code: 1,
- label: "invalid_data"
- }
- return methods.respond(this, response);
- }
- if(!session.exists(data.session)) {
- response.error = {
- code: 2,
- label: "undefined_session"
- }
- return methods.respond(this, response);
- }
- // Get the user data from the session result
- session.get(data.session, function(result){
- var user = result.user;
- console.log(user);
- });
- },
- join: function(data) {
- // Prepare the response data
- var response = {
- cmd: "wall",
- error: false,
- data: {}
- };
- // Expand the current scope
- var self = this;
- if(data && "session" in data) {
- }
- },
- leave: function() {
- },
- bc: function(data) {
- // We send a broadcast request to
- // master threat. And return the result
- process.send({
- cmd: "bc",
- data: data
- });
- },
- kill: function() {
- // Send the kill command to the master process
- // This command is only allowed when the server runs
- // in debug mode
- if (config.debug) {
- process.send({
- cmd: "kill"
- });
- }
- },
- time: function() {
- // Get the local and utc time
- var local = moment(), utc = local.utc();
- // Create the time response
- var response = {
- cmd: "time",
- error: false,
- data: {
- local: local.format("X"),
- utc: utc.format("X")
- }
- };
- methods.respond(this, response);
- },
- ping: function() {
- // Create the ping response
- var response = {
- cmd: "pong",
- error: false
- };
- // Encode the response to JSON
- methods.respond(this, response);
- },
- image: function(data) {
- fs.writeFile("test.jpg", data.image, "base64", function(err) {
- });
- }
- };
- // Create a new server instance
- var server = new net.Server();
- // Change the maximum allowed event listeners
- server.setMaxListeners(0);
- server.on("connection", function(socket) {
- socket.key = socket.remoteAddress + ":" + socket.remotePort;
- // We have a new connection
- methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Socket %s connected", ("" + process.pid).padLeft(5, "0"), socket.remoteAddress);
- socket.setEncoding("utf8");
- socket.setKeepAlive(true);
- socket.setTimeout(60000, function(){
- methods.log("timeout!");
- });
- var buffer = "";
- var message = "";
- var messages = [];
- // Create the on data receive event
- socket.on("data", function(data) {
- // Strip the data
- data = data.replace(/\\/gi, '');
- data = data.replace(/^\r\n/, '');
- // Append the data to the buffer
- buffer += data;
- // Match the buffer
- if(messages = buffer.match(/(.+)(?=\r\n)/g)) {
- //buffer.replace()
- for(var i in messages) {
- // Get the current message
- message = messages[i];
- // Remove the message from the buffer
- buffer = buffer.replace(message + "\r\n", "");
- try {
- // Try to parse the JSON data
- message = JSON.parse(message);
- // Get the command from the
- // message and validate it.
- if ((message.cmd) && message.cmd in cmds) {
- methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Running command: %s", ("" + process.pid).padLeft(5, "0"), message.cmd);
- try {
- // Call the requested command and pass the message data.
- cmds[message.cmd].call(socket, message.data || null);
- } catch(error) {
- methods.log(error);
- // We have a command run error
- //methods.log("[WKR:" + "%s".cyan + "] [" + "ERROR".red + "] There was a problem when performing the command: %s", ("" + process.pid).padLeft(5, "0"), message.cmd)
- }
- }
- } catch(error) {
- // We have a JSON parse error
- methods.log("[WKR:" + "%s".cyan + "] [" + "ERROR".red + "] JSON parse error", ("" + process.pid).padLeft(5, "0"));
- }
- }
- }
- });
- socket.on('close', function () {
- console.log("SOCKET HAS BEEN CLOSED :" + socket.key);
- socket.destroy();
- });
- // Create the connection end event
- socket.on("end", function() {
- socket.destroy();
- methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Socket disconnect", ("" + process.pid).padLeft(5, "0"));
- });
- // Output any socket errors
- socket.on("error", function(error) {
- methods.log(error);
- });
- });
- // output the errors
- server.on("error", methods.log);
- // Start the listening
- server.listen(config.port, config.host);
- }
- }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement