3 * A general ConnectionHelper class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseConnectionHelper extends BaseHubHelper implements Registerable, ProtocolHandler {
26 const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
31 private $protocol = 'invalid';
46 private $sentData = 0;
54 * Whether this connection is initialized
56 private $isInitialized = false;
59 * Whether this connection is shutted down
61 private $shuttedDown = false;
64 * Currently queued chunks
66 private $queuedChunks = array();
71 private $currentFinalHash = '';
74 * Protected constructor
76 * @param $className Name of the class
79 protected function __construct ($className) {
80 // Call parent constructor
81 parent::__construct($className);
83 // Initialize output stream
84 $streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_output_stream_class');
86 // And add it to this connection helper
87 $this->setOutputStreamInstance($streamInstance);
89 // Init state which sets the state to 'init'
92 // Register this connection helper
93 Registry::getRegistry()->addInstance('connection', $this);
97 * Getter for real class name, overwrites generic method and is final
99 * @return $class Name of this class
101 public final function __toString () {
102 // Class name representation
103 $class = self::getConnectionClassName($this->getAddress(), $this->getPort(), parent::__toString());
110 * Getter for port number to satify ProtocolHandler
112 * @return $port The port number
114 public final function getPort () {
119 * Setter for port number to satify ProtocolHandler
121 * @param $port The port number
124 protected final function setPort ($port) {
129 * Getter for protocol
131 * @return $protocol Used protocol
133 public final function getProtocol () {
134 return $this->protocol;
138 * Setter for protocol
140 * @param $protocol Used protocol
143 protected final function setProtocol ($protocol) {
144 $this->protocol = $protocol;
148 * Getter for IP address
150 * @return $address The IP address
152 public final function getAddress () {
153 return $this->address;
157 * Setter for IP address
159 * @param $address The IP address
162 protected final function setAddress ($address) {
163 $this->address = $address;
167 * Initializes the current connection
170 * @throws SocketOptionException If setting any socket option fails
172 protected function initConnection () {
173 // Get socket resource
174 $socketResource = $this->getSocketResource();
176 // Set the option to reuse the port
177 if (!socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1)) {
178 // Handle this socket error with a faked recipientData array
179 $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
182 // @TODO Move this to the socket error handler
183 throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
187 * Set socket to non-blocking mode before trying to establish a link to
188 * it. This is now the default behaviour for all connection helpers who
189 * call initConnection(); .
191 if (!socket_set_nonblock($socketResource)) {
192 // Handle this socket error with a faked recipientData array
193 $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
196 throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
199 // Last step: mark connection as initialized
200 $this->isInitialized = true;
204 * Attempts to connect to a peer by given IP number and port from a valid
205 * recipientData array with currently configured timeout.
207 * @param $recipientData A valid recipient data array, 0=IP; 1=PORT
208 * @return $isConnected Whether the connection went fine
209 * @see Please see http://de.php.net/manual/en/function.socket-connect.php#84465 for original code
210 * @todo Rewrite the while() loop to a iterator to not let the software stay very long here
212 protected function connectToPeerByRecipientDataArray (array $recipientData) {
213 // Only call this if the connection is initialized by initConnection()
214 assert($this->isInitialized === true);
219 // "Cache" socket resource and timeout config
220 $socketResource = $this->getSocketResource();
221 $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
224 $this->debugOutput('CONNECTION-HELPER: Trying to connect to ' . $recipientData[0] . ':' . $recipientData[1] . ' with socketResource[' . gettype($socketResource) . ']=' . $socketResource . ' ...');
226 // Try to connect until it is connected
227 while ($isConnected = !@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
228 // Get last socket error
229 $socketError = socket_last_error($socketResource);
231 // Skip any errors which may happen on non-blocking connections
232 if (($socketError == SOCKET_EINPROGRESS) || ($socketError == SOCKET_EALREADY)) {
233 // Now, is that attempt within parameters?
234 if ((time() - $time) >= $timeout) {
235 // Didn't work within timeout
236 $isConnected = false;
240 // Sleep about one second
242 } elseif ($socketError != 0) {
243 // Stop on everything else pronto
244 $isConnected = false;
254 * Static "getter" for this connection class' name
256 * @param $address IP address
257 * @param $port Port number
258 * @param $className Original class name
259 * @return $class Expanded class name
261 public static function getConnectionClassName ($address, $port, $className) {
263 $class = $address . ':' . $port . ':' . $className;
270 * Initializes the peer's state which sets it to 'init'
274 private function initState() {
276 * Get the state factory and create the initial state, we don't need
277 * the state instance here
279 PeerStateFactory::createPeerStateInstanceByName('init', $this);
283 * "Getter" for raw data from a package array. A fragmenter is used which
284 * will returns us only so many raw data which fits into the back buffer.
285 * The rest is being held in a back-buffer and waits there for the next
286 * cycle and while be then sent.
288 * This method does 4 simple steps:
289 * 1) Aquire fragmenter object instance from the factory
290 * 2) Handle over the package data array to the fragmenter
292 * 4) Finally return the chunk (array) to the caller
294 * @param $packageData Raw package data array
295 * @return $chunkData Raw data chunk
297 private function getRawDataFromPackageArray (array $packageData) {
298 // Get the fragmenter instance
299 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
301 // Implode the package data array and fragement the resulting string, returns the final hash
302 $finalHash = $fragmenterInstance->fragmentPackageArray($packageData, $this);
303 if ($finalHash !== true) {
304 $this->currentFinalHash = $finalHash;
308 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: currentFinalHash=' . $this->currentFinalHash);
310 // Get the next raw data chunk from the fragmenter
311 $rawDataChunk = $fragmenterInstance->getNextRawDataChunk($this->currentFinalHash);
313 // Get chunk hashes and chunk data
314 $chunkHashes = array_keys($rawDataChunk);
315 $chunkData = array_values($rawDataChunk);
317 // Is the required data there?
318 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: chunkHashes[]=' . count($chunkHashes) . ',chunkData[]=' . count($chunkData));
319 if ((isset($chunkHashes[0])) && (isset($chunkData[0]))) {
320 // Remember this chunk as queued
321 $this->queuedChunks[$chunkHashes[0]] = $chunkData[0];
323 // Return the raw data
324 return $chunkData[0];
326 // Return zero string
332 * "Accept" a visitor by simply calling it back
334 * @param $visitorInstance A Visitor instance
337 protected final function accept (Visitor $visitorInstance) {
338 // Just call the visitor
339 $visitorInstance->visitConnectionHelper($this);
343 * Sends raw package data to the recipient
345 * @param $packageData Raw package data
346 * @return $totalSentBytes Total sent bytes to the peer
347 * @throws InvalidSocketException If we got a problem with this socket
349 public function sendRawPackageData (array $packageData) {
350 // The helper's state must be 'connected'
351 $this->getStateInstance()->validatePeerStateConnected();
353 // Cache buffer length
354 $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
361 // Fill sending buffer with data
362 while ((strlen($rawData) < $bufferSize) && (strlen($dataStream) > 0)) {
363 // Convert the package data array to a raw data stream
364 $dataStream = $this->getRawDataFromPackageArray($packageData);
365 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Adding ' . strlen($dataStream) . ' bytes to the sending buffer ...');
366 $rawData .= $dataStream;
369 // Nothing to sent is bad news, so assert on it
370 assert(strlen($rawData) > 0);
372 // Encode the raw data with our output-stream
373 $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
375 // Calculate difference
376 $this->diff = $bufferSize - strlen($encodedData);
378 // Get socket resource
379 $socketResource = $this->getSocketResource();
385 while ($sentBytes !== false) {
387 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sending out ' . strlen($encodedData) . ' bytes,bufferSize=' . $bufferSize . ',diff=' . $this->diff);
388 $sentBytes = @socket_write($socketResource, $encodedData, ($bufferSize - $this->diff));
390 // If there was an error, we don't continue here
391 if ($sentBytes === false) {
392 // Handle the error with a faked recipientData array
393 $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
396 throw new InvalidSocketException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
397 } elseif (($sentBytes == 0) && (strlen($encodedData) > 0)) {
398 // Nothing sent means we are done
399 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
403 // The difference between sent bytes and length of raw data should not go below zero
404 assert((strlen($encodedData) - $sentBytes) >= 0);
406 // Add total sent bytes
407 $totalSentBytes += $sentBytes;
409 // Cut out the last unsent bytes
410 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sent out ' . $sentBytes . ' of ' . strlen($encodedData) . ' bytes ...');
411 $encodedData = substr($encodedData, $sentBytes);
413 // Calculate difference again
414 $this->diff = $bufferSize - strlen($encodedData);
417 if (strlen($encodedData) <= 0) {
418 // Abort here, all sent!
419 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
425 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: totalSentBytes=' . $totalSentBytes);
426 return $totalSentBytes;
430 * Marks this connection as shutted down
434 protected final function markConnectionShuttedDown () {
435 /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ' has been marked as shutted down');
436 $this->shuttedDown = true;
438 // And remove the (now invalid) socket
439 $this->setSocketResource(false);
443 * Getter for shuttedDown
445 * @return $shuttedDown Whether this connection is shutted down
447 public final function isShuttedDown () {
448 /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
449 return $this->shuttedDown;
452 // ************************************************************************
453 // Socket error handler call-back methods
454 // ************************************************************************
457 * Handles socket error 'connection timed out', but does not clear it for
458 * later debugging purposes.
460 * @param $socketResource A valid socket resource
462 * @throws SocketConnectionException The connection attempts fails with a time-out
464 protected function socketErrorConnectionTimedOutHandler ($socketResource) {
465 // Get socket error code for verification
466 $socketError = socket_last_error($socketResource);
469 $errorMessage = socket_strerror($socketError);
471 // Shutdown this socket
472 $this->shutdownSocket($socketResource);
475 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
479 * Handles socket error 'resource temporary unavailable', but does not
480 * clear it for later debugging purposes.
482 * @param $socketResource A valid socket resource
484 * @throws SocketConnectionException The connection attempts fails with a time-out
486 protected function socketErrorResourceUnavailableHandler ($socketResource) {
487 // Get socket error code for verification
488 $socketError = socket_last_error($socketResource);
491 $errorMessage = socket_strerror($socketError);
493 // Shutdown this socket
494 $this->shutdownSocket($socketResource);
497 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
501 * Handles socket error 'connection refused', but does not clear it for
502 * later debugging purposes.
504 * @param $socketResource A valid socket resource
506 * @throws SocketConnectionException The connection attempts fails with a time-out
508 protected function socketErrorConnectionRefusedHandler ($socketResource) {
509 // Get socket error code for verification
510 $socketError = socket_last_error($socketResource);
513 $errorMessage = socket_strerror($socketError);
515 // Shutdown this socket
516 $this->shutdownSocket($socketResource);
519 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
523 * Handles socket error 'no route to host', but does not clear it for later
524 * debugging purposes.
526 * @param $socketResource A valid socket resource
528 * @throws SocketConnectionException The connection attempts fails with a time-out
530 protected function socketErrorNoRouteToHostHandler ($socketResource) {
531 // Get socket error code for verification
532 $socketError = socket_last_error($socketResource);
535 $errorMessage = socket_strerror($socketError);
537 // Shutdown this socket
538 $this->shutdownSocket($socketResource);
541 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
545 * Handles socket error 'operation already in progress' which happens in
546 * method connectToPeerByRecipientDataArray() on timed out connection
549 * @param $socketResource A valid socket resource
551 * @throws SocketConnectionException The connection attempts fails with a time-out
553 protected function socketErrorOperationAlreadyProgressHandler ($socketResource) {
554 // Get socket error code for verification
555 $socketError = socket_last_error($socketResource);
558 $errorMessage = socket_strerror($socketError);
560 // Half-shutdown this socket (see there for difference to shutdownSocket())
561 $this->halfShutdownSocket($socketResource);
564 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
568 * Handles socket "error" 'operation now in progress' which can be safely
569 * passed on with non-blocking connections.
571 * @param $socketResource A valid socket resource
574 protected function socketErrorOperationInProgressHandler ($socketResource) {
575 $this->debugOutput('CONNECTION: Operation is now in progress, this is usual for non-blocking connections and is no bug.');