]> git.mxchange.org Git - hub.git/blob - application/hub/main/helper/connection/class_BaseConnectionHelper.php
27ced2e4224bea69087ff3a90d53af7b89159c1f
[hub.git] / application / hub / main / helper / connection / class_BaseConnectionHelper.php
1 <?php
2 /**
3  * A general ConnectionHelper class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
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
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 BaseHubHelper implements Registerable, ProtocolHandler {
25         // Exception codes
26         const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
27
28         /**
29          * Protocol used
30          */
31         private $protocol = 'invalid';
32
33         /**
34          * Port number used
35          */
36         private $port = 0;
37
38         /**
39          * (IP) Adress used
40          */
41         private $address = 0;
42
43         /**
44          * Sent data in bytes
45          */
46         private $sentData = 0;
47
48         /**
49          * Difference
50          */
51         private $diff = 0;
52
53         /**
54          * Whether this connection is initialized
55          */
56         private $isInitialized = false;
57
58         /**
59          * Wether this connection is shutted down
60          */
61         private $shuttedDown = false;
62
63         /**
64          * Currently queued chunks
65          */
66         private $queuedChunks = array();
67
68         /**
69          * Current final hash
70          */
71         private $currentFinalHash = '';
72
73         /**
74          * Protected constructor
75          *
76          * @param       $className      Name of the class
77          * @return      void
78          */
79         protected function __construct ($className) {
80                 // Call parent constructor
81                 parent::__construct($className);
82
83                 // Initialize output stream
84                 $streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_output_stream_class');
85
86                 // And add it to this connection helper
87                 $this->setOutputStreamInstance($streamInstance);
88
89                 // Init state which sets the state to 'init'
90                 $this->initState();
91
92                 // Register this connection helper
93                 Registry::getRegistry()->addInstance('connection', $this);
94         }
95
96         /**
97          * Getter for real class name, overwrites generic method and is final
98          *
99          * @return      $class  Name of this class
100          */
101         public final function __toString () {
102                 // Class name representation
103                 $class = self::getConnectionClassName($this->getAddress(), $this->getPort(), parent::__toString());
104
105                 // Return it
106                 return $class;
107         }
108
109         /**
110          * Getter for port number to satify ProtocolHandler
111          *
112          * @return      $port   The port number
113          */
114         public final function getPort () {
115                 return $this->port;
116         }
117
118         /**
119          * Setter for port number to satify ProtocolHandler
120          *
121          * @param       $port   The port number
122          * @return      void
123          */
124         protected final function setPort ($port) {
125                 $this->port = $port;
126         }
127
128         /**
129          * Getter for protocol
130          *
131          * @return      $protocol       Used protocol
132          */
133         public final function getProtocol () {
134                 return $this->protocol;
135         }
136
137         /**
138          * Setter for protocol
139          *
140          * @param       $protocol       Used protocol
141          * @return      void
142          */
143         protected final function setProtocol ($protocol) {
144                 $this->protocol = $protocol;
145         }
146
147         /**
148          * Getter for IP address
149          *
150          * @return      $address        The IP address
151          */
152         public final function getAddress () {
153                 return $this->address;
154         }
155
156         /**
157          * Setter for IP address
158          *
159          * @param       $address        The IP address
160          * @return      void
161          */
162         protected final function setAddress ($address) {
163                 $this->address = $address;
164         }
165
166         /**
167          * Initializes the current connection
168          *
169          * @return      void
170          * @throws      SocketOptionException   If setting any socket option fails
171          */
172         protected function initConnection () {
173                 // Get socket resource
174                 $socketResource = $this->getSocketResource();
175
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'));
180
181                         // And throw again
182                         // @TODO Move this to the socket error handler
183                         throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
184                 } // END - if
185
186                 /*
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(); .
190                  */
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'));
194
195                         // And throw again
196                         throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
197                 } // END - if
198
199                 // Last step: mark connection as initialized
200                 $this->isInitialized = true;
201         }
202
203         /**
204          * Attempts to connect to a peer by given IP number and port from a valid
205          * recipientData array with currently configured timeout.
206          *
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
211          */
212         protected function connectToPeerByRecipientDataArray (array $recipientData) {
213                 // Only call this if the connection is initialized by initConnection()
214                 assert($this->isInitialized === true);
215
216                 // Get current time
217                 $time = time();
218
219                 // "Cache" socket resource and timeout config
220                 $socketResource = $this->getSocketResource();
221                 $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
222
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);
227
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;
234                                         break;
235                                 } // END - if
236
237                                 // Sleep about one second
238                                 $this->idle(1000);
239                         } elseif ($socketError != 0) {
240                                 // Stop on everything else pronto
241                                 $isConnected = false;
242                                 break;
243                         }
244                 } // END - while
245
246                 // Return status
247                 return $isConnected;
248         }
249
250         /**
251          * Static "getter" for this connection class' name
252          *
253          * @param       $address        IP address
254          * @param       $port           Port number
255          * @param       $className      Original class name
256          * @return      $class          Expanded class name
257          */
258         public static function getConnectionClassName ($address, $port, $className) {
259                 // Construct it
260                 $class = $address . ':' . $port . ':' . $className;
261
262                 // ... and return it
263                 return $class;
264         }
265
266         /**
267          * Initializes the peer's state which sets it to 'init'
268          *
269          * @return      void
270          */
271         private function initState() {
272                 /*
273                  * Get the state factory and create the initial state, we don't need
274                  * the state instance here
275                  */
276                 PeerStateFactory::createPeerStateInstanceByName('init', $this);
277         }
278
279         /**
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.
284          *
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
288          * 3) Request a chunk
289          * 4) Finally return the chunk (array) to the caller
290          *
291          * @param       $packageData    Raw package data array
292          * @return      $chunkData              Raw data chunk
293          */
294         private function getRawDataFromPackageArray (array $packageData) {
295                 // Get the fragmenter instance
296                 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
297
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;
302                 } // END - if
303
304                 // Debug message
305                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: currentFinalHash=' . $this->currentFinalHash);
306
307                 // Get the next raw data chunk from the fragmenter
308                 $rawDataChunk = $fragmenterInstance->getNextRawDataChunk($this->currentFinalHash);
309
310                 // Get chunk hashes and chunk data
311                 $chunkHashes = array_keys($rawDataChunk);
312                 $chunkData   = array_values($rawDataChunk);
313
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];
319
320                         // Return the raw data
321                         return $chunkData[0];
322                 } else {
323                         // Return zero string
324                         return '';
325                 }
326         }
327
328         /**
329          * "Accept" a visitor by simply calling it back
330          *
331          * @param       $visitorInstance        A Visitor instance
332          * @return      void
333          */
334         protected final function accept (Visitor $visitorInstance) {
335                 // Just call the visitor
336                 $visitorInstance->visitConnectionHelper($this);
337         }
338
339         /**
340          * Sends raw package data to the recipient
341          *
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
345          */
346         public function sendRawPackageData (array $packageData) {
347                 // The helper's state must be 'connected'
348                 $this->getStateInstance()->validatePeerStateConnected();
349
350                 // Cache buffer length
351                 $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
352
353                 // Init variables
354                 $rawData        = '';
355                 $dataStream     = ' ';
356                 $totalSentBytes = 0;
357
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;
364                 } // END - while
365
366                 // Nothing to sent is bad news, so assert on it
367                 assert(strlen($rawData) > 0);
368
369                 // Encode the raw data with our output-stream
370                 $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
371
372                 // Calculate difference
373                 $this->diff = $bufferSize - strlen($encodedData);
374
375                 // Get socket resource
376                 $socketResource = $this->getSocketResource();
377
378                 // Init sent bytes
379                 $sentBytes = 0;
380
381                 // Deliver all data
382                 while ($sentBytes !== false) {
383                         // And deliver it
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));
386
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'));
391
392                                 // And throw it
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__ . ')');
397                                 break;
398                         }
399
400                         // The difference between sent bytes and length of raw data should not go below zero
401                         assert((strlen($encodedData) - $sentBytes) >= 0);
402
403                         // Add total sent bytes
404                         $totalSentBytes += $sentBytes;
405
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);
409
410                         // Calculate difference again
411                         $this->diff = $bufferSize - strlen($encodedData);
412
413                         // Can we abort?
414                         if (strlen($encodedData) <= 0) {
415                                 // Abort here, all sent!
416                                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
417                                 break;
418                         } // END - if
419                 } // END - while
420
421                 // Return sent bytes
422                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: totalSentBytes=' . $totalSentBytes);
423                 return $totalSentBytes;
424         }
425
426         /**
427          * Marks this connection as shutted down
428          *
429          * @return      void
430          */
431         protected final function markConnectionShuttedDown () {
432                 /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ' has been marked as shutted down');
433                 $this->shuttedDown = true;
434
435                 // And remove the (now invalid) socket
436                 $this->setSocketResource(false);
437         }
438
439         /**
440          * Getter for shuttedDown
441          *
442          * @return      $shuttedDown    Wether this connection is shutted down
443          */
444         public final function isShuttedDown () {
445                 /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
446                 return $this->shuttedDown;
447         }
448
449         // ************************************************************************
450         //                 Socket error handler call-back methods
451         // ************************************************************************
452
453         /**
454          * Handles socket error 'connection timed out', but does not clear it for
455          * later debugging purposes.
456          *
457          * @param       $socketResource         A valid socket resource
458          * @return      void
459          * @throws      SocketConnectionException       The connection attempts fails with a time-out
460          */
461         protected function socketErrorConnectionTimedOutHandler ($socketResource) {
462                 // Get socket error code for verification
463                 $socketError = socket_last_error($socketResource);
464
465                 // Get error message
466                 $errorMessage = socket_strerror($socketError);
467
468                 // Shutdown this socket
469                 $this->shutdownSocket($socketResource);
470
471                 // Throw it again
472                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
473         }
474
475         /**
476          * Handles socket error 'resource temporary unavailable', but does not
477          * clear it for later debugging purposes.
478          *
479          * @param       $socketResource         A valid socket resource
480          * @return      void
481          * @throws      SocketConnectionException       The connection attempts fails with a time-out
482          */
483         protected function socketErrorResourceUnavailableHandler ($socketResource) {
484                 // Get socket error code for verification
485                 $socketError = socket_last_error($socketResource);
486
487                 // Get error message
488                 $errorMessage = socket_strerror($socketError);
489
490                 // Shutdown this socket
491                 $this->shutdownSocket($socketResource);
492
493                 // Throw it again
494                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
495         }
496
497         /**
498          * Handles socket error 'connection refused', but does not clear it for
499          * later debugging purposes.
500          *
501          * @param       $socketResource         A valid socket resource
502          * @return      void
503          * @throws      SocketConnectionException       The connection attempts fails with a time-out
504          */
505         protected function socketErrorConnectionRefusedHandler ($socketResource) {
506                 // Get socket error code for verification
507                 $socketError = socket_last_error($socketResource);
508
509                 // Get error message
510                 $errorMessage = socket_strerror($socketError);
511
512                 // Shutdown this socket
513                 $this->shutdownSocket($socketResource);
514
515                 // Throw it again
516                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
517         }
518
519         /**
520          * Handles socket error 'no route to host', but does not clear it for later
521          * debugging purposes.
522          *
523          * @param       $socketResource         A valid socket resource
524          * @return      void
525          * @throws      SocketConnectionException       The connection attempts fails with a time-out
526          */
527         protected function socketErrorNoRouteToHostHandler ($socketResource) {
528                 // Get socket error code for verification
529                 $socketError = socket_last_error($socketResource);
530
531                 // Get error message
532                 $errorMessage = socket_strerror($socketError);
533
534                 // Shutdown this socket
535                 $this->shutdownSocket($socketResource);
536
537                 // Throw it again
538                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
539         }
540
541         /**
542          * Handles socket error 'operation already in progress' which happens in
543          * method connectToPeerByRecipientDataArray() on timed out connection
544          * attempts.
545          *
546          * @param       $socketResource         A valid socket resource
547          * @return      void
548          * @throws      SocketConnectionException       The connection attempts fails with a time-out
549          */
550         protected function socketErrorOperationAlreadyProgressHandler ($socketResource) {
551                 // Get socket error code for verification
552                 $socketError = socket_last_error($socketResource);
553
554                 // Get error message
555                 $errorMessage = socket_strerror($socketError);
556
557                 // Half-shutdown this socket (see there for difference to shutdownSocket())
558                 $this->halfShutdownSocket($socketResource);
559
560                 // Throw it again
561                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
562         }
563
564         /**
565          * Handles socket "error" 'operation now in progress' which can be safely
566          * passed on with non-blocking connections.
567          *
568          * @param       $socketResource         A valid socket resource
569          * @return      void
570          */
571         protected function socketErrorOperationInProgressHandler ($socketResource) {
572                 $this->debugOutput('CONNECTION: Operation is now in progress, this is usual for non-blocking connections and no bug.');
573         }
574 }
575
576 // [EOF]
577 ?>