Esempio n. 1
0
 public static function setUpBeforeClass()
 {
     if (function_exists('pcntl_fork') && function_exists('posix_kill')) {
         // get an empty socket
         $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
         socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
         socket_bind($socket, '127.0.0.1', 0);
         socket_getsockname($socket, $socket_address, $port);
         socket_close($socket);
         // set it somewhere
         self::$port = $port;
         // fork the webserver
         self::$pid = pcntl_fork();
         if (self::$pid == -1) {
             return $this->raiseError('Could not fork child process.');
         } elseif (self::$pid == 0) {
             $webserver =& new LocalWebServer('127.0.0.1', $port);
             $webserver->_driver->setDebugMode(false);
             $webserver->documentRoot = dirname(__FILE__) . '/../www';
             $webserver->start();
         } else {
             // the parent process does not have to do anything
         }
     }
 }
 /**
  * @desc 获取当前套接字本地inet地址
  * @param[out] sAddr: 点分格式表示的本地地址
  * @param[out] iPort: 本地端口
  * @return 0: 成功 -1: 失败
  */
 public function GetLocalAddr(&$sAddr, &$iPort)
 {
     if (socket_getsockname($this->_iHandle, $sAddr, $iPort) === false) {
         return -1;
     }
     return 0;
 }
Esempio n. 3
0
 public function __construct(Server $server, $password, $port = 19132, $interface = "0.0.0.0", $threads = 1, $clientsPerThread = 50)
 {
     $this->server = $server;
     $this->workers = [];
     $this->password = (string) $password;
     $this->server->getLogger()->info("Starting remote control listener");
     if ($this->password === "") {
         $this->server->getLogger()->critical("RCON can't be started: Empty password");
         return;
     }
     $this->threads = (int) max(1, $threads);
     $this->clientsPerThread = (int) max(1, $clientsPerThread);
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)) {
         $this->server->getLogger()->critical("RCON can't be started: " . socket_strerror(socket_last_error()));
         $this->threads = 0;
         return;
     }
     socket_set_block($this->socket);
     for ($n = 0; $n < $this->threads; ++$n) {
         $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread);
     }
     socket_getsockname($this->socket, $addr, $port);
     $this->server->getLogger()->info("RCON running on {$addr}:{$port}");
 }
Esempio n. 4
0
 public function getHost($sockInt)
 {
     $status = socket_getsockname($this->socketInfo[$sockInt]->socket, $addr);
     if ($status == false) {
         return false;
     }
     return $addr;
 }
 public function __construct($connection)
 {
     $address = '';
     $port = '';
     socket_getsockname($connection, $address, $port);
     $this->address = $address;
     $this->port = $port;
     $this->connection = $connection;
 }
 /**
  * Returns local endpoint
  *
  * @return  peer.SocketEndpoint
  * @throws  peer.SocketException
  */
 public function localEndpoint()
 {
     if (is_resource($this->_sock)) {
         if (FALSE === socket_getsockname($this->_sock, $host, $port)) {
             throw new SocketException('Cannot get socket name on ' . $this->_sock);
         }
         return new SocketEndpoint($host, $port);
     }
     return NULL;
     // Not connected
 }
Esempio n. 7
0
 public function __construct($bind_ip, $port)
 {
     set_time_limit(0);
     $this->hooks = array();
     $this->config["ip"] = $bind_ip;
     $this->config["port"] = $port;
     $this->master_socket = socket_create(AF_INET, SOCK_STREAM, 0);
     socket_bind($this->master_socket, $this->config["ip"], $this->config["port"]) or die("Issue Binding");
     socket_getsockname($this->master_socket, $bind_ip, $port);
     socket_listen($this->master_socket);
     SocketServer::debug("Listenting for connections on {$bind_ip}:{$port}");
 }
