Advertisement
Guest User

Untitled

a guest
Nov 10th, 2013
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Create the database connection
  2. var db = mysql.createConnection({
  3.     host: config.db_host,
  4.     user: config.db_user,
  5.     password: config.db_pass,
  6.     database: config.db_name
  7. });
  8.  
  9. if (db.connect(function() {
  10.     // Make the database global
  11.     global.db = db;
  12.    
  13.     var moment = require("moment"),
  14.         colors = require("colors"),
  15.         net = require("net"),
  16.         fs  = require("fs"),
  17.         cluster = require("cluster"),
  18.         session = require("./modules/session");
  19.        
  20.     /********************************************/
  21.     /* COMMOM METHODS                           */
  22.     /********************************************/
  23.     var methods = {
  24.         log: function() {
  25.             // only shot the message if we are in debug mode
  26.             if (config.debug) {
  27.                 // get the current moment in time
  28.                 var now = moment();
  29.                 // add the date and time
  30.                 arguments[0] = "[" + now.format("DD-MM-YYYY HH:mm:ss") + "] " + arguments[0];
  31.                 // apply the new arguments to the console log method
  32.                 console.log.apply(console, arguments);
  33.             }
  34.         },
  35.        
  36.         respond: function(socket, data, callback) {
  37.             // Prepare the data
  38.             data  = JSON.stringify(data);
  39.             data += "\r\n";
  40.            
  41.             // Send the data
  42.             socket.write(data, "utf8", callback);
  43.         }
  44.     }
  45.    
  46.     /********************************************/
  47.     /* MASTER THREAT                            */
  48.     /********************************************/
  49.     if (cluster.isMaster) {
  50.        
  51.         // Variable declaration
  52.         var cpu, cmds, worker;
  53.         var os = require("os");
  54.        
  55.         // Master command handlers
  56.         cmds = {
  57.             // Broadcast handler
  58.             bc: function(data) {
  59.                 // Declare the worker variable
  60.                 var worker;
  61.                 for (var id in cluster.workers) {
  62.                     // send the data to all workers
  63.                     cluster.workers[id].send({
  64.                         cmd: "bc",
  65.                         data: data
  66.                     });
  67.                 }
  68.             },
  69.            
  70.             // Server kill method
  71.             kill: function() {
  72.                 // Soft-kill the workers
  73.                 for (var id in cluster.workers) {
  74.                     cluster.workers[id].kill();
  75.                 }
  76.                 // Close the master process
  77.                 process.exit(0);
  78.             }
  79.         };
  80.        
  81.         // Get the the available system cores
  82.         // so we know how many workers we
  83.         // are able to fork.
  84.         cores = os.cpus();
  85.        
  86.         cluster.on("fork", function(worker) {
  87.             methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Forking..", ("" + worker.process.pid).padLeft(5, "0"));
  88.         });
  89.        
  90.         cluster.on("online", function(worker) {
  91.             methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Online and ready to listen", ("" + worker.process.pid).padLeft(5, "0"));
  92.         });
  93.        
  94.         cluster.on("listening", function(worker, address) {
  95.             methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Listening to %s:%d", ("" + worker.process.pid).padLeft(5, "0"), address.address, address.port);
  96.         });
  97.        
  98.         cluster.on("disconnect", function(worker) {
  99.             methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Disconnected", ("" + worker.process.pid).padLeft(5, "0"));
  100.         });
  101.        
  102.         cluster.on('exit', function(worker, code, signal) {
  103.             // Get the exit code
  104.             var code = worker.process.exitCode;
  105.             if (code != 0) {
  106.                 // Log the crash and spawn a replacement worker
  107.                 methods.log("[WKR:" + "%s".cyan + "] [" + "ERROR".red + "] Crashed (exit code: %d). Spawning a replacement worker", ("" + worker.process.pid).padLeft(5, "0"), worker.process.exitCode);
  108.                 cluster.fork();
  109.             }
  110.         });
  111.         // Loop trough the cores
  112.         // and fork the threats
  113.         for (var i = 0; i < cores.length; i++) {
  114.             // Fork the worker
  115.             worker = cluster.fork();
  116.             // Create a message event so we
  117.             // can receive data from the worker
  118.             worker.on("message", function(msg) {
  119.                 // Get the command from the
  120.                 // message and validate it.
  121.                 if ((msg.cmd) && msg.cmd in cmds) {
  122.                     // Call the requested command and pass
  123.                     // the message data.
  124.                     cmds[msg.cmd].call(this, msg.data || null);
  125.                 }
  126.             });
  127.         }
  128.     }
  129.      
  130.     /********************************************/
  131.     /* WORKER THREAT                            */
  132.     /********************************************/
  133.     if (cluster.isWorker) {      
  134.         // Worker command handlers
  135.         var cmds = {
  136.             // Client authentication handler
  137.             auth: function(data) {
  138.                 // Prepare the response data
  139.                 var response = {
  140.                     cmd: "auth",
  141.                     error: false,
  142.                     data: {}
  143.                 };
  144.                 // Expand the current scope
  145.                 var self = this;
  146.                 // Check if the username and password are set
  147.                 if (data.username && data.password) {
  148.                     // Check if this is a valid user
  149.                     db.query("SELECT id, firstname, lastname, online_at FROM user WHERE username = ? AND password = ? LIMIT 1", [data.username, data.password], function(error, result){
  150.                         // Create the new user session
  151.                         session.create(function(id){
  152.                             // Map the user data to the session
  153.                             session.set(id, { user: result}, function(){
  154.                                 // The mapping is complete, and the user session is created
  155.                                 methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Session: %s created", ("" + process.pid).padLeft(5, "0"), id);
  156.                                 // Now send the auth response to the device
  157.                                 response.data = {
  158.                                     session: id,
  159.                                     user: result[0]
  160.                                 };
  161.                                 // Convert the response to string and send it to the device
  162.                                 methods.respond(self, response);
  163.                             });
  164.                         });
  165.                     });
  166.                 } else {
  167.                     response.error = {
  168.                         code: 1
  169.                     };
  170.                     // Send the response to the device
  171.                     methods.respond(this, response);
  172.                 }
  173.             },
  174.            
  175.             wall: function(data) {
  176.                 // Prepare the response data
  177.                 var response = {
  178.                     cmd: "wall",
  179.                     error: false,
  180.                     data: {}
  181.                 };
  182.                 // Expand the current scope
  183.                 var self = this;
  184.                 // Check if we have a session id
  185.                 if (data && "session" in data) {
  186.                     // Get the user from the session id
  187.                     session.get(data.session, function(result){
  188.                         // Declare the result size boundairies
  189.                         data.offset = data.offset || 0;
  190.                         data.limit  = data.limit || 50;
  191.                         // Run the user select query
  192.                         db.query("SELECT id, firstname, lastname, online_at FROM user LIMIT ?, ?", [data.offset, data.limit], function(error, result){
  193.                             if(!error && result) {
  194.                                 // Bind the result data to the response
  195.                                 response.data = result;
  196.                                 //Convert the response to JSON and send it to the devices
  197.                                 methods.respond(self, response);
  198.                             }
  199.                         });
  200.                     });
  201.                 } else {
  202.                     response.error = {
  203.                         code: 1
  204.                     };
  205.                    
  206.                     methods.respond(this, response);
  207.                 }
  208.             },
  209.            
  210.             // This is the chat handler. We will send
  211.             // the chat message to the destination socket or
  212.             // store it in the database for future synchronization.
  213.             chat: function(data) {
  214.                 // Prepare the response data
  215.                 var response = {
  216.                     cmd: "wall",
  217.                     error: false,
  218.                     data: {}
  219.                 };
  220.                 // Expand the current scope
  221.                 var self = this;
  222.              
  223.                 this.write(data.msg);
  224.             },
  225.            
  226.             create: function(data) {
  227.                 // Prepare the response data
  228.                 var response = {
  229.                     cmd: "create",
  230.                     error: false,
  231.                     data: {}
  232.                 };
  233.                 // Expand the current scope
  234.                 var self = this;
  235.                
  236.                 if(!data || !("session" in data)) {
  237.                    
  238.                     response.error = {
  239.                         code: 1,
  240.                         label: "invalid_data"
  241.                     }
  242.                    
  243.                     return methods.respond(this, response);
  244.                 }
  245.                
  246.                 if(!session.exists(data.session)) {
  247.                    
  248.                     response.error = {
  249.                         code: 2,
  250.                         label: "undefined_session"
  251.                     }
  252.                    
  253.                     return methods.respond(this, response);
  254.                 }
  255.                
  256.                 // Get the user data from the session result
  257.                 session.get(data.session, function(result){
  258.                    
  259.                     var user = result.user;
  260.                    
  261.                     console.log(user);
  262.                 });
  263.             },
  264.            
  265.             join: function(data) {
  266.                 // Prepare the response data
  267.                 var response = {
  268.                     cmd: "wall",
  269.                     error: false,
  270.                     data: {}
  271.                 };
  272.                 // Expand the current scope
  273.                 var self = this;
  274.                
  275.                 if(data && "session" in data) {
  276.                    
  277.                 }
  278.             },
  279.            
  280.             leave: function() {
  281.                
  282.             },
  283.            
  284.             bc: function(data) {
  285.                 // We send a broadcast request to
  286.                 // master threat. And return the result
  287.                 process.send({
  288.                     cmd: "bc",
  289.                     data: data
  290.                 });
  291.             },
  292.            
  293.             kill: function() {
  294.                 // Send the kill command to the master process
  295.                 // This command is only allowed when the server runs
  296.                 // in debug mode
  297.                 if (config.debug) {
  298.                     process.send({
  299.                         cmd: "kill"
  300.                     });
  301.                 }
  302.             },
  303.            
  304.             time: function() {
  305.                 // Get the local and utc time
  306.                 var local = moment(), utc = local.utc();
  307.                
  308.                 // Create the time response
  309.                 var response = {
  310.                     cmd: "time",
  311.                     error: false,
  312.                     data: {
  313.                         local: local.format("X"),
  314.                         utc: utc.format("X")
  315.                     }
  316.                 };
  317.                
  318.                 methods.respond(this, response);
  319.             },
  320.            
  321.             ping: function() {
  322.                 // Create the ping response
  323.                 var response = {
  324.                     cmd: "pong",
  325.                     error: false
  326.                 };
  327.                
  328.                 // Encode the response to JSON
  329.                 methods.respond(this, response);
  330.             },
  331.            
  332.             image: function(data) {
  333.                 fs.writeFile("test.jpg", data.image, "base64", function(err) {
  334.                    
  335.                 });
  336.             }
  337.         };
  338.         // Create a new server instance
  339.         var server = new net.Server();
  340.        
  341.         // Change the maximum allowed event listeners
  342.         server.setMaxListeners(0);
  343.        
  344.         server.on("connection", function(socket) {
  345.          
  346.             socket.key = socket.remoteAddress + ":" + socket.remotePort;
  347.          
  348.             // We have a new connection
  349.             methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Socket %s connected", ("" + process.pid).padLeft(5, "0"), socket.remoteAddress);
  350.            
  351.             socket.setEncoding("utf8");
  352.             socket.setKeepAlive(true);
  353.            
  354.             socket.setTimeout(60000, function(){
  355.                 methods.log("timeout!");
  356.             });
  357.            
  358.             var buffer   = "";
  359.             var message  = "";
  360.             var messages = [];
  361.            
  362.             // Create the on data receive event
  363.             socket.on("data", function(data) {
  364.              
  365.                 // Strip the data
  366.                 data = data.replace(/\\/gi, '');
  367.                 data = data.replace(/^\r\n/, '');
  368.              
  369.                 // Append the data to the buffer
  370.                 buffer += data;
  371.                
  372.                 // Match the buffer
  373.                 if(messages = buffer.match(/(.+)(?=\r\n)/g)) {
  374.                     //buffer.replace()
  375.                     for(var i in messages) {
  376.                         // Get the current message
  377.                         message = messages[i];
  378.                         // Remove the message from the buffer
  379.                         buffer = buffer.replace(message + "\r\n", "");
  380.                        
  381.                         try {
  382.                             // Try to parse the JSON data
  383.                             message = JSON.parse(message);
  384.  
  385.                             // Get the command from the
  386.                             // message and validate it.
  387.                             if ((message.cmd) && message.cmd in cmds) {
  388.                                
  389.                                 methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Running command: %s", ("" + process.pid).padLeft(5, "0"), message.cmd);
  390.                                
  391.                                 try {
  392.                                   // Call the requested command and pass the message data.
  393.                                   cmds[message.cmd].call(socket, message.data || null);
  394.                                  
  395.                                 } catch(error) {
  396.                                     methods.log(error);
  397.                                     // We have a command run error
  398.                                     //methods.log("[WKR:" + "%s".cyan + "] [" + "ERROR".red + "] There was a problem when performing the command: %s", ("" + process.pid).padLeft(5, "0"), message.cmd)
  399.                                 }
  400.                             }                              
  401.                         } catch(error) {
  402.                             // We have a JSON parse error
  403.                             methods.log("[WKR:" + "%s".cyan + "] [" + "ERROR".red + "] JSON parse error", ("" + process.pid).padLeft(5, "0"));
  404.                         }
  405.                     }
  406.                 }
  407.             });
  408.             socket.on('close', function () {
  409.                 console.log("SOCKET HAS BEEN CLOSED :" + socket.key);
  410.                 socket.destroy();
  411.             });
  412.             // Create the connection end event
  413.             socket.on("end", function() {
  414.                  socket.destroy();
  415.                  methods.log("[WKR:" + "%s".cyan + "] [" + "OK".green + "] Socket disconnect", ("" + process.pid).padLeft(5, "0"));
  416.             });
  417.            
  418.             // Output any socket errors
  419.             socket.on("error", function(error) {
  420.                 methods.log(error);
  421.             });
  422.         });
  423.        
  424.         // output the errors
  425.         server.on("error", methods.log);
  426.        
  427.         // Start the listening
  428.         server.listen(config.port, config.host);
  429.     }
  430. }));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement