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);
95 // Get the fragmenter instance
96 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
99 $this->setFragmenterInstance($fragmenterInstance);
103 * Getter for real class name, overwrites generic method and is final
105 * @return $class Name of this class
107 public final function __toString () {
108 // Class name representation
109 $class = self::getConnectionClassName($this->getAddress(), $this->getPort(), parent::__toString());
116 * Getter for port number to satify ProtocolHandler
118 * @return $port The port number
120 public final function getPort () {
125 * Setter for port number to satify ProtocolHandler
127 * @param $port The port number
130 protected final function setPort ($port) {
135 * Getter for protocol
137 * @return $protocol Used protocol
139 public final function getProtocol () {
140 return $this->protocol;
144 * Setter for protocol
146 * @param $protocol Used protocol
149 protected final function setProtocol ($protocol) {
150 $this->protocol = $protocol;
154 * Getter for IP address
156 * @return $address The IP address
158 public final function getAddress () {
159 return $this->address;
163 * Setter for IP address
165 * @param $address The IP address
168 protected final function setAddress ($address) {
169 $this->address = $address;
173 * Initializes the current connection
176 * @throws SocketOptionException If setting any socket option fails
178 protected function initConnection () {
179 // Get socket resource
180 $socketResource = $this->getSocketResource();
182 // Set the option to reuse the port
183 if (!socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1)) {
184 // Handle this socket error with a faked recipientData array
185 $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
188 // @TODO Move this to the socket error handler
189 throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
193 * Set socket to non-blocking mode before trying to establish a link to
194 * it. This is now the default behaviour for all connection helpers who
195 * call initConnection(); .
197 if (!socket_set_nonblock($socketResource)) {
198 // Handle this socket error with a faked recipientData array
199 $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
202 throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
205 // Last step: mark connection as initialized
206 $this->isInitialized = true;
210 * Attempts to connect to a peer by given IP number and port from a valid
211 * recipientData array with currently configured timeout.
213 * @param $recipientData A valid recipient data array, 0=IP; 1=PORT
214 * @return $isConnected Whether the connection went fine
215 * @see Please see http://de.php.net/manual/en/function.socket-connect.php#84465 for original code
216 * @todo Rewrite the while() loop to a iterator to not let the software stay very long here
218 protected function connectToPeerByRecipientDataArray (array $recipientData) {
219 // Only call this if the connection is initialized by initConnection()
220 assert($this->isInitialized === true);
225 // "Cache" socket resource and timeout config
226 $socketResource = $this->getSocketResource();
227 $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
230 $this->debugOutput('CONNECTION-HELPER: Trying to connect to ' . $recipientData[0] . ':' . $recipientData[1] . ' with socketResource[' . gettype($socketResource) . ']=' . $socketResource . ' ...');
232 // Try to connect until it is connected
233 while ($isConnected = !@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
234 // Get last socket error
235 $socketError = socket_last_error($socketResource);
237 // Skip any errors which may happen on non-blocking connections
238 if (($socketError == SOCKET_EINPROGRESS) || ($socketError == SOCKET_EALREADY)) {
239 // Now, is that attempt within parameters?
240 if ((time() - $time) >= $timeout) {
241 // Didn't work within timeout
242 $isConnected = false;
246 // Sleep about one second
248 } elseif ($socketError != 0) {
249 // Stop on everything else pronto
250 $isConnected = false;
260 * Static "getter" for this connection class' name
262 * @param $address IP address
263 * @param $port Port number
264 * @param $className Original class name
265 * @return $class Expanded class name
267 public static function getConnectionClassName ($address, $port, $className) {
269 $class = $address . ':' . $port . ':' . $className;
276 * Initializes the peer's state which sets it to 'init'
280 private function initState() {
282 * Get the state factory and create the initial state, we don't need
283 * the state instance here
285 PeerStateFactory::createPeerStateInstanceByName('init', $this);
289 * "Getter" for raw data from a package array. A fragmenter is used which
290 * will returns us only so many raw data which fits into the back buffer.
291 * The rest is being held in a back-buffer and waits there for the next
292 * cycle and while be then sent.
294 * This method does 4 simple steps:
295 * 1) Aquire fragmenter object instance from the factory
296 * 2) Handle over the package data array to the fragmenter
298 * 4) Finally return the chunk (array) to the caller
300 * @param $packageData Raw package data array
301 * @return $chunkData Raw data chunk
303 private function getRawDataFromPackageArray (array $packageData) {
304 // Implode the package data array and fragement the resulting string, returns the final hash
305 $finalHash = $this->getFragmenterInstance()->fragmentPackageArray($packageData, $this);
306 if ($finalHash !== true) {
307 $this->currentFinalHash = $finalHash;
311 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: currentFinalHash=' . $this->currentFinalHash);
313 // Get the next raw data chunk from the fragmenter
314 $rawDataChunk = $this->getFragmenterInstance()->getNextRawDataChunk($this->currentFinalHash);
316 // Get chunk hashes and chunk data
317 $chunkHashes = array_keys($rawDataChunk);
318 $chunkData = array_values($rawDataChunk);
320 // Is the required data there?
321 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: chunkHashes[]=' . count($chunkHashes) . ',chunkData[]=' . count($chunkData));
322 //* NOISY-DEBUG: */ $this->debugOutput('chunkData='.print_r($chunkData,true));
323 if ((isset($chunkHashes[0])) && (isset($chunkData[0]))) {
324 // Remember this chunk as queued
325 $this->queuedChunks[$chunkHashes[0]] = $chunkData[0];
327 // Return the raw data
328 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Returning ' . strlen($chunkData[0]) . ' bytes from ' . __METHOD__ . ' ...');
329 return $chunkData[0];
331 // Return zero string
332 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Returning zero bytes from ' . __METHOD__ . '!');
338 * "Accept" a visitor by simply calling it back
340 * @param $visitorInstance A Visitor instance
343 protected final function accept (Visitor $visitorInstance) {
344 // Just call the visitor
345 $visitorInstance->visitConnectionHelper($this);
349 * Sends raw package data to the recipient
351 * @param $packageData Raw package data
352 * @return $totalSentBytes Total sent bytes to the peer
353 * @throws InvalidSocketException If we got a problem with this socket
355 public function sendRawPackageData (array $packageData) {
356 // The helper's state must be 'connected'
357 $this->getStateInstance()->validatePeerStateConnected();
359 // Cache buffer length
360 $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
367 // Fill sending buffer with data
368 while (strlen($dataStream) > 0) {
369 // Convert the package data array to a raw data stream
370 $dataStream = $this->getRawDataFromPackageArray($packageData);
371 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Adding ' . strlen($dataStream) . ' bytes to the sending buffer ...');
372 $rawData .= $dataStream;
374 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: rawData[' . strlen($rawData) . ']=' . $rawData);
376 // Nothing to sent is bad news, so assert on it
377 assert(strlen($rawData) > 0);
379 // Encode the raw data with our output-stream
380 $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
382 // Calculate difference
383 $this->diff = $bufferSize - strlen($encodedData);
385 // Get socket resource
386 $socketResource = $this->getSocketResource();
392 while ($sentBytes !== false) {
394 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sending out ' . strlen($encodedData) . ' bytes,bufferSize=' . $bufferSize . ',diff=' . $this->diff);
395 if ($this->diff >= 0) {
396 // Send all out (encodedData is smaller than or equal buffer size)
397 $sentBytes = @socket_write($socketResource, $encodedData, ($bufferSize - $this->diff));
399 // Send buffer size out
400 $sentBytes = @socket_write($socketResource, $encodedData, $bufferSize);
403 // If there was an error, we don't continue here
404 if ($sentBytes === false) {
405 // Handle the error with a faked recipientData array
406 $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
409 throw new InvalidSocketException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
410 } elseif (($sentBytes == 0) && (strlen($encodedData) > 0)) {
411 // Nothing sent means we are done
412 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (LINE=' . __LINE__ . ')');
416 // The difference between sent bytes and length of raw data should not go below zero
417 assert((strlen($encodedData) - $sentBytes) >= 0);
419 // Add total sent bytes
420 $totalSentBytes += $sentBytes;
422 // Cut out the last unsent bytes
423 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sent out ' . $sentBytes . ' of ' . strlen($encodedData) . ' bytes ...');
424 $encodedData = substr($encodedData, $sentBytes);
426 // Calculate difference again
427 $this->diff = $bufferSize - strlen($encodedData);
430 if (strlen($encodedData) <= 0) {
431 // Abort here, all sent!
432 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (LINE=' . __LINE__ . ')');
438 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: totalSentBytes=' . $totalSentBytes . ',diff=' . $this->diff);
439 return $totalSentBytes;
443 * Marks this connection as shutted down
447 protected final function markConnectionShuttedDown () {
448 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ' has been marked as shutted down');
449 $this->shuttedDown = true;
451 // And remove the (now invalid) socket
452 $this->setSocketResource(false);
456 * Getter for shuttedDown
458 * @return $shuttedDown Whether this connection is shutted down
460 public final function isShuttedDown () {
461 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
462 return $this->shuttedDown;
465 // ************************************************************************
466 // Socket error handler call-back methods
467 // ************************************************************************
470 * Handles socket error 'connection timed out', but does not clear it for
471 * later debugging purposes.
473 * @param $socketResource A valid socket resource
475 * @throws SocketConnectionException The connection attempts fails with a time-out
477 protected function socketErrorConnectionTimedOutHandler ($socketResource) {
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
497 * @throws SocketConnectionException The connection attempts fails with a time-out
499 protected function socketErrorResourceUnavailableHandler ($socketResource) {
500 // Get socket error code for verification
501 $socketError = socket_last_error($socketResource);
504 $errorMessage = socket_strerror($socketError);
506 // Shutdown this socket
507 $this->shutdownSocket($socketResource);
510 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
514 * Handles socket error 'connection refused', but does not clear it for
515 * later debugging purposes.
517 * @param $socketResource A valid socket resource
519 * @throws SocketConnectionException The connection attempts fails with a time-out
521 protected function socketErrorConnectionRefusedHandler ($socketResource) {
522 // Get socket error code for verification
523 $socketError = socket_last_error($socketResource);
526 $errorMessage = socket_strerror($socketError);
528 // Shutdown this socket
529 $this->shutdownSocket($socketResource);
532 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
536 * Handles socket error 'no route to host', but does not clear it for later
537 * debugging purposes.
539 * @param $socketResource A valid socket resource
541 * @throws SocketConnectionException The connection attempts fails with a time-out
543 protected function socketErrorNoRouteToHostHandler ($socketResource) {
544 // Get socket error code for verification
545 $socketError = socket_last_error($socketResource);
548 $errorMessage = socket_strerror($socketError);
550 // Shutdown this socket
551 $this->shutdownSocket($socketResource);
554 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
558 * Handles socket error 'operation already in progress' which happens in
559 * method connectToPeerByRecipientDataArray() on timed out connection
562 * @param $socketResource A valid socket resource
564 * @throws SocketConnectionException The connection attempts fails with a time-out
566 protected function socketErrorOperationAlreadyProgressHandler ($socketResource) {
567 // Get socket error code for verification
568 $socketError = socket_last_error($socketResource);
571 $errorMessage = socket_strerror($socketError);
573 // Half-shutdown this socket (see there for difference to shutdownSocket())
574 $this->halfShutdownSocket($socketResource);
577 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
581 * Handles socket "error" 'operation now in progress' which can be safely
582 * passed on with non-blocking connections.
584 * @param $socketResource A valid socket resource
587 protected function socketErrorOperationInProgressHandler ($socketResource) {
588 $this->debugOutput('CONNECTION: Operation is now in progress, this is usual for non-blocking connections and is no bug.');