public function socketClose() { $this->sock_error = socket_strerror(socket_last_error($this->fsock)); socket_clear_error(); @socket_close($this->fsock); return $this; }
private function get_mesh_info($info_type) { $socket = null; try { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { socket_clear_error($socket); return null; } $result = socket_connect($socket, "127.0.0.1", 9090); if ($result === false) { socket_clear_error($socket); return null; } $input = "GET /{$info_type} HTTP/1.1\r\n"; $output = ''; socket_write($socket, $input, strlen($input)); while ($buffer = socket_read($socket, 2048)) { $output .= $buffer; } socket_close($socket); return json_decode($output, true); } catch (Exception $e) { socket_clear_error($socket); return null; } }
private function _connect() { if ($this->connection = socket_create($this->socket_domain, SOCK_STREAM, $this->socket_domain > 1 ? getprotobyname('tcp') : 0)) { if (socket_connect($this->connection, $this->socket_address, $this->socket_port)) { $this->setNonBlock(); // $this->connection); // устанавливаем неблокирующий режим работы сокета return $this->connected = true; } else { $error = socket_last_error($this->connection); socket_clear_error($this->connection); switch ($error) { case SOCKET_ECONNREFUSED: case SOCKET_ENOENT: // если отсутствует файл сокета, либо соединиться со слушающим сокетом не удалось - возвращаем false $this->disconnect(); return false; default: // в иных случаях кидаем необрабатываемое исключение throw new \Exception(socket_strerror($error)); } } } // @TODO delete next line... trigger_error('Client connect failed', E_USER_ERROR); return false; }
/** * Handle socket errors. * * @return void * * @throws SyslogException if a socket error occured. */ protected function handleError() { if (\is_resource($this->sock) && socket_last_error($this->sock)) { $e = new SyslogException(socket_strerror(socket_last_error($this->sock)), socket_last_error($this->sock)); socket_clear_error($this->sock); throw $e; } }
function check_sock_error($area) { $err = socket_last_error(); if ($err > 0) { errorlog("CHECK_SOCK_ERROR(" . $area . "): " . socket_strerror(socket_last_error())); socket_clear_error(); } }
public function destructBot($sMessage = false) { $this->Output('QUIT :' . ($sMessage == false ? $this->oMaster->oConfig->Network['quitmsg'] : $sMessage)); Timers::Delete($this->iPingTimer); @socket_clear_error(); $this->socketShutdown(); $this->Active = false; $this->isWaiting = false; }
/** * Connect to Asterisk * @param bool $reconfig * @return boolean true on success */ public function connect($reconfig = false) { if ($reconfig && !$this->config->isChanged()) { return true; } $this->reconnect = 0; if ($this->socket) { $this->reconnect = 1; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === FALSE) { $this->log("Unable to create socket - " . socket_last_error(), 'ERROR'); } else { while (!@socket_connect($socket, $this->config->host, $this->config->port)) { $this->log("Unable to connect to manager {$this->config->host}:{$this->config->port} - " . socket_last_error($socket), 'ERROR'); if ($this->reconnect && !$reconfig) { usleep($this->reconnect_delay); $this->fireEvent('Loop'); // if we got HUP here, we did connect() once more again, and it can be succeful if (!$this->reconnect) { return true; } } else { $socket = FALSE; break; } } } if ($socket !== FALSE) { socket_clear_error($socket); $this->log("Connected to manager {$this->config->host}:{$this->config->port}", 'DEBUG'); if ($this->reconnect) { @socket_close($this->socket); } $this->socket = $socket; $this->connected = 0; $this->logged_in = 0; $this->reconnect = 0; $this->current_select_timeout = $this->handshake_timeout; $this->config->clearChanged(); return true; } else { if ($reconfig) { $this->log("Fail to change asterisk connection, keep working with old connection", 'ERROR'); } return false; } }
function error($msg = null) { $errCode = socket_last_error($this->hnd); if ($errCode != 0) { //Connection reset by peer if ($errCode == 104) { $this->bConnected = false; } $errMsg = socket_strerror($errCode); $this->sSocErr = "(" . $errCode . ")(" . $errMsg . ")"; socket_clear_error($this->hnd); } elseif (strlen($msg)) { $this->sSocErr = $errMsg; } return false; }
function sock_gets($sock) { global $msgsock; socket_clear_error($msgsock); $buf = socket_read($sock, 4096, PHP_NORMAL_READ); if (CITADEL_DEBUG_PROXY) { syslog(LOG_DEBUG, "gets Read: " . $buf); } if (socket_last_error($sock)) { return false; } if (preg_match("'\n\$'s", $buf)) { $buf = substr($buf, 0, strpos($buf, "\n")); } return $buf; }
public function __construct($message = null) { if (!$message) { $errno = socket_last_error(); } elseif (is_resource($message)) { $errno = socket_last_error($message); } else { parent::__construct((string) $message); return; } $error = socket_strerror($errno); parent::__construct($error, $errno); if (!$message) { socket_clear_error(); } else { socket_clear_error($message); } }
public function connect() { if ($this->is_connected()) { return true; } if ($this->connection = socket_create($this->socket_domain, SOCK_STREAM, $this->socket_domain > 1 ? getprotobyname('tcp') : 0)) { socket_set_option($this->connection, SOL_SOCKET, SO_REUSEADDR, true); if (socket_bind($this->connection, $this->socket_address, $this->socket_port)) { if (socket_listen($this->connection)) { socket_set_nonblock($this->connection); $this->_open_try = false; // сбрасываем флаг попытки открыть сервер return $this->opened = true; } else { throw new \Exception(socket_strerror(socket_last_error($this->connection))); } } else { $error = socket_last_error($this->connection); socket_clear_error($this->connection); error_log('error: ' . $error); switch ($error) { case SOCKET_EADDRINUSE: // если сокет уже открыт - пробуем его закрыть и снова открыть // @TODO socket close self::socket_close(); // @todo recheck this code // closing socket and try restart $this->disconnect(); if (!$this->_open_try) { $this->_open_try = true; return $this->open(); } break; default: throw new \Exception(socket_strerror($error)); } } } // @TODO delete next line... trigger_error('Server open failed', E_USER_ERROR); return false; }
/** * Sends a packet via UDP to the list of name servers. * * This function sends a packet to a nameserver. It is called by * send_udp if the sockets PHP extension is compiled into PHP. * * @param string $packet A packet object to send to the NS list * @param string $packet_data The data in the packet as returned by * the Net_DNS_Packet::data() method * @return object Net_DNS_Packet Returns an answer packet object * @see Net_DNS_Resolver::send_tcp(), Net_DNS_Resolver::send(), * Net_DNS_Resolver::send_udp(), Net_DNS_Resolver::send_udp_no_sock_lib() */ function send_udp_with_sock_lib($packet, $packet_data) { $retrans = $this->retrans; $timeout = $retrans; //$w = error_reporting(0); $ctr = 0; // Create a socket handle for each nameserver foreach ($this->nameservers as $nameserver) { if (($sock[$ctr++] = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) && socket_connect($sock[$ctr - 1], $nameserver, $this->port)) { $peerhost[$ctr - 1] = $nameserver; $peerport[$ctr - 1] = $this->port; socket_set_nonblock($sock[$ctr - 1]); } else { $ctr--; } } //error_reporting($w); if ($ctr == 0) { $this->errorstring = 'no nameservers'; return null; } // Try each nameserver up to $this->retry times for ($i = 0; $i < $this->retry; $i++) { if ($i != 0) { // Set the timeout for each retry based on the number of // nameservers there is a connected socket for. $retrans *= 2; $timeout = (int) ($retrans / $ctr); } // Make sure the timeout is at least 1 second if ($timeout < 1) { $timeout = 1; } // Try each nameserver foreach ($sock as $k => $s) { if ($this->debug) { echo "\n;; send_udp(" . $peerhost[$k] . ':' . $peerport[$k] . '): sending ' . strlen($packet_data) . " bytes\n"; } if (!socket_write($s, $packet_data)) { if ($this->debug) { echo ";; send error\n"; } } $set = array($s); if ($this->debug) { echo ";; timeout set to {$timeout} seconds\n"; } $changed = socket_select($set, $w = null, $e = null, $timeout); if ($changed) { // Test to see if the connection was refused. Linux servers will send // an ICMP message which will cause the client's next system call to // return ECONNREFUSED if the server is not listening on the ip:port queried if (socket_get_option($s, SOL_SOCKET, SO_ERROR) == SOCKET_ECONNREFUSED) { // Unix socket connection was refused if ($this->debug) { echo ';; connection to ' . $peerhost[$k] . ':' . $peerport[$k] . " was refused\n"; } // Try the next server. continue; } // Read the response $buf = @socket_read($s, 512); if ($buf === false) { // No data could be read from socket if ($this->debug) { echo ';; no data could be read from ' . $peerhost[$k] . ':' . $peerport[$k] . "\n"; echo ';; socket_error: ' . socket_strerror(socket_last_error()) . "\n"; } // Reset the non-specific socket error status socket_clear_error(); // Try the next server. continue; } $this->answerfrom = $peerhost[$k]; $this->answersize = strlen($buf); if ($this->debug) { echo ';; answer from ' . $peerhost[$k] . ':' . $peerport[$k] . ': ' . strlen($buf) . " bytes\n"; } $ans = new Net_DNS_Packet($this->debug); if ($ans->parse($buf)) { if ($ans->header->qr != '1') { // Ignore packet if it is not a response continue; } elseif ($ans->header->id != $packet->header->id) { // Ignore packet if the response id does not match the query id continue; } else { // Return the DNS response packet $this->errorstring = $ans->header->rcode; $ans->answerfrom = $this->answerfrom; $ans->answersize = $this->answersize; return $ans; } } } elseif ($this->debug) { echo ";; query to " . $peerhost[$k] . ':' . $peerport[$k] . " timed out\n"; } } } $this->errorstring = 'query timed out'; return null; }
protected function handleSocketReadError() { $errno = socket_last_error($this->socket); if ($errno === 11 || $errno === 35) { throw new MongoCursorTimeoutException('Timed out waiting for data'); } socket_clear_error($this->socket); return socket_strerror($errno); }
static function getRegSpamScore(&$score, array $user, $verbose, $debug, $model) { $o = XenForo_Application::getOptions(); if (trim($o->TPUDetectSpamRegOpenPort) != '') { if (!function_exists('socket_create')) { $model->logScore('PHP function socket_create() not available, you need the PHP socket extension for open port detection to work', 0); return; } $entries = array(); $socks = array(); foreach (explode("\n", $o->TPUDetectSpamRegOpenPort) as $entry) { $entry = explode('|', trim($entry)); if (count($entry) != 2) { continue; } list($points, $port) = $entry; if (!is_numeric($port)) { $port = getservbyname($port, 'tcp'); } if ($port > 0) { socket_clear_error(); if (self::isIPv6($user['ip'])) { $sock = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } else { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } socket_set_nonblock($sock); @socket_connect($sock, $user['ip'], $port); $errno = socket_last_error(); if ($errno == SOCKET_EALREADY || $errno == SOCKET_EINPROGRESS || $errno == 0) { $socks[] = $sock; } else { socket_close($sock); } $entries[] = array('points' => $points, 'port' => $port, 'open' => false); } } $start = microtime(true); while ($socks && microtime(true) - $start < self::TIMEOUT) { $null = null; $write = $socks; socket_select($null, $write, $null, 1); foreach ($write as $k => $sock) { $errno = socket_get_option($sock, SOL_SOCKET, SO_ERROR); if ($errno == 0) { $entries[$k]['open'] = true; } elseif ($errno == SOCKET_ECONNREFUSED) { } elseif ($errno == SOCKET_ETIMEDOUT) { } else { $errmsg = socket_strerror($errno); } unset($socks[$k]); socket_close($sock); } } foreach ($entries as $entry) { if ($entry['open']) { $model->logScore('tpu_detectspamreg_port_fail', $entry['points'], array('port' => $entry['port'])); $points = $entry['points']; if (is_numeric($points)) { $score['points'] += $points; } else { $score[$points] = true; } } else { if ($debug) { $model->logScore('tpu_detectspamreg_port_ok', 0, array('port' => $entry['port'])); } } } } }
/** * 错误信息赋值 */ protected function set_error() { $this->errCode = socket_last_error($this->sock); $this->errMsg = socket_strerror($this->errCode); socket_clear_error($this->sock); }
public function getError() { $error = socket_strerror(socket_last_error($this->_socket)); socket_clear_error($this->_socket); return $error; }
public function receive($socket) { // ! // on all following cases we assume that // socket_select() returned the current socket as "changed" // ! $timeout = 3; // set your timeout /* important */ $socket_recv_return_values['no_data_received'] = false; $socket_recv_return_values['client_disconnected'] = 0; $start = time(); $received_data = null; $received_bytes = null; socket_set_nonblock($socket); socket_clear_error(); while (($t_out = time() - $start >= $timeout) === false and ($read = @socket_recv($socket, $buf, 4096, 0)) >= 1) { $received_data = isset($received_data) ? $received_data . $buf : $buf; $received_bytes = isset($received_bytes) ? $received_bytes + $read : $read; } $last_error = socket_last_error($socket); socket_set_block($socket); if ($t_out === true) { throw new Exception('timeout after ' . (!$received_bytes ? 0 : $received_bytes) . ' bytes', 0); } elseif ($last_error !== false and $last_error !== 0) { throw new Exception(socket_strerror($last_error), $last_error); } else { if ($read === $socket_recv_return_values['no_data_received']) { // client returned NO DATA // but we were in a loop and could have got some data before: if ($received_bytes < 1) { // client is connected but sent NO DATA ? // no: // in this case the client must be "crashed" because - // it is not possible to "send no data" (zero bytes) // socket_select() now returns this socket as "changed" "forever" /*throw new Exception( 'client crashed', 0 // your eCode here );*/ // No Data return to Listen again return FALSE; } else { // client returned DATA return $received_data; } } elseif ($read === $socket_recv_return_values['client_disconnected']) { // client disconnected if ($received_bytes < 1) { // return 'Disconnected'; // client disconnected before/without sending any bytes throw new Exception('client disconnected', 0); } else { // *this value* ^= $socket_recv_return_values['client_disconnected'] // // client disconnected AFTER sending data (we were in a loop!) // socket_select() will return this socket "forever" as "changed" and - // socket_recv() will return *this value* "forever". // we will be "back" again "very soon" to see: // socket_recv() returns *this value* AND no bytes received // which results in disconnect-exception above return $received_data; } } } }
/** * returns number of written bytes or false on timeout **/ public function write($buffer, $length = null) { $this->checkWrite(); socket_clear_error($this->socket); try { if ($length === null) { $result = socket_write($this->socket, $buffer); } else { $result = socket_write($this->socket, $buffer, $length); } } catch (BaseException $e) { // probably connection reset by peer $result = false; } if ($result === false && !$this->isTimedOut()) { throw new NetworkException('socket writing failed: ' . socket_strerror(socket_last_error())); } return $result; }
/** * Create an Exception after a global socket operation failed (like socket creation) * * @param string $messagePrefix * @return self * @uses socket_last_error() to get last global error code * @uses socket_clear_error() to clear global error code * @uses self::createFromCode() to automatically construct exception with full error message */ public static function createFromGlobalSocketOperation($messagePrefix = 'Socket operation failed') { $code = socket_last_error(); socket_clear_error(); return self::createFromCode($code, $messagePrefix); }
public function get_error() { $error_no = socket_last_error($this->server_socket); $error = 'error no: ' . $error_no . ', ' . socket_strerror($error_no); socket_clear_error($this->server_socket); return $error; }
var_dump($res); var_dump(socket_recvfrom($s, $buffer, 100, 0, $name, $vport)); var_dump($buffer); $s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $port = bind_random_port($s, "127.0.0.1"); var_dump($port != 0); var_dump(socket_listen($s)); var_dump(socket_shutdown($s)); $s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $port = bind_random_port($s, "127.0.0.1"); var_dump($port != 0); var_dump(socket_listen($s)); var_dump(socket_close($s)); $s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); @socket_bind($s, "127.0.0.1", 80); if (socket_last_error($s) == 13) { var_dump(socket_strerror(13) == "Permission denied"); socket_clear_error($s); } var_dump(socket_last_error($s)); $fsock = false; $port = pfsockopen_random_port($fsock, "udp://[0:0:0:0:0:0:0:1]"); var_dump($port != 0); var_dump(fwrite($fsock, "foo") > 0); $errnum = null; $errstr = null; $fsock2 = pfsockopen("udp://[::1]", $port, $errnum, $errstr); var_dump($fsock !== false); var_dump($fsock != $fsock2); var_dump($errnum); var_dump($errstr);
public function clearError() { socket_clear_error($this->getHandle()); }
/** * Show errors if $bShowErrors is enabled * If $bExceptions, throws an exception, otherwise prints a message. * If $msg is not empty, show $msg; * * @param string $msg */ public function error($msg = null) { if (!$this->bShowErros && !$this->bExceptions) { return; } $errCode = socket_last_error($this->hnd); if ($errCode != 0) { //Connection reset by peer if ($errCode == 104) { $this->bConnected = false; } $errMsg = socket_strerror($errCode); if ($this->bExceptions) { throw new Exception("Socket error. Code: {$errCode} - Message: {$errMsg}\n"); } else { trigger_error("Socket Error. Code: {$errCode} - Message: {$errMsg}"); } socket_clear_error($this->hnd); } elseif (strlen($msg)) { if ($this->bExceptions) { throw new Exception("Socket error." . $msg); } else { trigger_error("{$msg}\n", E_USER_ERROR); } } }
/** * Run a set of tasks * * @param object $set A set of tasks to run * @param int $timeout Time in seconds for the socket timeout. Max is 10 seconds * * @return void * @see Net_Gearman_Set, Net_Gearman_Task */ public function runSet(Net_Gearman_Set $set, $timeout = null) { $this->set = $set; $totalTasks = $this->set->tasksCount; $taskKeys = array_keys($this->set->tasks); $t = 0; if ($timeout !== null) { $socket_timeout = min(10, (int) $timeout); } else { $socket_timeout = 10; } while (!$this->set->finished()) { if ($timeout !== null) { if (empty($start)) { $start = microtime(true); } else { $now = microtime(true); if ($now - $start >= $timeout) { break; } } } if ($t < $totalTasks) { $k = $taskKeys[$t]; $this->submitTask($this->set->tasks[$k]); if ($this->set->tasks[$k]->type == Net_Gearman_Task::JOB_BACKGROUND || $this->set->tasks[$k]->type == Net_Gearman_Task::JOB_HIGH_BACKGROUND || $this->set->tasks[$k]->type == Net_Gearman_Task::JOB_LOW_BACKGROUND) { $this->set->tasks[$k]->finished = true; $this->set->tasksCount--; } $t++; } $write = null; $except = null; $read = $this->conn; @socket_select($read, $write, $except, $socket_timeout); foreach ($read as $socket) { $err = socket_last_error($socket); // Error 11 is EAGAIN and is normal in non-blocking mode if ($err && $err != 11) { $msg = socket_strerror($err); socket_getpeername($socket, $remote_address, $remote_port); socket_getsockname($socket, $local_address, $local_port); trigger_error("socket_select failed: ({$err}) {$msg}; server: {$remote_address}:{$remote_port}", E_USER_WARNING); } socket_clear_error($socket); $resp = Net_Gearman_Connection::read($socket); if (count($resp)) { $this->handleResponse($resp, $socket, $this->set); } } } }
public function killSocket($sockInt) { if (DEBUG == 1) { echo "Killing socket: " . $sockInt . "\n"; } if ($this->socketInfo[$sockInt]->status == SOCK_ACCEPTED) { $this->acceptedSockets--; } if ($this->socketInfo[$sockInt]->status != SOCK_DEAD) { $this->removeReadSocketFromArray($sockInt); $this->removeWriteSocketFromArray($sockInt); $this->socketInfo[$sockInt]->status = SOCK_DEAD; } if (is_resource($this->socketInfo[$sockInt]->socket)) { if (DEBUG == 1) { echo "Closed socket: " . $sockInt . "\n"; } socket_clear_error($this->socketInfo[$sockInt]->socket); socket_close($this->socketInfo[$sockInt]->socket); } else { if (DEBUG == 1) { echo "Socket already closed: " . $sockInt . "\n"; } } }
/** * Executes the given command in the device. Be *warned* you may need * high times for recv_to and or devread_to depending on the device you * are interacting with. * * @param int $connection_to Connection timeout to server, in milliseconds. * @param int $recv_to Receive timeout from server, in milliseconds. * @param int $command Command. * @param int $devconn_to Timeout when connecting to the device from * server. * @param int $devread_to Timeout when reading from the device from * server. * @param csv $arguments Command arguments, like 'a,b,c' * * @throws Exception on error. * @return void */ public function exec($connection_to, $recv_to, $command, $devconn_to, $devread_to, $arguments = null) { /* Validate connection timeout. */ if (!is_int($connection_to) || $connection_to < 1) { throw new Exception('Connection timeout should be a integer > 0'); } /* Validate receive timeout. */ if (!is_int($recv_to) || $recv_to < 1) { throw new Exception('Receive timeout should be a integer > 0'); } /* Validate device connection timeout. */ if (!is_int($devconn_to) || $devconn_to < 1) { throw new Exception('Device connection timeout should be a integer > 0'); } /* Validate device read timeout. */ if (!is_int($devread_to) || $devread_to < 1) { throw new Exception('Device read timeout should be a integer > 0'); } /* Create socket. */ $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { throw new Exception('Error opening socket: ' . $this->getSocketErrorString()); } /* Set non blocking. */ if (socket_set_nonblock($socket) === false) { throw new Exception('Error setting non blocking mode: ' . $this->getSocketErrorString($socket)); } /* Connect socket. */ $totaltime = 0; $connection_to_tmp = $connection_to / 2; /* XXX WTF ??? XXX */ do { if (@socket_connect($socket, $this->_host, $this->_port) === true) { break; } $readfd = array($socket); $writefd = array($socket); $exfd = array($socket); /* * If wasnt successfull, select() in the socket until timeout or * event occurs. */ $r = @socket_select($readfd, $writefd, $exfd, 0, 0); if ($r === false) { throw new Exception('Error select()ing socket: ' . $this->getSocketErrorString($socket)); } if ($r > 0) { $error = $this->getSocketErrorNumber(); socket_clear_error($socket); if ($error != SOCKET_EINPROGRESS) { if ($error === SOCKET_EALREADY || $error === 56) { break; } else { throw new Exception('Error connecting socket (1): ' . $this->getSocketErrorString(null, $error)); } } } usleep(1000); $totaltime += 1; } while ($totaltime < $connection_to_tmp); if ($totaltime >= $connection_to_tmp) { throw new Exception('Timeout Connecting.'); } /* Form command. */ $commandstr = '<?xml version="1.0" encoding="UTF-8"?>' . "\n"; $commandstr .= '<mdm_request '; $commandstr .= 'xmlns:mdm="http://www.mg.com.ar/MDM-Protocol" '; $commandstr .= "\n"; $commandstr .= 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '; $commandstr .= "\n"; $commandstr .= 'xsi:schemaLocation="'; $commandstr .= 'http://www.mg.com.ar/MDM mdm_request.xsd">' . "\n"; $commandstr .= '<version>0.1.1</version>' . "\n"; $commandstr .= '<device>' . $this->_device . '</device>' . "\n"; $commandstr .= '<connection>' . "\n"; $commandstr .= '<target>' . $this->_connection_target . '</target>'; $commandstr .= "\n"; $commandstr .= '<type>' . $this->_connection . '</type>' . "\n"; $commandstr .= '<connect_timeout>'; $commandstr .= $devconn_to . '</connect_timeout>' . "\n"; $commandstr .= '<recv_timeout>'; $commandstr .= $devread_to . '</recv_timeout>' . "\n"; $commandstr .= '<credential>' . "\n"; $commandstr .= '<username>'; $commandstr .= $this->_connection_username; $commandstr .= '</username>' . "\n"; $commandstr .= '<password>'; $commandstr .= $this->_connection_password; $commandstr .= '</password>' . "\n"; $commandstr .= '</credential>' . "\n"; $commandstr .= '</connection>' . "\n"; $commandstr .= '<command>' . "\n"; $commandstr .= '<type>' . $command . '</type>' . "\n"; if (is_string($arguments) && !empty($arguments)) { $commandstr .= '<arguments><![CDATA[' . $arguments; $commandstr .= ']]></arguments>' . "\n"; } $commandstr .= '</command>' . "\n"; $commandstr .= '</mdm_request>' . "\n"; /* Send command. */ $bufflen = strlen($commandstr); if (socket_write($socket, $commandstr, $bufflen) < $bufflen) { throw new Exception('Error sending command: ' . $this->getSocketErrorString($socket)); } /* Get response. */ /* This is blocking $responsestr = ''; $responsestrlen = 1048576; socket_set_block($socket); $responsestr .= socket_read($socket, $responsestrlen); if ($responsestr === false) { throw new Exception( 'Error reading response: ' . $this->getSocketErrorString($socket) ); } */ $this->_response = ''; $responsestrlen = 1048576; $to = 0; $recv_to_tmp = $recv_to / 2; /* XXX WTF ?? XXX */ do { $buffer = ''; $readfd = array($socket); $writefd = array($socket); $exfd = array($socket); /* * If wasnt successfull, select() in the socket until timeout or * event occurs. */ $r = @socket_select($readfd, $write, $exfd, 0, 0); if ($r === false) { throw new Exception('Error select()ing socket: ' . $this->getSocketErrorString($socket)); } if (count($exfd) > 0) { throw new Exception('Error reading command 1: ' . $this->getSocketErrorString($socket)); } if (count($readfd) > 0) { $r = @socket_read($socket, $responsestrlen); if ($r === false) { throw new Exception('Error reading command 2: ' . $this->getSocketErrorString($socket)); } else { $this->_response .= $r; } } usleep(1000); $to += 1; if ($to >= $recv_to_tmp) { throw new Exception('Read timeout from server.'); } } while (strstr($this->_response, '</mdm_response>') === false); /* Done. */ socket_close($socket); /*var_dump($this->_response); */ /* Validate response. */ $this->_responsexmldoc = new DOMDocument(); if (!$this->_responsexmldoc->loadXML($this->_response)) { throw new Exception('Error loading xml: ' . print_r(libxml_get_last_error(), true) . ' : ' . print_r($this->_response, true)); } if (!$this->_responsexmldoc->schemaValidate($this->_schemafile)) { throw new Exception('Error validating xml: ' . print_r(libxml_get_last_error(), true)); } /* Work with a simplexml object from now on. */ $this->_responsexmldoc = new SimpleXMLElement($this->_response); }
function do_monitor_list($portmonlist, &$serverhistlist) { global $global_ip_array; global $global_remoteserver; global $global_remoteport; $loopcount = 0; while (true) { $count = 0; $loopcount++; foreach ($portmonlist as $s => &$serv) { foreach ($serv as $k => &$data) { $nname = $k; if ($data[4] === 'done') { continue; } if (isset($global_ip_array[$data[0]])) { $ip = $global_ip_array[$data[0]]; } else { $ip = "Silly screwup. Can't find dns for {$data[0]}\n"; } if (!validate_ipaddress($ip)) { //print("failed Dns $ip for *{$data[0]}*\n"); $obj['portstatus'] = 'off'; //$obj['errornumber'] = 100; $obj['errorstring'] = "DNS failed for {$ip}"; $obj['portnname'] = $nname; $data[2] = null; $data[4] = 'done'; $serverhistlist[$s][$k] = $obj; socket_clear_error(); continue; } $ret = socket_connect($data[2], $ip, $data[1]); $err = socket_last_error($data[2]); if ($ret === true || $err === 10056 || $err === 0) { fclose($data[2]); $data[2] = null; $data[4] = 'done'; $obj['portstatus'] = 'on'; $obj['errorstring'] = "SSS"; // $obj['errornumber'] = 0; $obj['portnname'] = $nname; $serverhistlist[$s][$k] = $obj; continue; } //print("$s: $k, $ret, $err $here\n"); if ($err === 115 || $err === 114 || $err === 10035 || $err === 10037) { $data[4] = 'notdone'; $count++; if ($loopcount < 14) { //print("Timeout not reached ... " . time() . " $startmon\n"); } else { $obj['portstatus'] = 'off'; //$obj['errornumber'] = $err; $obj['errorstring'] = "Timeout"; $obj['portnname'] = $nname; $data[2] = null; $data[4] = 'done'; $serverhistlist[$s][$k] = $obj; socket_clear_error(); } continue; } //$obj['errornumber'] = $err; $strerror = socket_strerror($err); $vrttt = var_export($ret, true); if (!$err || !$strerror || $strerror === "Success") { $obj['errorstring'] = "Got NO error. Errno {$err}... ret was {$vrttt}"; $obj['portstatus'] = 'on'; } else { $obj['errorstring'] = "({$err}) {$strerror} (ret: {$vrttt})"; $obj['portstatus'] = 'off'; } $obj['portnname'] = $nname; $data[2] = null; $data[4] = 'done'; $serverhistlist[$s][$k] = $obj; socket_clear_error(); } } if ($count === 0) { break; } sleep(1); } return $serverhistlist; }
public function __construct($message, $errno) { socket_clear_error(); parent::__construct($message, $errno); }
protected function disconnect($socket, $triggerClosed = true, $sockErrNo = null) { $disconnectedUser = $this->getUserBySocket($socket); if ($disconnectedUser !== null) { unset($this->users[$disconnectedUser->id]); if (array_key_exists($disconnectedUser->id, $this->sockets)) { unset($this->sockets[$disconnectedUser->id]); } if (!is_null($sockErrNo)) { socket_clear_error($socket); } if ($triggerClosed) { $this->closed($disconnectedUser); socket_close($disconnectedUser->socket); } else { $message = $this->frame('', $disconnectedUser, 'close'); @socket_write($disconnectedUser->socket, $message, strlen($message)); } } }
/** * dispatchWork * * @param string $function * @param array $parameters * @param object $socket */ protected function dispatchWork($f,$p) { $this->Log->debug(__METHOD__); // If this work is to be done locally set it up right here if('local'==$this->work['method']) { // dispatch the API call include_once($_SERVER['SCRIPT_FILENAME']); $this->Log->debug('include_once('.$_SERVER['SCRIPT_FILENAME'].')'); // The expected class name $class_name = ANYAPI_CALL_CLASS; if(!class_exists($class_name)) { $this->Log->error("Code 531: Unable to locate the expected class named '".$class_name."' in ".$_SERVER['SCRIPT_FILENAME']); $response['error'] = array('code'=>'531','message'=>'Internal system error'); $this->out($response); // terminates } // Try and instantiate the class try { $anyapi = new $class_name; } catch (Exception $e) { $this->Log->error("Code 540: Unable instantiate class named '".$class_name."' got exception ".$e); $response['error'] = array('code'=>'540','message'=>'Internal system error'); $this->out($response); // terminates } // There must be a better way to do this - uck!! if(0==count($p)) { return $anyapi->$f(); } elseif(1==count($p)) { return $anyapi->$f($p[0]); } elseif(2==count($p)) { return $anyapi->$f($p[0],$p[1]); } elseif(3==count($p)) { return $anyapi->$f($p[0],$p[1],$p[2]); } elseif(4==count($p)) { return $anyapi->$f($p[0],$p[1],$p[2],$p[3]); } elseif(5==count($p)) { return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4]); } elseif(6==count($p)) { return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5]); } elseif(7==count($p)) { return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6]); } elseif(8==count($p)) { return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6],$p[7]); } elseif(9==count($p)) { return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6],$p[7],$p[8]); } elseif(10==count($p)){ return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6],$p[7],$p[8],$p[9]); } elseif(11==count($p)){ return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6],$p[7],$p[8],$p[9],$p[10]); } elseif(12==count($p)){ return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6],$p[7],$p[8],$p[9],$p[10],$p[11]); } elseif(13==count($p)){ return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6],$p[7],$p[8],$p[9],$p[10],$p[11],$p[12]); } elseif(14==count($p)){ return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6],$p[7],$p[8],$p[9],$p[10],$p[11],$p[12],$p[13]); } elseif(15==count($p)){ return $anyapi->$f($p[0],$p[1],$p[2],$p[3],$p[4],$p[5],$p[6],$p[7],$p[8],$p[9],$p[10],$p[11],$p[12],$p[13],$p[14]); } $this->Log->error("Code 563: AnyApi only supports 15x input parameters for an action - got an elegant fix?"); $response['error'] = array('code'=>'563','message'=>'Internal system error'); return $response; } // Check we are setup for beanstalkd since it's the only type supported at the moment if('beanstalkd' != $this->work['queue']['type']) { $this->Log->error("Code 565: AnyApi only supports work[queue][type] = 'beanstalkd'"); $response['error'] = array('code'=>'565','message'=>'Internal system error'); return $response; } $socket = null; // Only create a return data socket if the worker will not be doing an external callback if(!isset($this->request['return_options']['callback']['url']) && !isset($this->request['return_options']['callback']['email'])) { $this->Log->debug("Creating an internet tcp stream socket for work return data"); $socket = socket_create(AF_INET,SOCK_STREAM,getprotobyname('tcp')); // Make sure we created the socket if(!$socket) { $this->Log->error("Code 490: Unable to create work queue return data socket!"); $response['error'] = array('code'=>'490','message'=>'Internal system error'); $this->out($response); // terminates } // Bind the socket to something we can use $return_token = false; while(!$return_token) { $port_delta = $this->work['queue']['callback_socket']['max_port'] - $this->work['queue']['callback_socket']['min_port']; $port = $this->work['queue']['callback_socket']['min_port'] + rand(0,$port_delta); if(@socket_bind($socket,$this->work['queue']['callback_socket']['address'],$port)) { $this->Log->debug('Bound socket to '.$this->work['queue']['callback_socket']['address'].':'.$port.' ready for work queue return data'); $return_token = md5(mt_rand(0,10000000).microtime(true)); } } $this->request['return_options']['callback']['socket'] = array( 'address' =>$this->work['queue']['callback_socket']['address'], 'port' => $port, 'token' => $return_token, 'timeout' => $this->work['queue']['callback_socket']['timeout'] ); } // Beanstalk! include_once(dirname(__FILE__).'/pheanstalk/pheanstalk_init.php'); $Pheanstalk = new Pheanstalk($this->work['queue']['host'],$this->work['queue']['port'],$this->work['queue']['connect_timeout']); $job_id = null; try { $job_id = $Pheanstalk ->useTube(ANYAPI_CALL_CLASS) // use the class name for the tube name ->put(gzcompress(serialize(array($f,$p,$this->request['return_options'])),9)); } catch (Exception $e) { $this->Log->error("Code 589: Unable to place work onto beanstalkd queue at ".$this->work['queue']['host'].':'.$this->work['queue']['port']); $response['error'] = array('code'=>'589','message'=>'Internal system error'); return $response; } $this->Log->debug("Work placed on beanstalkd queue with job_id:".$job_id); // Wait for callback response from the worker into the socket here socket_listen($socket); $this->Log->debug("Socket listening for response data for job_id:".$job_id); socket_set_nonblock($socket); $this->Log->debug("Socket set to non-blocking mode for job_id:".$job_id); // Wait until timeout for the callback socket response $timeout_timestamp = time() + $this->work['queue']['callback_socket']['timeout']; $usleep_interval = 100; // 1/10000th of a second $connection = false; while(!$connection) { $connection = @socket_accept($socket); usleep($usleep_interval); $usleep_interval = $usleep_interval*1.1; // gradual scaling back of $usleep_interval if(time() > $timeout_timestamp) { $this->Log->error('Code 456: Timed out after while for response data from job_id: '.$job_id); $response['error'] = array('code'=>'456','message'=>'Internal system error'); return $response; } } // Slurp up the data in a buffered manner $data = null; do { @socket_recv($connection, $buffer,1024,MSG_DONTWAIT); // Protect against resource temporarily unavailable problems if(11 == socket_last_error($connection)) { socket_clear_error($connection); $buffer = 'CONTINUE'; } else { $data .= $buffer; } } while (!empty($buffer)); // Uncompress the data returned through the socket $data = @gzuncompress($data); // Strip apart data and token componets $token = substr($data,(strlen($data)-strlen($this->request['return_options']['callback']['socket']['token'])),strlen($this->request['return_options']['callback']['socket']['token'])); $data = substr($data,0,strlen($data)-strlen($this->request['return_options']['callback']['socket']['token'])-1 ); // Make sure the token matches the expected value if($token != $this->request['return_options']['callback']['socket']['token']) { $this->Log->error('Code 472: Invalid return data token for job_id: '.$job_id); $response['error'] = array('code'=>'472','message'=>'Internal system error'); return $response; } // Detect if this is raw binary data or not as indicated by a BIN\0 at the front of the string if("BIN\0" == substr($data,0,4)) { return substr($data,4); } return json_decode($data,true); }