Esempio n. 8
0
 /**
  * Bind the socket
  * @return null|boolean Success.
  */
 public function bindSocket()
 {
     if ($this->erroneous) {
         return false;
     }
     $port = $this->getPort();
     if (!is_int($port)) {
         Daemon::log(get_class($this) . ' (' . get_class($this->pool) . '): no port defined for \'' . $this->uri['uri'] . '\'');
         return;
     }
     if ($port < 1024 && Daemon::$config->user->value !== 'root') {
         $this->listenerMode = false;
     }
     if ($this->listenerMode) {
         $this->setFd($this->host . ':' . $port);
         return true;
     }
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if (!$sock) {
         $errno = socket_last_error();
         Daemon::$process->log(get_class($this->pool) . ': Couldn\'t create TCP-socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
         return false;
     }
     if ($this->reuse) {
         if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
             $errno = socket_last_error();
             Daemon::$process->log(get_class($this->pool) . ': Couldn\'t set option REUSEADDR to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
             return false;
         }
         if (defined('SO_REUSEPORT') && !@socket_set_option($sock, SOL_SOCKET, SO_REUSEPORT, 1)) {
             $errno = socket_last_error();
             Daemon::$process->log(get_class($this->pool) . ': Couldn\'t set option REUSEPORT to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
             return false;
         }
     }
     if (!@socket_bind($sock, $this->host, $port)) {
         $errno = socket_last_error();
         Daemon::$process->log(get_class($this->pool) . ': Couldn\'t bind TCP-socket \'' . $this->host . ':' . $port . '\' (' . $errno . ' - ' . socket_strerror($errno) . ').');
         return false;
     }
     socket_getsockname($sock, $this->host, $this->port);
     socket_set_nonblock($sock);
     if (!$this->listenerMode) {
         if (!socket_listen($sock, SOMAXCONN)) {
             $errno = socket_last_error();
             Daemon::$process->log(get_class($this->pool) . ': Couldn\'t listen TCP-socket \'' . $this->host . ':' . $port . '\' (' . $errno . ' - ' . socket_strerror($errno) . ')');
             return false;
         }
     }
     $this->setFd($sock);
     return true;
 }
Esempio 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;
     }
 }
 public function __construct($socket)
 {
     $this->socket = $socket;
     if (!is_resource($this->socket)) {
         throw new socketException("Invalid socket or resource");
     } elseif (!socket_getsockname($this->socket, $this->local_addr, $this->local_port)) {
         throw new socketException("Could not retrieve local address & port: " . socket_strerror(socket_last_error($this->socket)));
     } elseif (!socket_getpeername($this->socket, $this->remote_address, $this->remote_port)) {
         throw new socketException("Could not retrieve remote address & port: " . socket_strerror(socket_last_error($this->socket)));
     }
     $this->set_non_block();
     $this->on_connect();
 }
Esempio n. 11
0
 function __construct($hostname, $port, $driver = 'Fork')
 {
     if ($port == 0) {
         $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
         socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
         socket_bind($socket, '127.0.0.1', 0);
         socket_getsockname($socket, $socket_address, $port);
         socket_close($socket);
     }
     $this->_driver =& new E34_Net_Server_Driver_Fork($hostname, $port);
     $this->_driver->readEndCharacter = "\r\n\r\n";
     $this->_driver->setCallbackObject($this);
 }
Esempio n. 12
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);
     }
 }
Esempio n. 13
0
 public function __construct($socket)
 {
     AirD::Log(AirD::LOGTYPE_INTERNAL, "socketServerClient's constructor", true);
     $this->socket = $socket;
     if (!is_resource($this->socket)) {
         throw new socketException("Invalid socket or resource");
     } elseif (!socket_getsockname($this->socket, $this->local_addr, $this->local_port)) {
         throw new socketException("Could not retrieve local address & port: " . socket_strerror(socket_last_error($this->socket)));
     } elseif (!socket_getpeername($this->socket, $this->remote_address, $this->remote_port)) {
         throw new socketException("Could not retrieve remote address & port: " . socket_strerror(socket_last_error($this->socket)));
     }
     $this->on_connect();
     $this->set_non_block(true);
     SocketEngine::AddFd($this);
 }
