]> git.mxchange.org Git - hub.git/blob - application/hub/main/helper/connection/class_BaseConnectionHelper.php
'hub' project continued:
[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          * Whether 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                 // Get the fragmenter instance
96                 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
97
98                 // Set it here
99                 $this->setFragmenterInstance($fragmenterInstance);
100         }
101
102         /**
103          * Getter for real class name, overwrites generic method and is final
104          *
105          * @return      $class  Name of this class
106          */
107         public final function __toString () {
108                 // Class name representation
109                 $class = self::getConnectionClassName($this->getAddress(), $this->getPort(), parent::__toString());
110
111                 // Return it
112                 return $class;
113         }
114
115         /**
116          * Getter for port number to satify ProtocolHandler
117          *
118          * @return      $port   The port number
119          */
120         public final function getPort () {
121                 return $this->port;
122         }
123
124         /**
125          * Setter for port number to satify ProtocolHandler
126          *
127          * @param       $port   The port number
128          * @return      void
129          */
130         protected final function setPort ($port) {
131                 $this->port = $port;
132         }
133
134         /**
135          * Getter for protocol
136          *
137          * @return      $protocol       Used protocol
138          */
139         public final function getProtocol () {
140                 return $this->protocol;
141         }
142
143         /**
144          * Setter for protocol
145          *
146          * @param       $protocol       Used protocol
147          * @return      void
148          */
149         protected final function setProtocol ($protocol) {
150                 $this->protocol = $protocol;
151         }
152
153         /**
154          * Getter for IP address
155          *
156          * @return      $address        The IP address
157          */
158         public final function getAddress () {
159                 return $this->address;
160         }
161
162         /**
163          * Setter for IP address
164          *
165          * @param       $address        The IP address
166          * @return      void
167          */
168         protected final function setAddress ($address) {
169                 $this->address = $address;
170         }
171
172         /**
173          * Initializes the current connection
174          *
175          * @return      void
176          * @throws      SocketOptionException   If setting any socket option fails
177          */
178         protected function initConnection () {
179                 // Get socket resource
180                 $socketResource = $this->getSocketResource();
181
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'));
186
187                         // And throw again
188                         // @TODO Move this to the socket error handler
189                         throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
190                 } // END - if
191
192                 /*
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(); .
196                  */
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'));
200
201                         // And throw again
202                         throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
203                 } // END - if
204
205                 // Last step: mark connection as initialized
206                 $this->isInitialized = true;
207         }
208
209         /**
210          * Attempts to connect to a peer by given IP number and port from a valid
211          * recipientData array with currently configured timeout.
212          *
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
217          */
218         protected function connectToPeerByRecipientDataArray (array $recipientData) {
219                 // Only call this if the connection is initialized by initConnection()
220                 assert($this->isInitialized === true);
221
222                 // Get current time
223                 $time = time();
224
225                 // "Cache" socket resource and timeout config
226                 $socketResource = $this->getSocketResource();
227                 $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
228
229                 // Debug output
230                 $this->debugOutput('CONNECTION-HELPER: Trying to connect to ' . $recipientData[0] . ':' . $recipientData[1] . ' with socketResource[' . gettype($socketResource) . ']=' . $socketResource . ' ...');
231
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);
236
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;
243                                         break;
244                                 } // END - if
245
246                                 // Sleep about one second
247                                 $this->idle(1000);
248                         } elseif ($socketError != 0) {
249                                 // Stop on everything else pronto
250                                 $isConnected = false;
251                                 break;
252                         }
253                 } // END - while
254
255                 // Return status
256                 return $isConnected;
257         }
258
259         /**
260          * Static "getter" for this connection class' name
261          *
262          * @param       $address        IP address
263          * @param       $port           Port number
264          * @param       $className      Original class name
265          * @return      $class          Expanded class name
266          */
267         public static function getConnectionClassName ($address, $port, $className) {
268                 // Construct it
269                 $class = $address . ':' . $port . ':' . $className;
270
271                 // ... and return it
272                 return $class;
273         }
274
275         /**
276          * Initializes the peer's state which sets it to 'init'
277          *
278          * @return      void
279          */
280         private function initState() {
281                 /*
282                  * Get the state factory and create the initial state, we don't need
283                  * the state instance here
284                  */
285                 PeerStateFactory::createPeerStateInstanceByName('init', $this);
286         }
287
288         /**
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.
293          *
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
297          * 3) Request a chunk
298          * 4) Finally return the chunk (array) to the caller
299          *
300          * @param       $packageData    Raw package data array
301          * @return      $chunkData              Raw data chunk
302          */
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;
308                 } // END - if
309
310                 // Debug message
311                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: currentFinalHash=' . $this->currentFinalHash);
312
313                 // Get the next raw data chunk from the fragmenter
314                 $rawDataChunk = $this->getFragmenterInstance()->getNextRawDataChunk($this->currentFinalHash);
315
316                 // Get chunk hashes and chunk data
317                 $chunkHashes = array_keys($rawDataChunk);
318                 $chunkData   = array_values($rawDataChunk);
319
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];
326
327                         // Return the raw data
328                         //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Returning ' . strlen($chunkData[0]) . ' bytes from ' . __METHOD__ . ' ...');
329                         return $chunkData[0];
330                 } else {
331                         // Return zero string
332                         //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Returning zero bytes from ' . __METHOD__ . '!');
333                         return '';
334                 }
335         }
336
337         /**
338          * "Accept" a visitor by simply calling it back
339          *
340          * @param       $visitorInstance        A Visitor instance
341          * @return      void
342          */
343         protected final function accept (Visitor $visitorInstance) {
344                 // Just call the visitor
345                 $visitorInstance->visitConnectionHelper($this);
346         }
347
348         /**
349          * Sends raw package data to the recipient
350          *
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
354          */
355         public function sendRawPackageData (array $packageData) {
356                 // The helper's state must be 'connected'
357                 $this->getStateInstance()->validatePeerStateConnected();
358
359                 // Cache buffer length
360                 $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
361
362                 // Init variables
363                 $rawData        = '';
364                 $dataStream     = ' ';
365                 $totalSentBytes = 0;
366
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;
373                 } // END - while
374                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: rawData[' . strlen($rawData) . ']=' . $rawData);
375
376                 // Nothing to sent is bad news, so assert on it
377                 assert(strlen($rawData) > 0);
378
379                 // Encode the raw data with our output-stream
380                 $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
381
382                 // Calculate difference
383                 $this->diff = $bufferSize - strlen($encodedData);
384
385                 // Get socket resource
386                 $socketResource = $this->getSocketResource();
387
388                 // Init sent bytes
389                 $sentBytes = 0;
390
391                 // Deliver all data
392                 while ($sentBytes !== false) {
393                         // And deliver it
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));
398                         } else {
399                                 // Send buffer size out
400                                 $sentBytes = @socket_write($socketResource, $encodedData, $bufferSize);
401                         }
402
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'));
407
408                                 // And throw it
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__ . ')');
413                                 break;
414                         }
415
416                         // The difference between sent bytes and length of raw data should not go below zero
417                         assert((strlen($encodedData) - $sentBytes) >= 0);
418
419                         // Add total sent bytes
420                         $totalSentBytes += $sentBytes;
421
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);
425
426                         // Calculate difference again
427                         $this->diff = $bufferSize - strlen($encodedData);
428
429                         // Can we abort?
430                         if (strlen($encodedData) <= 0) {
431                                 // Abort here, all sent!
432                                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (LINE=' . __LINE__ . ')');
433                                 break;
434                         } // END - if
435                 } // END - while
436
437                 // Return sent bytes
438                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: totalSentBytes=' . $totalSentBytes . ',diff=' . $this->diff);
439                 return $totalSentBytes;
440         }
441
442         /**
443          * Marks this connection as shutted down
444          *
445          * @return      void
446          */
447         protected final function markConnectionShuttedDown () {
448                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ' has been marked as shutted down');
449                 $this->shuttedDown = true;
450
451                 // And remove the (now invalid) socket
452                 $this->setSocketResource(false);
453         }
454
455         /**
456          * Getter for shuttedDown
457          *
458          * @return      $shuttedDown    Whether this connection is shutted down
459          */
460         public final function isShuttedDown () {
461                 //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
462                 return $this->shuttedDown;
463         }
464
465         // ************************************************************************
466         //                 Socket error handler call-back methods
467         // ************************************************************************
468
469         /**
470          * Handles socket error 'connection timed out', but does not clear it for
471          * later debugging purposes.
472          *
473          * @param       $socketResource         A valid socket resource
474          * @return      void
475          * @throws      SocketConnectionException       The connection attempts fails with a time-out
476          */
477         protected function socketErrorConnectionTimedOutHandler ($socketResource) {
478                 // Get socket error code for verification
479                 $socketError = socket_last_error($socketResource);
480
481                 // Get error message
482                 $errorMessage = socket_strerror($socketError);
483
484                 // Shutdown this socket
485                 $this->shutdownSocket($socketResource);
486
487                 // Throw it again
488                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
489         }
490
491         /**
492          * Handles socket error 'resource temporary unavailable', but does not
493          * clear it for later debugging purposes.
494          *
495          * @param       $socketResource         A valid socket resource
496          * @return      void
497          * @throws      SocketConnectionException       The connection attempts fails with a time-out
498          */
499         protected function socketErrorResourceUnavailableHandler ($socketResource) {
500                 // Get socket error code for verification
501                 $socketError = socket_last_error($socketResource);
502
503                 // Get error message
504                 $errorMessage = socket_strerror($socketError);
505
506                 // Shutdown this socket
507                 $this->shutdownSocket($socketResource);
508
509                 // Throw it again
510                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
511         }
512
513         /**
514          * Handles socket error 'connection refused', but does not clear it for
515          * later debugging purposes.
516          *
517          * @param       $socketResource         A valid socket resource
518          * @return      void
519          * @throws      SocketConnectionException       The connection attempts fails with a time-out
520          */
521         protected function socketErrorConnectionRefusedHandler ($socketResource) {
522                 // Get socket error code for verification
523                 $socketError = socket_last_error($socketResource);
524
525                 // Get error message
526                 $errorMessage = socket_strerror($socketError);
527
528                 // Shutdown this socket
529                 $this->shutdownSocket($socketResource);
530
531                 // Throw it again
532                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
533         }
534
535         /**
536          * Handles socket error 'no route to host', but does not clear it for later
537          * debugging purposes.
538          *
539          * @param       $socketResource         A valid socket resource
540          * @return      void
541          * @throws      SocketConnectionException       The connection attempts fails with a time-out
542          */
543         protected function socketErrorNoRouteToHostHandler ($socketResource) {
544                 // Get socket error code for verification
545                 $socketError = socket_last_error($socketResource);
546
547                 // Get error message
548                 $errorMessage = socket_strerror($socketError);
549
550                 // Shutdown this socket
551                 $this->shutdownSocket($socketResource);
552
553                 // Throw it again
554                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
555         }
556
557         /**
558          * Handles socket error 'operation already in progress' which happens in
559          * method connectToPeerByRecipientDataArray() on timed out connection
560          * attempts.
561          *
562          * @param       $socketResource         A valid socket resource
563          * @return      void
564          * @throws      SocketConnectionException       The connection attempts fails with a time-out
565          */
566         protected function socketErrorOperationAlreadyProgressHandler ($socketResource) {
567                 // Get socket error code for verification
568                 $socketError = socket_last_error($socketResource);
569
570                 // Get error message
571                 $errorMessage = socket_strerror($socketError);
572
573                 // Half-shutdown this socket (see there for difference to shutdownSocket())
574                 $this->halfShutdownSocket($socketResource);
575
576                 // Throw it again
577                 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
578         }
579
580         /**
581          * Handles socket "error" 'operation now in progress' which can be safely
582          * passed on with non-blocking connections.
583          *
584          * @param       $socketResource         A valid socket resource
585          * @return      void
586          */
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.');
589         }
590 }
591
592 // [EOF]
593 ?>