]> git.mxchange.org Git - hub.git/blob - application/hub/main/helper/connection/class_BaseConnectionHelper.php
Refactured sending encoded (raw) data to sockets to a stacker-based approach.
[hub.git] / application / hub / main / helper / connection / class_BaseConnectionHelper.php
1 <?php
2 /**
3  * A general ConnectionHelper class
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class BaseConnectionHelper extends BaseHubSystemHelper implements Registerable, ProtocolHandler {
25         // Exception codes
26         const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x9100;
27
28         /**
29          * Connection type 'incoming'
30          */
31         const CONNECTION_TYPE_INCOMING = 'incoming';
32
33         /**
34          * Connection type 'outgoing'
35          */
36         const CONNECTION_TYPE_OUTGOING = 'outgoing';
37
38         /**
39          * Connection type 'server'
40          */
41         const CONNECTION_TYPE_SERVER   = 'server';
42
43         /**
44          * Protocol used
45          */
46         private $protocol = 'invalid';
47
48         /**
49          * Port number used
50          */
51         private $port = 0;
52
53         /**
54          * (IP) Adress used
55          */
56         private $address = 0;
57
58         /**
59          * Sent data in bytes
60          */
61         private $sentData = 0;
62
63         /**
64          * Whether this connection is initialized
65          */
66         private $isInitialized = FALSE;
67
68         /**
69          * Whether this connection is shutted down
70          */
71         private $shuttedDown = FALSE;
72
73         /**
74          * Currently queued chunks
75          */
76         private $queuedChunks = array();
77
78         /**
79          * Current final hash
80          */
81         private $currentFinalHash = '';
82
83         /**
84          * Protected constructor
85          *
86          * @param       $className      Name of the class
87          * @return      void
88          */
89         protected function __construct ($className) {
90                 // Call parent constructor
91                 parent::__construct($className);
92
93                 // Init state which sets the state to 'init'
94                 $this->initState();
95
96                 // Initialize output stream
97                 $streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_output_stream_class');
98
99                 // And add it to this connection helper
100                 $this->setOutputStreamInstance($streamInstance);
101
102                 // Get package instance from factory
103                 $packageInstance = NetworkPackageFactory::createNetworkPackageInstance();
104
105                 // ... and set it here
106                 $this->setPackageInstance($packageInstance);
107
108                 // Register this connection helper
109                 Registry::getRegistry()->addInstance('connection', $this);
110
111                 // Get the fragmenter instance
112                 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
113
114                 // Set it here
115                 $this->setFragmenterInstance($fragmenterInstance);
116         }
117
118         /**
119          * Getter for real class name, overwrites generic method and is final
120          *
121          * @return      $class  Name of this class
122          */
123         public final function __toString () {
124                 // Class name representation
125                 $class = self::getConnectionClassName($this->getAddress(), $this->getPort(), parent::__toString());
126
127                 // Return it
128                 return $class;
129         }
130
131         /**
132          * Getter for port number to satify ProtocolHandler
133          *
134          * @return      $port   The port number
135          */
136         public final function getPort () {
137                 return $this->port;
138         }
139
140         /**
141          * Setter for port number to satify ProtocolHandler
142          *
143          * @param       $port   The port number
144          * @return      void
145          */
146         protected final function setPort ($port) {
147                 $this->port = $port;
148         }
149
150         /**
151          * Getter for protocol
152          *
153          * @return      $protocol       Used protocol
154          */
155         public final function getProtocol () {
156                 return $this->protocol;
157         }
158
159         /**
160          * Setter for protocol
161          *
162          * @param       $protocol       Used protocol
163          * @return      void
164          */
165         protected final function setProtocol ($protocol) {
166                 $this->protocol = $protocol;
167         }
168
169         /**
170          * Getter for IP address
171          *
172          * @return      $address        The IP address
173          */
174         public final function getAddress () {
175                 return $this->address;
176         }
177
178         /**
179          * Setter for IP address
180          *
181          * @param       $address        The IP address
182          * @return      void
183          */
184         protected final function setAddress ($address) {
185                 $this->address = $address;
186         }
187
188         /**
189          * Initializes the current connection
190          *
191          * @return      void
192          * @throws      SocketOptionException   If setting any socket option fails
193          */
194         protected function initConnection () {
195                 // Get socket resource
196                 $socketResource = $this->getSocketResource();
197
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'));
202
203                         // And throw again
204                         // @TODO Move this to the socket error handler
205                         throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
206                 } // END - if
207
208                 /*
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(); .
212                  */
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'));
216
217                         // And throw again
218                         throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
219                 } // END - if
220
221                 // Last step: mark connection as initialized
222                 $this->isInitialized = TRUE;
223         }
224
225         /**
226          * Attempts to connect to a peer by given IP number and port from a valid
227          * recipientData array with currently configured timeout.
228          *
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
233          */
234         protected function connectToPeerByRecipientData (array $recipientData) {
235                 // Only call this if the connection is initialized by initConnection()
236                 assert($this->isInitialized === TRUE);
237
238                 // Get current time
239                 $time = time();
240
241                 // "Cache" socket resource and timeout config
242                 $socketResource = $this->getSocketResource();
243                 $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
244
245                 // Debug output
246                 self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Trying to connect to ' . $recipientData[0] . ':' . $recipientData[1] . ' with socketResource[' . gettype($socketResource) . ']=' . $socketResource . ' ...');
247
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);
252
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;
259                                         break;
260                                 } // END - if
261
262                                 // Sleep about one second
263                                 $this->idle(1000);
264                         } elseif ($socketError != 0) {
265                                 // Stop on everything else pronto
266                                 $isConnected = FALSE;
267                                 break;
268                         }
269                 } // END - while
270
271                 // Is the peer connected?
272                 if ($isConnected === TRUE) {
273                         // Connection is fully established here, so change the state.
274                         PeerStateFactory::createPeerStateInstanceByName('connected', $this);
275                 } else {
276                         /*
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).
279                          */
280                         PeerStateFactory::createPeerStateInstanceByName('problem', $this);
281                 }
282
283                 // Return status
284                 return $isConnected;
285         }
286
287         /**
288          * Static "getter" for this connection class' name
289          *
290          * @param       $address        IP address
291          * @param       $port           Port number
292          * @param       $className      Original class name
293          * @return      $class          Expanded class name
294          */
295         public static function getConnectionClassName ($address, $port, $className) {
296                 // Construct it
297                 $class = $address . ':' . $port . ':' . $className;
298
299                 // ... and return it
300                 return $class;
301         }
302
303         /**
304          * Initializes the peer's state which sets it to 'init'
305          *
306          * @return      void
307          */
308         private function initState() {
309                 /*
310                  * Get the state factory and create the initial state, we don't need
311                  * the state instance here
312                  */
313                 PeerStateFactory::createPeerStateInstanceByName('init', $this);
314         }
315
316         /**
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.
321          *
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
325          *
326          * @param       $packageData    Raw package data array
327          * @return      $chunkData              Raw data chunk
328          */
329         private function getRawDataFromPackageArray (array $packageData) {
330                 // Debug message
331                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: currentFinalHash=' . $this->currentFinalHash);
332
333                 // Make sure the final hash is set
334                 assert((is_string($this->currentFinalHash)) && (!empty($this->currentFinalHash)));
335
336                 // Get the next raw data chunk from the fragmenter
337                 $rawDataChunk = $this->getFragmenterInstance()->getNextRawDataChunk($this->currentFinalHash);
338
339                 // Debug message
340                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: rawDataChunk=' . print_r($rawDataChunk, TRUE));
341
342                 // Get chunk hashes and chunk data
343                 $chunkHashes = array_keys($rawDataChunk);
344                 $chunkData   = array_values($rawDataChunk);
345
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];
352
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];
356                 } else {
357                         // Return zero string
358                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Returning zero bytes from ' . __METHOD__ . '!');
359                         return '';
360                 }
361         }
362
363         /**
364          * "Accept" a visitor by simply calling it back
365          *
366          * @param       $visitorInstance        A Visitor instance
367          * @return      void
368          */
369         protected final function accept (Visitor $visitorInstance) {
370                 // Just call the visitor
371                 $visitorInstance->visitConnectionHelper($this);
372         }
373
374         /**
375          * Sends raw package data to the recipient
376          *
377          * @param       $packageData            Raw package data
378          * @return      void
379          * @throws      InvalidSocketException  If we got a problem with this socket
380          */
381         public function sendRawPackageData (array $packageData) {
382                 // The helper's state must be 'connected'
383                 $this->getStateInstance()->validatePeerStateConnected();
384
385                 // Implode the package data array and fragement the resulting string, returns the final hash
386                 $finalHash = $this->getFragmenterInstance()->fragmentPackageArray($packageData, $this);
387
388                 // Is the final hash set?
389                 if ($finalHash !== TRUE) {
390                         // Debug message
391                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Setting finalHash=' . $finalHash . ',currentFinalHash[' . gettype($this->currentFinalHash) . ']=' . $this->currentFinalHash);
392
393                         // Set final hash
394                         $this->currentFinalHash = $finalHash;
395                 } // END - if
396
397                 // Reset serial number
398                 $this->getFragmenterInstance()->resetSerialNumber($this->currentFinalHash);
399
400                 // Init variables
401                 $rawData        = '';
402                 $dataStream     = ' ';
403
404                 // Fill sending buffer with data
405                 while (strlen($dataStream) > 0) {
406                         // Debug message
407                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: packageData=' . print_r($packageData, TRUE));
408
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;
413                 } // END - while
414
415                 // Nothing to sent is bad news, so assert on it
416                 assert(strlen($rawData) > 0);
417
418                 // Calculate buffer size
419                 $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
420
421                 // Encode the raw data with our output-stream
422                 $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
423
424                 // Debug message
425                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: socketResource[]=' . gettype($this->getSocketResource()) . PHP_EOL);
426
427                 // Init array
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
435                 );
436
437                 // Calculate difference
438                 $diff = $encodedDataArray[NetworkPackage::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[NetworkPackage::RAW_ENCODED_DATA_INDEX]);
439
440                 // Push raw data to the package's outgoing stack
441                 $this->getPackageInstance()->getStackerInstance()->pushNamed(NetworkPackage::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
442         }
443
444         /**
445          * Marks this connection as shutted down
446          *
447          * @return      void
448          */
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;
452
453                 // And remove the (now invalid) socket
454                 $this->setSocketResource(FALSE);
455         }
456
457         /**
458          * Getter for shuttedDown
459          *
460          * @return      $shuttedDown    Whether this connection is shutted down
461          */
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;
465         }
466
467         // ************************************************************************
468         //                 Socket error handler call-back methods
469         // ************************************************************************
470
471         /**
472          * Handles socket error 'connection timed out', but does not clear it for
473          * later debugging purposes.
474          *
475          * @param       $socketResource         A valid socket resource
476          * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
477          * @return      void
478          * @throws      SocketConnectionException       The connection attempts fails with a time-out
479          */
480         protected function socketErrorConnectionTimedOutHandler ($socketResource, array $recipientData) {
481                 // Get socket error code for verification
482                 $socketError = socket_last_error($socketResource);
483
484                 // Get error message
485                 $errorMessage = socket_strerror($socketError);
486
487                 // Shutdown this socket
488                 $this->shutdownSocket($socketResource);
489
490                 // Throw it again
491                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
492         }
493
494         /**
495          * Handles socket error 'resource temporary unavailable', but does not
496          * clear it for later debugging purposes.
497          *
498          * @param       $socketResource         A valid socket resource
499          * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
500          * @return      void
501          * @throws      SocketConnectionException       The connection attempts fails with a time-out
502          */
503         protected function socketErrorResourceUnavailableHandler ($socketResource, array $recipientData) {
504                 // Get socket error code for verification
505                 $socketError = socket_last_error($socketResource);
506
507                 // Get error message
508                 $errorMessage = socket_strerror($socketError);
509
510                 // Shutdown this socket
511                 $this->shutdownSocket($socketResource);
512
513                 // Throw it again
514                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
515         }
516
517         /**
518          * Handles socket error 'connection refused', but does not clear it for
519          * later debugging purposes.
520          *
521          * @param       $socketResource         A valid socket resource
522          * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
523          * @return      void
524          * @throws      SocketConnectionException       The connection attempts fails with a time-out
525          */
526         protected function socketErrorConnectionRefusedHandler ($socketResource, array $recipientData) {
527                 // Get socket error code for verification
528                 $socketError = socket_last_error($socketResource);
529
530                 // Get error message
531                 $errorMessage = socket_strerror($socketError);
532
533                 // Shutdown this socket
534                 $this->shutdownSocket($socketResource);
535
536                 // Throw it again
537                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
538         }
539
540         /**
541          * Handles socket error 'no route to host', but does not clear it for later
542          * debugging purposes.
543          *
544          * @param       $socketResource         A valid socket resource
545          * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
546          * @return      void
547          * @throws      SocketConnectionException       The connection attempts fails with a time-out
548          */
549         protected function socketErrorNoRouteToHostHandler ($socketResource, array $recipientData) {
550                 // Get socket error code for verification
551                 $socketError = socket_last_error($socketResource);
552
553                 // Get error message
554                 $errorMessage = socket_strerror($socketError);
555
556                 // Shutdown this socket
557                 $this->shutdownSocket($socketResource);
558
559                 // Throw it again
560                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
561         }
562
563         /**
564          * Handles socket error 'operation already in progress' which happens in
565          * method connectToPeerByRecipientData() on timed out connection
566          * attempts.
567          *
568          * @param       $socketResource         A valid socket resource
569          * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
570          * @return      void
571          * @throws      SocketConnectionException       The connection attempts fails with a time-out
572          */
573         protected function socketErrorOperationAlreadyProgressHandler ($socketResource, array $recipientData) {
574                 // Get socket error code for verification
575                 $socketError = socket_last_error($socketResource);
576
577                 // Get error message
578                 $errorMessage = socket_strerror($socketError);
579
580                 // Half-shutdown this socket (see there for difference to shutdownSocket())
581                 $this->halfShutdownSocket($socketResource);
582
583                 // Throw it again
584                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
585         }
586
587         /**
588          * Handles socket "error" 'operation now in progress' which can be safely
589          * passed on with non-blocking connections.
590          *
591          * @param       $socketResource         A valid socket resource
592          * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
593          * @return      void
594          */
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.');
597         }
598 }
599
600 // [EOF]
601 ?>