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 * Wether 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 Wether 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');
223 // Try to connect until it is connected
224 while ($isConnected = !@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
225 // Get last socket error
226 $socketError = socket_last_error($socketResource);
228 // Skip any errors which may happen on non-blocking connections
229 if (($socketError == SOCKET_EINPROGRESS) || ($socketError == SOCKET_EALREADY)) {
230 // Now, is that attempt within parameters?
231 if ((time() - $time) >= $timeout) {
232 // Didn't work within timeout
233 $isConnected = false;
237 // Sleep about one second
239 } elseif ($socketError != 0) {
240 // Stop on everything else pronto
241 $isConnected = false;
251 * Static "getter" for this connection class' name
253 * @param $address IP address
254 * @param $port Port number
255 * @param $className Original class name
256 * @return $class Expanded class name
258 public static function getConnectionClassName ($address, $port, $className) {
260 $class = $address . ':' . $port . ':' . $className;
267 * Initializes the peer's state which sets it to 'init'
271 private function initState() {
273 * Get the state factory and create the initial state, we don't need
274 * the state instance here
276 PeerStateFactory::createPeerStateInstanceByName('init', $this);
280 * "Getter" for raw data from a package array. A fragmenter is used which
281 * will returns us only so many raw data which fits into the back buffer.
282 * The rest is being held in a back-buffer and waits there for the next
283 * cycle and while be then sent.
285 * This method does 4 simple steps:
286 * 1) Aquire fragmenter object instance from the factory
287 * 2) Handle over the package data array to the fragmenter
289 * 4) Finally return the chunk (array) to the caller
291 * @param $packageData Raw package data array
292 * @return $chunkData Raw data chunk
294 private function getRawDataFromPackageArray (array $packageData) {
295 // Get the fragmenter instance
296 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
298 // Implode the package data array and fragement the resulting string, returns the final hash
299 $finalHash = $fragmenterInstance->fragmentPackageArray($packageData, $this);
300 if ($finalHash !== true) {
301 $this->currentFinalHash = $finalHash;
305 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: currentFinalHash=' . $this->currentFinalHash);
307 // Get the next raw data chunk from the fragmenter
308 $rawDataChunk = $fragmenterInstance->getNextRawDataChunk($this->currentFinalHash);
310 // Get chunk hashes and chunk data
311 $chunkHashes = array_keys($rawDataChunk);
312 $chunkData = array_values($rawDataChunk);
314 // Is the required data there?
315 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: chunkHashes[]=' . count($chunkHashes) . ',chunkData[]=' . count($chunkData));
316 if ((isset($chunkHashes[0])) && (isset($chunkData[0]))) {
317 // Remember this chunk as queued
318 $this->queuedChunks[$chunkHashes[0]] = $chunkData[0];
320 // Return the raw data
321 return $chunkData[0];
323 // Return zero string
329 * "Accept" a visitor by simply calling it back
331 * @param $visitorInstance A Visitor instance
334 protected final function accept (Visitor $visitorInstance) {
335 // Just call the visitor
336 $visitorInstance->visitConnectionHelper($this);
340 * Sends raw package data to the recipient
342 * @param $packageData Raw package data
343 * @return $totalSentBytes Total sent bytes to the peer
344 * @throws InvalidSocketException If we got a problem with this socket
346 public function sendRawPackageData (array $packageData) {
347 // The helper's state must be 'connected'
348 $this->getStateInstance()->validatePeerStateConnected();
350 // Cache buffer length
351 $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
358 // Fill sending buffer with data
359 while ((strlen($rawData) < $bufferSize) && (strlen($dataStream) > 0)) {
360 // Convert the package data array to a raw data stream
361 $dataStream = $this->getRawDataFromPackageArray($packageData);
362 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Adding ' . strlen($dataStream) . ' bytes to the sending buffer ...');
363 $rawData .= $dataStream;
366 // Nothing to sent is bad news, so assert on it
367 assert(strlen($rawData) > 0);
369 // Encode the raw data with our output-stream
370 $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
372 // Calculate difference
373 $this->diff = $bufferSize - strlen($encodedData);
375 // Get socket resource
376 $socketResource = $this->getSocketResource();
382 while ($sentBytes !== false) {
384 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sending out ' . strlen($encodedData) . ' bytes,bufferSize=' . $bufferSize . ',diff=' . $this->diff);
385 $sentBytes = @socket_write($socketResource, $encodedData, ($bufferSize - $this->diff));
387 // If there was an error, we don't continue here
388 if ($sentBytes === false) {
389 // Handle the error with a faked recipientData array
390 $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
393 throw new InvalidSocketException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
394 } elseif (($sentBytes == 0) && (strlen($encodedData) > 0)) {
395 // Nothing sent means we are done
396 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
400 // The difference between sent bytes and length of raw data should not go below zero
401 assert((strlen($encodedData) - $sentBytes) >= 0);
403 // Add total sent bytes
404 $totalSentBytes += $sentBytes;
406 // Cut out the last unsent bytes
407 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sent out ' . $sentBytes . ' of ' . strlen($encodedData) . ' bytes ...');
408 $encodedData = substr($encodedData, $sentBytes);
410 // Calculate difference again
411 $this->diff = $bufferSize - strlen($encodedData);
414 if (strlen($encodedData) <= 0) {
415 // Abort here, all sent!
416 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
422 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: totalSentBytes=' . $totalSentBytes);
423 return $totalSentBytes;
427 * Marks this connection as shutted down
431 protected final function markConnectionShuttedDown () {
432 /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ' has been marked as shutted down');
433 $this->shuttedDown = true;
435 // And remove the (now invalid) socket
436 $this->setSocketResource(false);
440 * Getter for shuttedDown
442 * @return $shuttedDown Wether this connection is shutted down
444 public final function isShuttedDown () {
445 /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
446 return $this->shuttedDown;
449 // ************************************************************************
450 // Socket error handler call-back methods
451 // ************************************************************************
454 * Handles socket error 'connection timed out', but does not clear it for
455 * later debugging purposes.
457 * @param $socketResource A valid socket resource
459 * @throws SocketConnectionException The connection attempts fails with a time-out
461 protected function socketErrorConnectionTimedOutHandler ($socketResource) {
462 // Get socket error code for verification
463 $socketError = socket_last_error($socketResource);
466 $errorMessage = socket_strerror($socketError);
468 // Shutdown this socket
469 $this->shutdownSocket($socketResource);
472 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
476 * Handles socket error 'resource temporary unavailable', but does not
477 * clear it for later debugging purposes.
479 * @param $socketResource A valid socket resource
481 * @throws SocketConnectionException The connection attempts fails with a time-out
483 protected function socketErrorResourceUnavailableHandler ($socketResource) {
484 // Get socket error code for verification
485 $socketError = socket_last_error($socketResource);
488 $errorMessage = socket_strerror($socketError);
490 // Shutdown this socket
491 $this->shutdownSocket($socketResource);
494 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
498 * Handles socket error 'connection refused', but does not clear it for
499 * later debugging purposes.
501 * @param $socketResource A valid socket resource
503 * @throws SocketConnectionException The connection attempts fails with a time-out
505 protected function socketErrorConnectionRefusedHandler ($socketResource) {
506 // Get socket error code for verification
507 $socketError = socket_last_error($socketResource);
510 $errorMessage = socket_strerror($socketError);
512 // Shutdown this socket
513 $this->shutdownSocket($socketResource);
516 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
520 * Handles socket error 'no route to host', but does not clear it for later
521 * debugging purposes.
523 * @param $socketResource A valid socket resource
525 * @throws SocketConnectionException The connection attempts fails with a time-out
527 protected function socketErrorNoRouteToHostHandler ($socketResource) {
528 // Get socket error code for verification
529 $socketError = socket_last_error($socketResource);
532 $errorMessage = socket_strerror($socketError);
534 // Shutdown this socket
535 $this->shutdownSocket($socketResource);
538 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
542 * Handles socket error 'operation already in progress' which happens in
543 * method connectToPeerByRecipientDataArray() on timed out connection
546 * @param $socketResource A valid socket resource
548 * @throws SocketConnectionException The connection attempts fails with a time-out
550 protected function socketErrorOperationAlreadyProgressHandler ($socketResource) {
551 // Get socket error code for verification
552 $socketError = socket_last_error($socketResource);
555 $errorMessage = socket_strerror($socketError);
557 // Half-shutdown this socket (see there for difference to shutdownSocket())
558 $this->halfShutdownSocket($socketResource);
561 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
565 * Handles socket "error" 'operation now in progress' which can be safely
566 * passed on with non-blocking connections.
568 * @param $socketResource A valid socket resource
571 protected function socketErrorOperationInProgressHandler ($socketResource) {
572 $this->debugOutput('CONNECTION: Operation is now in progress, this is usual for non-blocking connections and is no bug.');