Esempio n. 14
0
 public function connect()
 {
     $this->siteManager->initSites();
     NginyUS::message('Binding socket...');
     while (!@socket_bind($this->socket, $this->addr, $this->port)) {
         NginyUS::message('Address $0 not available, trying $1', array($this->addr . ':' . $this->port, $this->addr . ':' . ($this->port + 1)), E_WARNING);
         $this->port++;
     }
     socket_set_nonblock($this->socket);
     NginyUS::message('Socket successfully bound to ' . $this->addr . ':' . $this->port);
     //Setting serverInfo about address and port
     $this->serverInfo['port'] = $this->port;
     socket_getsockname($this->socket, $this->serverInfo['addr']);
     NginyUS::message('Listening now...');
 }
Esempio n. 15
0
 public static function setUpBeforeClass()
 {
     $VTROOT = getenv('VTROOT');
     if (!$VTROOT) {
         throw new Exception('VTROOT env var not set; make sure to source dev.env');
     }
     // Pick an unused port.
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_bind($sock, 'localhost');
     if (!socket_getsockname($sock, $addr, $port)) {
         throw new Exception('Failed to find unused port for mock vtgate server.');
     }
     socket_close($sock);
     $cmd = "{$VTROOT}/bin/vtgateclienttest -logtostderr -lameduck-period 0 -grpc_port {$port} -service_map grpc-vtgateservice";
     $proc = proc_open($cmd, array(), $pipes);
     if (!$proc) {
         throw new Exception("Failed to start mock vtgate server with command: {$cmd}");
     }
     self::$proc = $proc;
     // Wait for connection to be accepted.
     $ctx = VTContext::getDefault()->withDeadlineAfter(5.0);
     $level = error_reporting(error_reporting() & ~E_WARNING);
     while (!$ctx->isCancelled()) {
         try {
             $client = new VTGrpcClient("{$addr}:{$port}");
         } catch (Exception $e) {
             usleep(100000);
             continue;
         }
         break;
     }
     error_reporting($level);
     self::$client = $client;
     // Test fixtures that can't be statically initialized.
     self::$BIND_VARS = array('bytes' => 'hello', 'int' => 123, 'uint_from_int' => new VTUnsignedInt(-123), 'uint_from_string' => new VTUnsignedInt('456'), 'float' => 1.5);
     self::$CALLER_ID = new \vtrpc\CallerID();
     self::$CALLER_ID->setPrincipal('test_principal');
     self::$CALLER_ID->setComponent('test_component');
     self::$CALLER_ID->setSubcomponent('test_subcomponent');
     self::$KEYSPACE_IDS = array(VTProto::KeyspaceIdFromHex('8000000000000000'), VTProto::KeyspaceIdFromHex('ff000000000000ef'));
     self::$KEY_RANGES = array(VTProto::KeyRangeFromHex('', '8000000000000000'), VTProto::KeyRangeFromHex('8000000000000000', ''));
     self::$ENTITY_KEYSPACE_IDS = array(VTProto::KeyspaceIdFromHex('1234567800000002') => 'hello', VTProto::KeyspaceIdFromHex('1234567800000000') => 123, VTProto::KeyspaceIdFromHex('1234567800000001') => new VTUnsignedInt(456), VTProto::KeyspaceIdFromHex('1234567800000002') => 1.5);
 }
