3 * A general ConnectionHelper class
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.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 BaseHubSystemHelper implements Registerable, ProtocolHandler {
26 const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x9100;
29 * Connection type 'incoming'
31 const CONNECTION_TYPE_INCOMING = 'incoming';
34 * Connection type 'outgoing'
36 const CONNECTION_TYPE_OUTGOING = 'outgoing';
39 * Connection type 'server'
41 const CONNECTION_TYPE_SERVER = 'server';
46 private $protocol = 'invalid';
61 private $sentData = 0;
64 * Whether this connection is initialized
66 private $isInitialized = FALSE;
69 * Whether this connection is shutted down
71 private $shuttedDown = FALSE;
74 * Currently queued chunks
76 private $queuedChunks = array();
81 private $currentFinalHash = '';
84 * Protected constructor
86 * @param $className Name of the class
89 protected function __construct ($className) {
90 // Call parent constructor
91 parent::__construct($className);
93 // Init state which sets the state to 'init'
96 // Initialize output stream
97 $streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_output_stream_class');
99 // And add it to this connection helper
100 $this->setOutputStreamInstance($streamInstance);
102 // Get package instance from factory
103 $packageInstance = NetworkPackageFactory::createNetworkPackageInstance();
105 // ... and set it here
106 $this->setPackageInstance($packageInstance);
108 // Register this connection helper
109 Registry::getRegistry()->addInstance('connection', $this);
111 // Get the fragmenter instance
112 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
115 $this->setFragmenterInstance($fragmenterInstance);
119 * Getter for real class name, overwrites generic method and is final
121 * @return $class Name of this class
123 public final function __toString () {
124 // Class name representation
125 $class = self::getConnectionClassName($this->getAddress(), $this->getPort(), parent::__toString());
132 * Getter for port number to satify ProtocolHandler
134 * @return $port The port number
136 public final function getPort () {
141 * Setter for port number to satify ProtocolHandler
143 * @param $port The port number
146 protected final function setPort ($port) {
151 * Getter for protocol
153 * @return $protocol Used protocol
155 public final function getProtocol () {
156 return $this->protocol;
160 * Setter for protocol
162 * @param $protocol Used protocol
165 protected final function setProtocol ($protocol) {
166 $this->protocol = $protocol;
170 * Getter for IP address
172 * @return $address The IP address
174 public final function getAddress () {
175 return $this->address;
179 * Setter for IP address
181 * @param $address The IP address
184 protected final function setAddress ($address) {
185 $this->address = $address;
189 * Initializes the current connection
192 * @throws SocketOptionException If setting any socket option fails
194 protected function initConnection () {
195 // Get socket resource
196 $socketResource = $this->getSocketResource();
198 // Set the option to reuse the port
199 if (!socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1)) {
200 // Handle this socket error with a faked recipientData array
201 $this->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
204 // @TODO Move this to the socket error handler
205 throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
209 * Set socket to non-blocking mode before trying to establish a link to
210 * it. This is now the default behaviour for all connection helpers who
211 * call initConnection(); .
213 if (!socket_set_nonblock($socketResource)) {
214 // Handle this socket error with a faked recipientData array
215 $helperInstance->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
218 throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
221 // Last step: mark connection as initialized
222 $this->isInitialized = TRUE;
226 * Attempts to connect to a peer by given IP number and port from a valid
227 * recipientData array with currently configured timeout.
229 * @param $recipientData A valid recipient data array, 0=IP; 1=PORT
230 * @return $isConnected Whether the connection went fine
231 * @see Please see http://de.php.net/manual/en/function.socket-connect.php#84465 for original code
232 * @todo Rewrite the while() loop to a iterator to not let the software stay very long here
234 protected function connectToPeerByRecipientData (array $recipientData) {
235 // Only call this if the connection is initialized by initConnection()
236 assert($this->isInitialized === TRUE);
241 // "Cache" socket resource and timeout config
242 $socketResource = $this->getSocketResource();
243 $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
246 self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Trying to connect to ' . $recipientData[0] . ':' . $recipientData[1] . ' with socketResource[' . gettype($socketResource) . ']=' . $socketResource . ' ...');
248 // Try to connect until it is connected
249 while ($isConnected = !@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
250 // Get last socket error
251 $socketError = socket_last_error($socketResource);
253 // Skip any errors which may happen on non-blocking connections
254 if (($socketError == SOCKET_EINPROGRESS) || ($socketError == SOCKET_EALREADY)) {
255 // Now, is that attempt within parameters?
256 if ((time() - $time) >= $timeout) {
257 // Didn't work within timeout
258 $isConnected = FALSE;
262 // Sleep about one second
264 } elseif ($socketError != 0) {
265 // Stop on everything else pronto
266 $isConnected = FALSE;
271 // Is the peer connected?
272 if ($isConnected === TRUE) {
273 // Connection is fully established here, so change the state.
274 PeerStateFactory::createPeerStateInstanceByName('connected', $this);
277 * There was a problem connecting to the peer (this state is a meta
278 * state until the error handler has found the real cause).
280 PeerStateFactory::createPeerStateInstanceByName('problem', $this);
288 * Static "getter" for this connection class' name
290 * @param $address IP address
291 * @param $port Port number
292 * @param $className Original class name
293 * @return $class Expanded class name
295 public static function getConnectionClassName ($address, $port, $className) {
297 $class = $address . ':' . $port . ':' . $className;
304 * Initializes the peer's state which sets it to 'init'
308 private function initState() {
310 * Get the state factory and create the initial state, we don't need
311 * the state instance here
313 PeerStateFactory::createPeerStateInstanceByName('init', $this);
317 * "Getter" for raw data from a package array. A fragmenter is used which
318 * will returns us only so many raw data which fits into the back buffer.
319 * The rest is being held in a back-buffer and waits there for the next
320 * cycle and while be then sent.
322 * This method does 2 simple steps:
323 * 1) Request a chunk from set fragmenter instance
324 * 2) Finally return the chunk (array) to the caller
326 * @param $packageData Raw package data array
327 * @return $chunkData Raw data chunk
329 private function getRawDataFromPackageArray (array $packageData) {
331 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: currentFinalHash=' . $this->currentFinalHash);
333 // Make sure the final hash is set
334 assert((is_string($this->currentFinalHash)) && (!empty($this->currentFinalHash)));
336 // Get the next raw data chunk from the fragmenter
337 $rawDataChunk = $this->getFragmenterInstance()->getNextRawDataChunk($this->currentFinalHash);
340 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: rawDataChunk=' . print_r($rawDataChunk, TRUE));
342 // Get chunk hashes and chunk data
343 $chunkHashes = array_keys($rawDataChunk);
344 $chunkData = array_values($rawDataChunk);
346 // Is the required data there?
347 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: chunkHashes[]=' . count($chunkHashes) . ',chunkData[]=' . count($chunkData));
348 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('chunkData='.print_r($chunkData, TRUE));
349 if ((isset($chunkHashes[0])) && (isset($chunkData[0]))) {
350 // Remember this chunk as queued
351 $this->queuedChunks[$chunkHashes[0]] = $chunkData[0];
353 // Return the raw data
354 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Returning ' . strlen($chunkData[0]) . ' bytes from ' . __METHOD__ . ' ...');
355 return $chunkData[0];
357 // Return zero string
358 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Returning zero bytes from ' . __METHOD__ . '!');
364 * "Accept" a visitor by simply calling it back
366 * @param $visitorInstance A Visitor instance
369 protected final function accept (Visitor $visitorInstance) {
370 // Just call the visitor
371 $visitorInstance->visitConnectionHelper($this);
375 * Sends raw package data to the recipient
377 * @param $packageData Raw package data
379 * @throws InvalidSocketException If we got a problem with this socket
381 public function sendRawPackageData (array $packageData) {
382 // The helper's state must be 'connected'
383 $this->getStateInstance()->validatePeerStateConnected();
385 // Implode the package data array and fragement the resulting string, returns the final hash
386 $finalHash = $this->getFragmenterInstance()->fragmentPackageArray($packageData, $this);
388 // Is the final hash set?
389 if ($finalHash !== TRUE) {
391 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Setting finalHash=' . $finalHash . ',currentFinalHash[' . gettype($this->currentFinalHash) . ']=' . $this->currentFinalHash);
394 $this->currentFinalHash = $finalHash;
397 // Reset serial number
398 $this->getFragmenterInstance()->resetSerialNumber($this->currentFinalHash);
404 // Fill sending buffer with data
405 while (strlen($dataStream) > 0) {
407 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: packageData=' . print_r($packageData, TRUE));
409 // Convert the package data array to a raw data stream
410 $dataStream = $this->getRawDataFromPackageArray($packageData);
411 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Adding ' . strlen($dataStream) . ' bytes to the sending buffer ...');
412 $rawData .= $dataStream;
415 // Nothing to sent is bad news, so assert on it
416 assert(strlen($rawData) > 0);
418 // Calculate buffer size
419 $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
421 // Encode the raw data with our output-stream
422 $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
425 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: socketResource[]=' . gettype($this->getSocketResource()) . PHP_EOL);
428 $encodedDataArray = array(
429 NetworkPackage::RAW_FINAL_HASH_INDEX => $this->currentFinalHash,
430 NetworkPackage::RAW_ENCODED_DATA_INDEX => $encodedData,
431 NetworkPackage::RAW_SENT_BYTES_INDEX => 0,
432 NetworkPackage::RAW_SOCKET_INDEX => $this->getSocketResource(),
433 NetworkPackage::RAW_BUFFER_SIZE_INDEX => $bufferSize,
434 NetworkPackage::RAW_DIFF_INDEX => 0
437 // Calculate difference
438 $diff = $encodedDataArray[NetworkPackage::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[NetworkPackage::RAW_ENCODED_DATA_INDEX]);
440 // Push raw data to the package's outgoing stack
441 $this->getPackageInstance()->getStackerInstance()->pushNamed(NetworkPackage::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
445 * Marks this connection as shutted down
449 protected final function markConnectionShuttedDown () {
450 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $this->__toString() . ' has been marked as shutted down');
451 $this->shuttedDown = TRUE;
453 // And remove the (now invalid) socket
454 $this->setSocketResource(FALSE);
458 * Getter for shuttedDown
460 * @return $shuttedDown Whether this connection is shutted down
462 public final function isShuttedDown () {
463 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
464 return $this->shuttedDown;
467 // ************************************************************************
468 // Socket error handler call-back methods
469 // ************************************************************************
472 * Handles socket error 'connection timed out', but does not clear it for
473 * later debugging purposes.
475 * @param $socketResource A valid socket resource
476 * @param $recipientData An array with two elements: 0=IP number, 1=port number
478 * @throws SocketConnectionException The connection attempts fails with a time-out
480 protected function socketErrorConnectionTimedOutHandler ($socketResource, array $recipientData) {
481 // Get socket error code for verification
482 $socketError = socket_last_error($socketResource);
485 $errorMessage = socket_strerror($socketError);
487 // Shutdown this socket
488 $this->shutdownSocket($socketResource);
491 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
495 * Handles socket error 'resource temporary unavailable', but does not
496 * clear it for later debugging purposes.
498 * @param $socketResource A valid socket resource
499 * @param $recipientData An array with two elements: 0=IP number, 1=port number
501 * @throws SocketConnectionException The connection attempts fails with a time-out
503 protected function socketErrorResourceUnavailableHandler ($socketResource, array $recipientData) {
504 // Get socket error code for verification
505 $socketError = socket_last_error($socketResource);
508 $errorMessage = socket_strerror($socketError);
510 // Shutdown this socket
511 $this->shutdownSocket($socketResource);
514 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
518 * Handles socket error 'connection refused', but does not clear it for
519 * later debugging purposes.
521 * @param $socketResource A valid socket resource
522 * @param $recipientData An array with two elements: 0=IP number, 1=port number
524 * @throws SocketConnectionException The connection attempts fails with a time-out
526 protected function socketErrorConnectionRefusedHandler ($socketResource, array $recipientData) {
527 // Get socket error code for verification
528 $socketError = socket_last_error($socketResource);
531 $errorMessage = socket_strerror($socketError);
533 // Shutdown this socket
534 $this->shutdownSocket($socketResource);
537 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
541 * Handles socket error 'no route to host', but does not clear it for later
542 * debugging purposes.
544 * @param $socketResource A valid socket resource
545 * @param $recipientData An array with two elements: 0=IP number, 1=port number
547 * @throws SocketConnectionException The connection attempts fails with a time-out
549 protected function socketErrorNoRouteToHostHandler ($socketResource, array $recipientData) {
550 // Get socket error code for verification
551 $socketError = socket_last_error($socketResource);
554 $errorMessage = socket_strerror($socketError);
556 // Shutdown this socket
557 $this->shutdownSocket($socketResource);
560 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
564 * Handles socket error 'operation already in progress' which happens in
565 * method connectToPeerByRecipientData() on timed out connection
568 * @param $socketResource A valid socket resource
569 * @param $recipientData An array with two elements: 0=IP number, 1=port number
571 * @throws SocketConnectionException The connection attempts fails with a time-out
573 protected function socketErrorOperationAlreadyProgressHandler ($socketResource, array $recipientData) {
574 // Get socket error code for verification
575 $socketError = socket_last_error($socketResource);
578 $errorMessage = socket_strerror($socketError);
580 // Half-shutdown this socket (see there for difference to shutdownSocket())
581 $this->halfShutdownSocket($socketResource);
584 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
588 * Handles socket "error" 'operation now in progress' which can be safely
589 * passed on with non-blocking connections.
591 * @param $socketResource A valid socket resource
592 * @param $recipientData An array with two elements: 0=IP number, 1=port number
595 protected function socketErrorOperationInProgressHandler ($socketResource, array $recipientData) {
596 self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Operation is now in progress, this is usual for non-blocking connections and is no bug.');