#!/usr/bin/php -q
<?php
include("/system/init.php");

// Set time limit to indefinite execution 
set_time_limit (0); 

// Set the ip and port we will listen on 
$address '0.0.0.0'
$port 1983;
$max_clients 5

// Array that will hold client information 
$clients = Array();
$banned = Array();

// Create a TCP Stream socket 
$sock socket_create(AF_INETSOCK_STREAM0); 
// Bind the socket to an address/port 

if (!@socket_setopt($sock,SOL_SOCKET,SO_REUSEADDR,1)) {
               echo 
"socket_setopt() failed: reason: ".socket_strerror(socket_last_error($sock))."\n";
               exit;
       }

socket_bind($sock$address$port) or die('Could not bind to address'); 
// Start listening for connections 
socket_listen($sock); 

// Loop continuously 
while ($quit != true) { 
    
// Setup clients listen socket for reading 
    
$read[0] = $sock
    for (
$i 0$i $max_clients$i++) 
    { 
        if (
$client[$i]['sock']  != null
            
$read[$i 1] = $client[$i]['sock'] ; 
    } 
    
// Set up a blocking call to socket_select() 
    
$ready socket_select($read,$write null,$except null,null); 
    
/* if a new connection is being made add it to the client array */ 
    
if (in_array($sock$read)) { 
        for (
$i 0$i $max_clients$i++) 
        { 
            if (
$client[$i]['sock'] == null) { 
                
srand ((double) microtime() * 1000000);
                
socket_getpeername($sock,&$ip);
                echo(
$ip);
                
                
$client[$i]['sock'] = socket_accept($sock);
                
$client[$i]["status"] = 'loggedout';
                
$client[$i]["num"] = rand(1000000099999999);
                
$client[$i]["ip"] = $ip;
                
$num $client[$i]["num"];
                
                if(
in_array($client[$i]["ip"],$banned)) {
                    print 
"killed ".$client[$i]["ip"];
                    
socket_close($client[$i]['sock']);
                    break;
                }
                
                
$client[$i]["result"] = substr(md5(substr($num,0,1).substr($num,2,1).substr($num,4,1).substr($num,6,1).substr($num,1,1).substr($num,3,1).substr($num,5,1).substr($num,7,1)),0,10);
                

                
socket_write($client[$i]['sock'],"//0 Fragzz Network Control System: ".system('hostname')."\r\n");
                
socket_write($client[$i]['sock'],"//L:".$client[$i]["num"]."\r\n");
                break; 
            } 
            elseif (
$i == $max_clients 1
                print (
"too many clients");
        } 
        if (--
$ready <= 0
            continue; 
    } 
// end if in_array 
     
    // If a client is trying to write - handle it now 
    
for ($i 0$i $max_clients$i++) // for each client 
    

        if (
in_array($client[$i]['sock'] , $read)) 
        { 
            
$input socket_read($client[$i]['sock'] , 1024); 
            if (
$input == null) { 
                
// Zero length string meaning disconnected 
                
unset($client[$i]); 
            } 
            
$client[$i]['data'] .= ereg_replace("[\t\n\r]","",$input);
            if(
ereg("\n",$input)) {
                
$data explode(" ",$client[$i]['data']);
                
$data[0] = strtolower($data[0]);
                
$sinfo['username'] = $data[1];

                if(
$data[0] == 'quit') {
                        
socket_write($client[$i]['sock'],"//2 Bye!\r\n");
                        
socket_close($client[$i]['sock']);
                        unset(
$client[$i]);
                }
                elseif(
$client[$i]['status'] == 'loggedout') {
                    if(
$client[$i]['data'] == $client[$i]["result"]) {
                        
$client[$i]["status"] = 'loggedin';
                        
socket_write($client[$i]['sock'],"//L OK\r\n");
                    }
                    else {
                        
$client[$i]["attempts"]++;
                        
socket_write($client[$i]['sock'],"//L Incorrect\r\n");
                        if(
$client[$i]["attempts"] == 3) {
                            
$banned[] = $client[$i]['ip'];
                            echo(
$client[$i]['ip']);
                            
socket_close($client[$i]['sock']);
                            unset(
$client[$i]);
                        }
                    }                    
                }
                else {
                    switch(
$data[0]) {
                    case 
'shutdown':
                        
$quit true;
                        
socket_write($client[$i]['sock'],"//1 OK. Shutting down.\r\n");
                        break;

                    case 
'init':
                        echo 
system("mkdir /servers/".$sinfo["username"]);
                        echo 
system("mkdir /servers/".$sinfo["username"]."/env/");
                        echo 
system("mkdir /servers/".$sinfo["username"]."/tmp/");
                        echo 
system("mkdir /servers/".$sinfo["username"]."/log/");
                        echo 
system("mkdir /servers/".$sinfo["username"]."/logs/");
                        echo 
system("mkdir /servers/".$sinfo["username"]."/supervise/");
                        echo 
system("touch /servers/".$sinfo["username"]."/supervise/down");
                        echo 
system("echo '/servers/".$sinfo["username"]."' > /servers/".$sinfo["username"]."/env/HOME");

                        
$file fopen('/servers/'.$sinfo["username"].'/log/run','w');
                        
fwrite($file,"#!/bin/sh
                        exec /usr/local/bin/setuidgid "
.$sinfo["username"]." /usr/local/bin/multilog t /servers/".$sinfo["username"]."/logs 2>&1
                        "
);
                        
fclose($file);
                        echo 
system("chmod +x /servers/".$sinfo["username"]."/log/run");

                        echo 
system("/usr/sbin/adduser -g servers -s /bin/noshell -d /servers/".$sinfo["username"]."  ".$sinfo["username"]);
                        echo 
system("chown ".$sinfo["username"].".servers /servers/".$sinfo["username"]." -R");
                        echo 
system("chown domains.servers /servers/".$sinfo["username"]."/env -R");
                        echo 
system("chown domains.servers /servers/".$sinfo["username"]."/tmp -R");
                        echo 
system("chown domains.servers /servers/".$sinfo["username"]."/log -R");
                        echo 
system("chmod 774 /servers/".$sinfo["username"]." -R");
                        echo 
system("chmod +t /servers/".$sinfo["username"]);
                        echo 
system("svc-add /servers/".$sinfo["username"]." > /dev/null 2>&1");
                        echo 
system("svc -d /service/".$sinfo["username"]." > /dev/null 2>&1");
                        echo 
system("chmod +t /service/".$sinfo["username"]);
                        
                        
$sqc $DB->query("SELECT server_config_id FROM s_config_db WHERE server_id = '".$DB->get_data("s_internal_db","server_id","username",$sinfo["username"])."';") or die($DB->error());
                        while(
$cfgs $DB->fetch_array($sqc)) {
                            
addconfig($sinfo["username"],$cfgs[0]);
                        }

                        
socket_write($client[$i]['sock'],"//3 OK\r\n");
                        break;


                                        case 
'archive':
                        
system("mkdir /servers/BACKUPS");
                        
system("tar cfv /servers/BACKUPS/".$sinfo['username']."-".date('d-M-Y').".tar /servers/".$sinfo['username']);

                                                
socket_write($client[$i]['sock'],"//4 OK\r\n");
                                                break;



                    case 
'deinit':
                        
system("svc-remove ".$sinfo['username']);
                        
system("userdel ".$sinfo['username']);
                        
system("rm -rf /servers/".$sinfo['username']);

                        
socket_write($client[$i]['sock'],"//4 OK\r\n");
                        break;

                    case 
'start':
                        
system("svc -u /servers/".$sinfo['username']);
                        
socket_write($client[$i]['sock'],"//5 OK\r\n");
                        break;

                    case 
'stop':
                        
system("svc -d /servers/".$sinfo['username']);
                        
socket_write($client[$i]['sock'],"//6 OK\r\n");
                        break;

                    case 
'restart':
                        
system("svc -h /servers/".$sinfo['username']);
                        
socket_write($client[$i]['sock'],"//7 OK\r\n");
                        break;

                    case 
'online':
                        
system("svc-add /servers/".$sinfo['username']);
                        
socket_write($client[$i]['sock'],"//8 OK\r\n");
                        break;

                    case 
'offline':
                        
system("svc-remove ".$sinfo['username']);
                        
socket_write($client[$i]['sock'],"//9 OK\r\n");
                        break;

                    case 
'status':
                        
$info system("/usr/bin/svstat /servers/".$sinfo['username']);
                        
socket_write($client[$i]['sock'],"//10 (".$data[1]."): ".$info."\r\n");
                        break;

                    case 
'addconfig':
                        
                        
addserver($sinfo["username"],$data[2]);
                        
                        
socket_write($client[$i]['sock'],"//13 OK\r\n");

                        break;

                    case 
'apply':
                        
$sql1 mysql_query("SELECT server_id, current_config FROM s_internal_db WHERE username = '".$sinfo['username']."';") or mail('chris@fragzzhost.com','dawdaw',mysql_error());

                        
$userid mysql_result($sql1,0,"server_id");
                        if(empty(
$data[2])) {
                                
$data[2] = mysql_result($sql1,0,"current_config");
                        }

                        if(empty(
$userid)) {
                                
socket_write($client[$i]['sock'],"//! User '".$data[1]."' not found\r\n");
                        }
                        else {
                                
apply_config($userid,$data[1],$data[2]);
                                
socket_write($client[$i]['sock'],"//11 $IP:$PORT\r\n");
                                echo(
"Config Applied\n");
                                echo(
"IP: $IP\n");
                                echo(
"Port: $PORT\n");
                        }

                        break;
                    
                    case 
'load':
                        
$info system('uptime');
                        
$iarr explode(" users,  load average: ",$info);
                        
$loads trim($iarr[1]);
                        
                        
socket_write($client[$i]['sock'],"//12 ".$loads."\r\n");

                        break;

                    case 
'wipeban':
                        if(
$data[1] == 'all') {
                            
$banned = array();
                        }
                        else {
                            unset(
$banned[array_search($data[1],$banned)]);
                        }

                        
socket_write($client[$i]['sock'],"//B OK\r\n");

                        break;
                    
                    case 
'getfile':
                        
$file "/servers/".$sinfo['username']."/".$data[2];
                        
$f fopen($file,'rb');
                        
$dat fread($f,filesize($file));
                        
$dat base64_encode($dat);
                        
fclose($f);
                        
                        
socket_write($client[$i]['sock'],"//13 OK Data will now follow\r\n".$dat);
                    
                        break;
                        
                    case 
'putfile':
                                                
$file "/servers/".$sinfo['username']."/".$data[2];                                                                      
                                                
$f fopen($file,'wb');
                                                
fwrite($f,base64_decode($data[3])); 
                        
fclose($f);

                                                
socket_write($client[$i]['sock'],"//14 OK\r\n".$data);

                                                                                                                                                                                                                                                                    
                    
                        break;
                        
                    case 
'grabupdate':
                        
system('rsync -aur 62.119.28.214::'.$data[1].' /'.str_replace('*','',$data[1]).' &');
                        
socket_write($client[$i]['sock'],"//15 OK Running in background\r\n");
                    
                        break;
                    
                    default:
                        
socket_write($client[$i]['sock'],"//! Command '".$data[0]."' not found\r\n");
                        break;

                    }
                }
                
$client[$i]['data'] = '';
            }
        } else { 
            unset(
$client[$i]); 
        } 
    } 
// end while 
// Close the master sockets 

for ($i 0$i $max_clients$i++) { 
    
socket_close($client[$i]['sock']); 
}

socket_close($sock); 
?>