Esempio n. 16
0
function server_loop($address, $port)
{
    global $__server_listening;
    global $__PROCESS_NUM;
    if (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
        events("failed to create socket: " . socket_strerror($sock), __FUNCTION__, __LINE__);
        exit;
    }
    if (($ret = socket_bind($sock, $address, $port)) < 0) {
        events("failed to bind socket: " . socket_strerror($ret), __FUNCTION__, __LINE__);
        exit;
    }
    if (($ret = socket_listen($sock, 0)) < 0) {
        events("failed to listen to socket: " . socket_strerror($ret), __FUNCTION__, __LINE__);
        exit;
    }
    @unlink("/etc/artica-postfix/pids/squid-tail-sock");
    // socket_set_nonblock($sock);
    socket_getsockname($socket, $GIP, $GPORT);
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    events("waiting for clients to connect {$GIP}:{$GPORT} ({$MyPort}) [ERR.{$errorcode}] `{$errormsg}` {$GLOBALS["COUNT_ERROR_98"]}", __FUNCTION__, __LINE__);
    if ($errorcode == 98) {
        events("die...", __FUNCTION__, __LINE__);
        return;
    }
    @file_put_contents("/etc/artica-postfix/pids/squid-tail-sock", "OK");
    $GLOBALS["SOCK"] = $sock;
    while ($__server_listening) {
        $connection = @socket_accept($sock);
        if ($connection === false) {
            usleep(200000);
        } elseif ($connection > 0) {
            events("handle_client()...", __FUNCTION__, __LINE__);
            handle_client($sock, $connection);
        } else {
            events("error: " . socket_strerror($connection), __FUNCTION__, __LINE__);
            die;
        }
    }
}
Esempio n. 17
0
 /**
  *  Create a TCP Stream socket
  */
 function Server()
 {
     set_time_limit(0);
     $server_socket = socket_create(AF_INET, SOCK_STREAM, 0);
     $address = "127.0.0.1";
     /* Address will always be localhost for safety. */
     /* Bind the socket to an address/port */
     socket_bind($server_socket, $address, 0) or die('Could not bind to address');
     socket_getsockname($server_socket, $socket_address, $socket_port);
     debug("port: {$socket_port} \n");
     write_to_disk("port", $socket_port);
     /* Start listening for connections. */
     socket_listen($server_socket);
     while (true) {
         /* Forever handle clients. */
         /* Accept incoming requests and handle them as child processes. */
         $client_socket = socket_accept($server_socket);
         /* Create a new client which will do all the hard lifting. */
         new Client($client_socket, $server_socket);
     }
 }
Esempio n. 18
0
 public function __construct($bind_address = 0, $bind_port = 0, $domain = AF_INET, $type = SOCK_STREAM, $protocol = SOL_TCP)
 {
     $this->bind_address = $bind_address;
     $this->bind_port = $bind_port;
     $this->domain = $domain;
     $this->type = $type;
     $this->protocol = $protocol;
     if (($this->socket = @socket_create($domain, $type, $protocol)) === false) {
         throw new socketException("Could not create socket: " . socket_strerror(socket_last_error($this->socket)));
     }
     if (!@socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
         throw new socketException("Could not set SO_REUSEADDR: " . $this->get_error());
     }
     if (!@socket_bind($this->socket, $bind_address, $bind_port)) {
         throw new socketException("Could not bind socket to [{$bind_address} - {$bind_port}]: " . socket_strerror(socket_last_error($this->socket)));
     }
     if (!@socket_getsockname($this->socket, $this->local_addr, $this->local_port)) {
         throw new socketException("Could not retrieve local address & port: " . socket_strerror(socket_last_error($this->socket)));
     }
     $this->set_non_block(true);
 }
Esempio n. 19
0
 public function __construct($password, $port = 19132, $interface = "0.0.0.0", $threads = 1, $clientsPerThread = 50)
 {
     $this->workers = array();
     $this->password = (string) $password;
     console("[INFO] Starting remote control listener");
     if ($this->password === "") {
         console("[ERROR] RCON can't be started: Empty password");
         return;
     }
     $this->threads = (int) max(1, $threads);
     $this->clientsPerThread = (int) max(1, $clientsPerThread);
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)) {
         console("[ERROR] RCON can't be started: " . socket_strerror(socket_last_error()));
         return;
     }
     @socket_set_block($this->socket);
     for ($n = 0; $n < $this->threads; ++$n) {
         $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread);
     }
     @socket_getsockname($this->socket, $addr, $port);
     console("[INFO] RCON running on {$addr}:{$port}");
     ServerAPI::request()->schedule(2, array($this, "check"), array(), true);
 }
