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() {
309 // Get the state factory and create the initial state.
310 PeerStateFactory::createPeerStateInstanceByName('init', $this);
314 * "Getter" for raw data from a package array. A fragmenter is used which
315 * will returns us only so many raw data which fits into the back buffer.
316 * The rest is being held in a back-buffer and waits there for the next
317 * cycle and while be then sent.
319 * This method does 2 simple steps:
320 * 1) Request a chunk from set fragmenter instance
321 * 2) Finally return the chunk (array) to the caller
323 * @param $packageData Raw package data array
324 * @return $chunkData Raw data chunk
326 private function getRawDataFromPackageArray (array $packageData) {
328 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: currentFinalHash=' . $this->currentFinalHash);
330 // Make sure the final hash is set
331 assert((is_string($this->currentFinalHash)) && (!empty($this->currentFinalHash)));
333 // Get the next raw data chunk from the fragmenter
334 $rawDataChunk = $this->getFragmenterInstance()->getNextRawDataChunk($this->currentFinalHash);
337 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: rawDataChunk=' . print_r($rawDataChunk, TRUE));
339 // Get chunk hashes and chunk data
340 $chunkHashes = array_keys($rawDataChunk);
341 $chunkData = array_values($rawDataChunk);
343 // Is the required data there?
344 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: chunkHashes[]=' . count($chunkHashes) . ',chunkData[]=' . count($chunkData));
345 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('chunkData='.print_r($chunkData, TRUE));
346 if ((isset($chunkHashes[0])) && (isset($chunkData[0]))) {
347 // Remember this chunk as queued
348 $this->queuedChunks[$chunkHashes[0]] = $chunkData[0];
350 // Return the raw data
351 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Returning ' . strlen($chunkData[0]) . ' bytes from ' . __METHOD__ . ' ...');
352 return $chunkData[0];
354 // Return zero string
355 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Returning zero bytes from ' . __METHOD__ . '!');
361 * "Accept" a visitor by simply calling it back
363 * @param $visitorInstance A Visitor instance
366 protected final function accept (Visitor $visitorInstance) {
367 // Just call the visitor
368 $visitorInstance->visitConnectionHelper($this);
372 * Sends raw package data to the recipient
374 * @param $packageData Raw package data
376 * @throws InvalidSocketException If we got a problem with this socket
378 public function sendRawPackageData (array $packageData) {
379 // The helper's state must be 'connected'
380 $this->getStateInstance()->validatePeerStateConnected();
382 // Implode the package data array and fragement the resulting string, returns the final hash
383 $finalHash = $this->getFragmenterInstance()->fragmentPackageArray($packageData, $this);
385 // Is the final hash set?
386 if ($finalHash !== TRUE) {
388 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Setting finalHash=' . $finalHash . ',currentFinalHash[' . gettype($this->currentFinalHash) . ']=' . $this->currentFinalHash);
391 $this->currentFinalHash = $finalHash;
394 // Reset serial number
395 $this->getFragmenterInstance()->resetSerialNumber($this->currentFinalHash);
401 // Fill sending buffer with data
402 while (strlen($dataStream) > 0) {
404 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: packageData=' . print_r($packageData, TRUE));
406 // Convert the package data array to a raw data stream
407 $dataStream = $this->getRawDataFromPackageArray($packageData);
408 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Adding ' . strlen($dataStream) . ' bytes to the sending buffer ...');
409 $rawData .= $dataStream;
412 // Nothing to sent is bad news, so assert on it
413 assert(strlen($rawData) > 0);
415 // Calculate buffer size
416 $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
418 // Encode the raw data with our output-stream
419 $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
422 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: socketResource[]=' . gettype($this->getSocketResource()) . PHP_EOL);
425 $encodedDataArray = array(
426 NetworkPackage::RAW_FINAL_HASH_INDEX => $this->currentFinalHash,
427 NetworkPackage::RAW_ENCODED_DATA_INDEX => $encodedData,
428 NetworkPackage::RAW_SENT_BYTES_INDEX => 0,
429 NetworkPackage::RAW_SOCKET_INDEX => $this->getSocketResource(),
430 NetworkPackage::RAW_BUFFER_SIZE_INDEX => $bufferSize,
431 NetworkPackage::RAW_DIFF_INDEX => 0
434 // Calculate difference
435 $diff = $encodedDataArray[NetworkPackage::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[NetworkPackage::RAW_ENCODED_DATA_INDEX]);
437 // Push raw data to the package's outgoing stack
438 $this->getPackageInstance()->getStackInstance()->pushNamed(NetworkPackage::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
442 * Marks this connection as shutted down
446 protected final function markConnectionShuttedDown () {
447 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $this->__toString() . ' has been marked as shutted down');
448 $this->shuttedDown = TRUE;
450 // And remove the (now invalid) socket
451 $this->setSocketResource(FALSE);
455 * Getter for shuttedDown
457 * @return $shuttedDown Whether this connection is shutted down
459 public final function isShuttedDown () {
460 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
461 return $this->shuttedDown;
464 // ************************************************************************
465 // Socket error handler call-back methods
466 // ************************************************************************
469 * Handles socket error 'connection timed out', but does not clear it for
470 * later debugging purposes.
472 * @param $socketResource A valid socket resource
473 * @param $recipientData An array with two elements: 0=IP number, 1=port number
475 * @throws SocketConnectionException The connection attempts fails with a time-out
477 protected function socketErrorConnectionTimedOutHandler ($socketResource, array $recipientData) {
478 // Get socket error code for verification
479 $socketError = socket_last_error($socketResource);
482 $errorMessage = socket_strerror($socketError);
484 // Shutdown this socket
485 $this->shutdownSocket($socketResource);
488 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
492 * Handles socket error 'resource temporary unavailable', but does not
493 * clear it for later debugging purposes.
495 * @param $socketResource A valid socket resource
496 * @param $recipientData An array with two elements: 0=IP number, 1=port number
498 * @throws SocketConnectionException The connection attempts fails with a time-out
500 protected function socketErrorResourceUnavailableHandler ($socketResource, array $recipientData) {
501 // Get socket error code for verification
502 $socketError = socket_last_error($socketResource);
505 $errorMessage = socket_strerror($socketError);
507 // Shutdown this socket
508 $this->shutdownSocket($socketResource);
511 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
515 * Handles socket error 'connection refused', but does not clear it for
516 * later debugging purposes.
518 * @param $socketResource A valid socket resource
519 * @param $recipientData An array with two elements: 0=IP number, 1=port number
521 * @throws SocketConnectionException The connection attempts fails with a time-out
523 protected function socketErrorConnectionRefusedHandler ($socketResource, array $recipientData) {
524 // Get socket error code for verification
525 $socketError = socket_last_error($socketResource);
528 $errorMessage = socket_strerror($socketError);
530 // Shutdown this socket
531 $this->shutdownSocket($socketResource);
534 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
538 * Handles socket error 'no route to host', but does not clear it for later
539 * debugging purposes.
541 * @param $socketResource A valid socket resource
542 * @param $recipientData An array with two elements: 0=IP number, 1=port number
544 * @throws SocketConnectionException The connection attempts fails with a time-out
546 protected function socketErrorNoRouteToHostHandler ($socketResource, array $recipientData) {
547 // Get socket error code for verification
548 $socketError = socket_last_error($socketResource);
551 $errorMessage = socket_strerror($socketError);
553 // Shutdown this socket
554 $this->shutdownSocket($socketResource);
557 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
561 * Handles socket error 'operation already in progress' which happens in
562 * method connectToPeerByRecipientData() on timed out connection
565 * @param $socketResource A valid socket resource
566 * @param $recipientData An array with two elements: 0=IP number, 1=port number
568 * @throws SocketConnectionException The connection attempts fails with a time-out
570 protected function socketErrorOperationAlreadyProgressHandler ($socketResource, array $recipientData) {
571 // Get socket error code for verification
572 $socketError = socket_last_error($socketResource);
575 $errorMessage = socket_strerror($socketError);
577 // Half-shutdown this socket (see there for difference to shutdownSocket())
578 $this->halfShutdownSocket($socketResource);
581 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
585 * Handles socket error 'connection reset by peer', but does not clear it for
586 * later debugging purposes.
588 * @param $socketResource A valid socket resource
589 * @param $recipientData An array with two elements: 0=IP number, 1=port number
591 * @throws SocketConnectionException The connection attempts fails with a time-out
593 protected function socketErrorConnectionResetByPeerHandler ($socketResource, array $recipientData) {
594 // Get socket error code for verification
595 $socketError = socket_last_error($socketResource);
598 $errorMessage = socket_strerror($socketError);
600 // Shutdown this socket
601 $this->shutdownSocket($socketResource);
604 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
608 * Handles socket "error" 'operation now in progress' which can be safely
609 * passed on with non-blocking connections.
611 * @param $socketResource A valid socket resource
612 * @param $recipientData An array with two elements: 0=IP number, 1=port number
615 protected function socketErrorOperationInProgressHandler ($socketResource, array $recipientData) {
616 self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Operation is now in progress, this is usual for non-blocking connections and is no bug.');