Esempio n. 20
0
 function connect()
 {
     /*
     Connect to the data proxy. The data proxy will need to make an Ident call
     back to get the scraperID. Since the data proxy may be on another machine
     and the peer address it sees will have been subject to NAT or masquerading,
     send the UML name and the socket port number in the request.
     */
     if (is_null($this->m_socket)) {
         $this->m_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
         if (socket_connect($this->m_socket, $this->m_host, $this->m_port) === FALSE) {
             throw new Exception("Could not socket_connect to datastore");
         }
         socket_getsockname($this->m_socket, $addr, $port);
         //print "socket_getsockname " . $addr . ":" . $port . "\n";
         $getmsg = sprintf("GET /?uml=%s&port=%s&vscrapername=%s&vrunid=%s&verify=%s HTTP/1.1\n\n", 'lxc', $port, urlencode($this->m_scrapername), urlencode($this->m_runid), urlencode($this->m_verification_key));
         socket_write($this->m_socket, $getmsg);
         socket_recv($this->m_socket, $buffer, 0xffff, 0);
         $result = json_decode($buffer, true);
         if ($result["status"] != "good") {
             throw new Exception($result["status"]);
         }
     }
 }
Esempio n. 21
0
/**
 * error handler for phpagi.
 *
 * @param integer $level PHP error level
 * @param string $message error message
 * @param string $file path to file
 * @param integer $line line number of error
 * @param array $context variables in the current scope
 */
function phpagi_error_handler($level, $message, $file, $line, $context)
{
    if (ini_get('error_reporting') == 0) {
        return;
    }
    // this happens with an @
    @syslog(LOG_WARNING, $file . '[' . $line . ']: ' . $message);
    global $phpagi_error_handler_email;
    if (function_exists('mail') && !is_null($phpagi_error_handler_email)) {
        // decode error level
        switch ($level) {
            case E_WARNING:
            case E_USER_WARNING:
                $level = "Warning";
                break;
            case E_NOTICE:
            case E_USER_NOTICE:
                $level = "Notice";
                break;
            case E_USER_ERROR:
                $level = "Error";
                break;
        }
        // build message
        $basefile = basename($file);
        $subject = "{$basefile}/{$line}/{$level}: {$message}";
        $message = "{$level}: {$message} in {$file} on line {$line}\n\n";
        if (function_exists('mysql_errno') && strpos(' ' . strtolower($message), 'mysql')) {
            $message .= 'MySQL error ' . mysql_errno() . ": " . mysql_error() . "\n\n";
        }
        // figure out who we are
        if (function_exists('socket_create')) {
            $addr = NULL;
            $port = 80;
            $socket = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
            @socket_connect($socket, '64.0.0.0', $port);
            @socket_getsockname($socket, $addr, $port);
            @socket_close($socket);
            $message .= "\n\nIP Address: {$addr}\n";
        }
        // include variables
        $message .= "\n\nContext:\n" . print_r($context, true);
        $message .= "\n\nGLOBALS:\n" . print_r($GLOBALS, true);
        $message .= "\n\nBacktrace:\n" . print_r(debug_backtrace(), true);
        // include code fragment
        if (file_exists($file)) {
            $message .= "\n\n{$file}:\n";
            $code = @file($file);
            for ($i = max(0, $line - 10); $i < min($line + 10, count($code)); $i++) {
                $message .= $i + 1 . "\t{$code[$i]}";
            }
        }
        // make sure message is fully readable (convert unprintable chars to hex representation)
        $ret = '';
        for ($i = 0; $i < strlen($message); $i++) {
            $c = ord($message[$i]);
            if ($c == 10 || $c == 13 || $c == 9) {
                $ret .= $message[$i];
            } elseif ($c < 16) {
                $ret .= '\\x0' . dechex($c);
            } elseif ($c < 32 || $c > 127) {
                $ret .= '\\x' . dechex($c);
            } else {
                $ret .= $message[$i];
            }
        }
        $message = $ret;
        // send the mail if less than 5 errors
        static $mailcount = 0;
        if ($mailcount < 5) {
            @mail($phpagi_error_handler_email, $subject, $message);
        }
        $mailcount++;
    }
}
Esempio n. 22
0
 function getSocketHost()
 {
     return socket_getsockname($this->socket, $addr) ? $addr : NULL;
 }
Esempio n. 23
0
 function _data_prepare($mode = FTP_ASCII)
 {
     if (!$this->_settype($mode)) {
         return FALSE;
     }
     $this->SendMSG("Creating data socket");
     $this->_ftp_data_sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->_ftp_data_sock < 0) {
         $this->PushError('_data_prepare', 'socket create failed', socket_strerror(socket_last_error($this->_ftp_data_sock)));
         return FALSE;
     }
     if (!$this->_settimeout($this->_ftp_data_sock)) {
         $this->_data_close();
         return FALSE;
     }
     if ($this->_passive) {
         if (!$this->_exec("PASV", "pasv")) {
             $this->_data_close();
             return FALSE;
         }
         if (!$this->_checkCode()) {
             $this->_data_close();
             return FALSE;
         }
         $ip_port = explode(",", ereg_replace("^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*" . CRLF . "\$", "\\1", $this->_message));
         $this->_datahost = $ip_port[0] . "." . $ip_port[1] . "." . $ip_port[2] . "." . $ip_port[3];
         $this->_dataport = ((int) $ip_port[4] << 8) + (int) $ip_port[5];
         $this->SendMSG("Connecting to " . $this->_datahost . ":" . $this->_dataport);
         if (!@socket_connect($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) {
             $this->PushError("_data_prepare", "socket_connect", socket_strerror(socket_last_error($this->_ftp_data_sock)));
             $this->_data_close();
             return FALSE;
         } else {
             $this->_ftp_temp_sock = $this->_ftp_data_sock;
         }
     } else {
         if (!@socket_getsockname($this->_ftp_control_sock, $addr, $port)) {
             $this->PushError("_data_prepare", "can't get control socket information", socket_strerror(socket_last_error($this->_ftp_control_sock)));
             $this->_data_close();
             return FALSE;
         }
         if (!@socket_bind($this->_ftp_data_sock, $addr)) {
             $this->PushError("_data_prepare", "can't bind data socket", socket_strerror(socket_last_error($this->_ftp_data_sock)));
             $this->_data_close();
             return FALSE;
         }
         if (!@socket_listen($this->_ftp_data_sock)) {
             $this->PushError("_data_prepare", "can't listen data socket", socket_strerror(socket_last_error($this->_ftp_data_sock)));
             $this->_data_close();
             return FALSE;
         }
         if (!@socket_getsockname($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) {
             $this->PushError("_data_prepare", "can't get data socket information", socket_strerror(socket_last_error($this->_ftp_data_sock)));
             $this->_data_close();
             return FALSE;
         }
         if (!$this->_exec('PORT ' . str_replace('.', ',', $this->_datahost . '.' . ($this->_dataport >> 8) . '.' . ($this->_dataport & 0xff)), "_port")) {
             $this->_data_close();
             return FALSE;
         }
         if (!$this->_checkCode()) {
             $this->_data_close();
             return FALSE;
         }
     }
     return TRUE;
 }
Esempio n. 24
0
 /**
  * Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path,
  * dependent on its type.
  *
  * <p><b>Note:</b> <code>getSockName()</code> should not be used with <code>AF_UNIX</code> sockets created with
  * <code>connect()</code>. Only sockets created with <code>accept()</code> or a primary server socket following a
  * call to <code>bind()</code> will return meaningful values.</p>
  *
  * @param string $address <p>If the given socket is of type <code>AF_INET</code> or <code>AF_INET6</code>,
  *                        <code>getSockName()</code> will return the local IP address in appropriate notation (e.g.
  *                        <code>127.0.0.1</code> or <code>fe80::1</code>) in the address parameter and, if the optional port parameter is
  *                        present, also the associated port.</p><p>If the given socket is of type <code>AF_UNIX</code>,
  *                        <code>getSockName()</code> will return the Unix filesystem path (e.g. <code>/var/run/daemon.sock</cod>) in the
  *                        address parameter.</p>
  * @param int    $port    If provided, this will hold the associated port.
  *
  * @throws Exception\SocketException <p>If the retrieval of the socket name fails or if the socket type is not
  *                                   <code>AF_INET</code>, <code>AF_INET6</code>, or <code>AF_UNIX</code>.</p>
  *
  * @return bool <p>Returns <code>true</code> if the retrieval of the socket name was successful.</p>
  */
 public function getSockName(&$address, &$port)
 {
     if (!in_array($this->domain, [AF_UNIX, AF_INET, AF_INET6])) {
         return false;
     }
     return static::exceptionOnFalse($this->resource, function ($resource) use(&$address, &$port) {
         return @socket_getsockname($resource, $address, $port);
     });
 }
Esempio n. 25
0
 /**
  * @param string $address
  * @param integer $port
  *
  * @return bool
  * @throws Exception\Exception_Socket
  */
 public function getSockName(&$address, &$port)
 {
     if (!in_array($this->domain, array(AF_UNIX, AF_INET, AF_INET6))) {
         return false;
     }
     $return = @socket_getsockname($this->resource, $address, $port);
     if ($return === false) {
         throw new Exception_Socket($this->resource);
     }
     return $return;
 }
Esempio n. 26
0
 /**
  * get local side's address/path
  *
  * @return string
  * @throws Exception on error
  * @uses socket_getsockname()
  */
 public function getSockName()
 {
     $ret = @socket_getsockname($this->resource, $address, $port);
     if ($ret === false) {
         throw Exception::createFromSocketResource($this->resource);
     }
     return $this->formatAddress($address, $port);
 }
 function CrewClient(&$server, $socket, $cid)
 {
     $this->server =& $server;
     $this->socket = $socket;
     $this->cid = $cid;
     if (socket_getpeername($socket, $this->remote_address, $this->remote_port) === FALSE) {
         $this->remote_address = 'unknown';
         $this->remote_port = 0;
         logger('cannot retrieve peer name: ' . sockerr($socket));
     }
     if (socket_getsockname($socket, $this->local_address, $this->local_port) === FALSE) {
         $this->local_address = 'unknown';
         $this->local_port = 0;
         logger('cannot retrieve sock name: ' . sockerr($socket));
     }
     logger(sprintf('new client #%d: %s:%d [%s:%d]', $cid, $this->remote_address, $this->remote_port, $this->local_address, $this->local_port));
 }
	protected function _data_prepare($mode = self::ASCII) {
		if(!$this->_settype($mode)) {
			return false;
		}
		$this->sendMsg("Creating data socket");
		$this->ftp_data_sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
		if ($this->ftp_data_sock < 0) {
			$socketErr = socket_strerror(socket_last_error($this->ftp_data_sock));
			$this->pushError('_data_prepare', 'socket create failed', $socketErr);
			return false;
		}
		if(!$this->_setTimeout($this->ftp_data_sock)) {
			$this->_data_close();
			return false;
		}
		if($this->passive) {
			if(!$this->_exec("PASV", "pasv")) {
				$this->_data_close();
				return false;
			}
			if(!$this->_checkCode()) {
				$this->_data_close();
				return false;
			}
			$msg = preg_replace(
				"~^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*".self::CRLF."$~",
				"\\1",
				$this->message
			);
			$ip_port = explode(",", $msg);
			$this->datahost = $ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3];
			$this->dataport = (((int)$ip_port[4])<<8) + ((int)$ip_port[5]);
			$this->sendMsg("Connecting to {$this->datahost}:{$this->dataport}");
			if(!@socket_connect($this->ftp_data_sock, $this->datahost, $this->dataport)) {
				$socketErr = socket_strerror(socket_last_error($this->ftp_data_sock));
				$this->pushError("_data_prepare", "socket_connect", $socketErr);
				$this->_data_close();
				return false;
			}
			else {
				$this->ftp_temp_sock = $this->ftp_data_sock;
			}
		}
		else {
			if(!@socket_getsockname($this->ftp_control_sock, $addr, $port)) {
				$this->pushError(
					"_data_prepare",
					"can't get control socket information",
					socket_strerror(socket_last_error($this->ftp_control_sock))
				);
				$this->_data_close();
				return false;
			}
			if(!@socket_bind($this->ftp_data_sock, $addr)) {
				$this->pushError(
					"_data_prepare",
					"can't bind data socket",
					socket_strerror(socket_last_error($this->ftp_data_sock))
				);
				$this->_data_close();
				return false;
			}
			if(!@socket_listen($this->ftp_data_sock)) {
				$this->pushError(
					"_data_prepare",
					"can't listen data socket",
					socket_strerror(socket_last_error($this->ftp_data_sock))
				);
				$this->_data_close();
				return false;
			}
			if(!@socket_getsockname($this->ftp_data_sock, $this->datahost, $this->dataport)) {
				$this->pushError(
					"_data_prepare",
					"can't get data socket information",
					socket_strerror(socket_last_error($this->ftp_data_sock))
				);
				$this->_data_close();
				return false;
			}
			$port = str_replace(
				'.',
				',',
				$this->datahost.'.'.($this->dataport>>8).'.'.($this->dataport&0x00FF)
			);
			if(!$this->_exec('PORT '.$port, "_port")) {
				$this->_data_close();
				return false;
			}
			if(!$this->_checkCode()) {
				$this->_data_close();
				return false;
			}
		}
		return true;
	}
Esempio n. 29
0
File: UDP.php Progetto: zenus/phpinx
 /**
  * Bind given addreess
  * @return boolean Success.
  */
 public function bindSocket()
 {
     $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     if (!$sock) {
         $errno = socket_last_error();
         Daemon::$process->log(get_class($this) . ': Couldn\'t create UDP-socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
         return false;
     }
     if (!isset($this->port)) {
         if (isset($this->defaultPort)) {
             $this->port = $this->defaultPort;
         } else {
             Daemon::log(get_class($this) . ' (' . get_class($this->pool) . '): no port defined for \'' . $this->uri['uri'] . '\'');
         }
     }
     if ($this->reuse) {
         if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
             $errno = socket_last_error();
             Daemon::$process->log(get_class($this) . ': Couldn\'t set option REUSEADDR to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
             return false;
         }
         if (defined('SO_REUSEPORT') && !socket_set_option($sock, SOL_SOCKET, SO_REUSEPORT, 1)) {
             $errno = socket_last_error();
             Daemon::$process->log(get_class($this) . ': Couldn\'t set option REUSEPORT to socket (' . $errno . ' - ' . socket_strerror($errno) . ').');
             return false;
         }
     }
     if (!@socket_bind($sock, $this->host, $this->port)) {
         $errno = socket_last_error();
         $addr = $this->host . ':' . $this->port;
         Daemon::$process->log(get_class($this) . ': Couldn\'t bind UDP-socket \'' . $addr . '\' (' . $errno . ' - ' . socket_strerror($errno) . ').');
         return false;
     }
     socket_getsockname($sock, $this->host, $this->port);
     $addr = $this->host . ':' . $this->port;
     socket_set_nonblock($sock);
     $this->setFd($sock);
     return true;
 }
 public function getSocketPort()
 {
     socket_getsockname($this->socket, $socket_address, $socket_port);
     return $socket_port;
 }