920819b7a2925751dec4bceadea49bea56cbcea7
[core.git] / inc / main / classes / listener / class_BaseListener.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Listener;
4
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Object\BaseFrameworkSystem;
8
9 /**
10  * A general listener class
11  *
12  * @author              Roland Haeder <webmaster@shipsimu.org>
13  * @version             0.0.0
14  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15  * @license             GNU GPL 3.0 or any newer version
16  * @link                http://www.shipsimu.org
17  *
18  * This program is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
30  */
31 class BaseListener extends BaseFrameworkSystem implements Visitable {
32         // Exception code constants
33         const EXCEPTION_INVALID_SOCKET                   = 0xa00;
34         const EXCEPTION_SOCKET_ALREADY_REGISTERED        = 0xa01;
35         const EXCEPTION_SOCKET_CREATION_FAILED           = 0xa02;
36         const EXCEPTION_NO_SOCKET_ERROR                  = 0xa03;
37         const EXCEPTION_CONNECTION_ALREADY_REGISTERED    = 0xa04;
38         const EXCEPTION_UNEXPECTED_PACKAGE_STATUS        = 0xa05;
39         const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
40         const EXCEPTION_FINAL_CHUNK_VERIFICATION         = 0xa07;
41         const EXCEPTION_INVALID_DATA_CHECKSUM            = 0xa08;
42
43         /**
44          * Address (IP mostly) we shall listen on
45          */
46         private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
47
48         /**
49          * Port we shall listen on (or wait for incoming data)
50          */
51         private $listenPort = 0; // This port MUST be changed by your application
52
53         /**
54          * Whether we are in blocking or non-blocking mode (default: non-blocking
55          */
56         private $blockingMode = FALSE;
57
58         /**
59          * A peer pool instance
60          */
61         private $poolInstance = NULL;
62
63         /**
64          * Protected constructor
65          *
66          * @param       $className      Name of the class
67          * @return      void
68          */
69         protected function __construct ($className) {
70                 // Call parent constructor
71                 parent::__construct($className);
72         }
73
74         /**
75          * Checks whether the given socket resource is a server socket
76          *
77          * @param       $socketResource         A valid socket resource
78          * @return      $isServerSocket         Whether the socket resource is a server socket
79          */
80         protected function isServerSocketResource ($socketResource) {
81                 // Check it
82                 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
83
84                 // We need to clear the error here if it is a resource
85                 if ($isServerSocket === TRUE) {
86                         // Clear the error
87                         //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('socketResource[]=' . gettype($socketResource));
88                         socket_clear_error($socketResource);
89                 } // END - if
90
91                 // Check peer name, it must be empty
92                 $isServerSocket = (($isServerSocket) && (empty($peerName)));
93
94                 // Return result
95                 return $isServerSocket;
96         }
97
98         /**
99          * Setter for listen address
100          *
101          * @param       $listenAddress  The address this listener should listen on
102          * @return      void
103          */
104         protected final function setListenAddress ($listenAddress) {
105                 $this->listenAddress = (string) $listenAddress;
106         }
107
108         /**
109          * Getter for listen address
110          *
111          * @return      $listenAddress  The address this listener should listen on
112          */
113         public final function getListenAddress () {
114                 return $this->listenAddress;
115         }
116
117         /**
118          * Setter for listen port
119          *
120          * @param       $listenPort             The port this listener should listen on
121          * @return      void
122          */
123         protected final function setListenPort ($listenPort) {
124                 $this->listenPort = (int) $listenPort;
125         }
126
127         /**
128          * Getter for listen port
129          *
130          * @return      $listenPort             The port this listener should listen on
131          */
132         public final function getListenPort () {
133                 return $this->listenPort;
134         }
135
136         /**
137          * "Setter" to set listen address from configuration entry
138          *
139          * @param       $configEntry    The configuration entry holding our listen address
140          * @return      void
141          */
142         public final function setListenAddressByConfiguration ($configEntry) {
143                 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
144         }
145
146         /**
147          * "Setter" to set listen port from configuration entry
148          *
149          * @param       $configEntry    The configuration entry holding our listen port
150          * @return      void
151          */
152         public final function setListenPortByConfiguration ($configEntry) {
153                 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
154         }
155
156         /**
157          * Setter for blocking-mode
158          *
159          * @param       $blockingMode   Whether blocking-mode is disabled (default) or enabled
160          * @return      void
161          */
162         protected final function setBlockingMode ($blockingMode) {
163                 $this->blockingMode = (boolean) $blockingMode;
164         }
165
166         /**
167          * Checks whether blocking-mode is enabled or disabled
168          *
169          * @return      $blockingMode   Whether blocking mode is disabled or enabled
170          */
171         public final function isBlockingModeEnabled () {
172                 return $this->blockingMode;
173         }
174
175         /**
176          * Setter for peer pool instance
177          *
178          * @param       $poolInstance   The peer pool instance we shall set
179          * @return      void
180          */
181         protected final function setPoolInstance (PoolablePeer $poolInstance) {
182                 $this->poolInstance = $poolInstance;
183         }
184
185         /**
186          * Getter for peer pool instance
187          *
188          * @return      $poolInstance   The peer pool instance we shall set
189          */
190         public final function getPoolInstance () {
191                 return $this->poolInstance;
192         }
193
194         /**
195          * Getter for connection type
196          *
197          * @return      $connectionType         Connection type for this listener
198          */
199         public final function getConnectionType () {
200                 // Wrap the real getter
201                 return $this->getProtocolName();
202         }
203
204         /**
205          * Registeres the given socket resource for "this" listener instance. This
206          * will be done in a seperate class to allow package writers to use it
207          * again.
208          *
209          * @param       $socketResource         A valid server socket resource
210          * @return      void
211          * @throws      InvalidServerSocketException            If the given resource is no server socket
212          * @throws      SocketAlreadyRegisteredException        If the given resource is already registered
213          */
214         protected function registerServerSocketResource ($socketResource) {
215                 // First check if it is valid
216                 if (!$this->isServerSocketResource($socketResource)) {
217                         // No server socket
218                         throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
219                 } elseif ($this->isServerSocketRegistered($socketResource)) {
220                         // Already registered
221                         throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
222                 }
223
224                 // Get a socket registry instance (singleton)
225                 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
226
227                 // Get a connection info instance
228                 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
229
230                 // Will the info instance with listener data
231                 $infoInstance->fillWithListenerInformation($this);
232
233                 // Register the socket
234                 $registryInstance->registerSocket($infoInstance, $socketResource);
235
236                 // And set it here
237                 $this->setSocketResource($socketResource);
238         }
239
240         /**
241          * Checks whether given socket resource is registered in socket registry
242          *
243          * @param       $socketResource         A valid server socket resource
244          * @return      $isRegistered           Whether given server socket is registered
245          */
246         protected function isServerSocketRegistered ($socketResource) {
247                 // Get a socket registry instance (singleton)
248                 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
249
250                 // Get a connection info instance
251                 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
252
253                 // Will the info instance with listener data
254                 $infoInstance->fillWithListenerInformation($this);
255
256                 // Check it
257                 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
258
259                 // Return result
260                 return $isRegistered;
261         }
262
263         /**
264          * Accepts the visitor to process the visit "request"
265          *
266          * @param       $visitorInstance        An instance of a Visitor class
267          * @return      void
268          */
269         public function accept (Visitor $visitorInstance) {
270                 // Debug message
271                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
272
273                 // Visit this listener
274                 $visitorInstance->visitListener($this);
275
276                 // Visit the pool if set
277                 if ($this->getPoolInstance() instanceof Poolable) {
278                         $this->getPoolInstance()->accept($visitorInstance);
279                 } // END - if
280
281                 // Debug message
282                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
283         }
284
285         /**
286          * Monitors incoming raw data from the handler and transfers it to the
287          * given receiver instance. This method should not be called, please call
288          * the decorator's version instead to separator node/client traffic.
289          *
290          * @return      void
291          * @throws      UnsupportedOperatorException    If this method is called by a mistake
292          */
293         public function monitorIncomingRawData () {
294                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
295         }
296
297         /**
298          * Constructs a callable method name from given socket error code. If the
299          * method is not found, a generic one is used.
300          *
301          * @param       $errorCode              Error code from socket_last_error()
302          * @return      $handlerName    Call-back method name for the error handler
303          * @throws      UnsupportedSocketErrorHandlerException If the error handler is not implemented
304          */
305         protected function getSocketErrorHandlerFromCode ($errorCode) {
306                 // Create a name from translated error code
307                 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
308
309                 // Is the call-back method there?
310                 if (!method_exists($this, $handlerName)) {
311                         // Please implement this
312                         throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
313                 } // END - if
314
315                 // Return it
316                 return $handlerName;
317         }
318
319         /**
320          * Translates socket error codes into our own internal names which can be
321          * used for call-backs.
322          *
323          * @param       $errorCode      The error code from socket_last_error() to be translated
324          * @return      $errorName      The translated name (all lower-case, with underlines)
325          */
326         public function translateSocketErrorCodeToName ($errorCode) {
327                 // Nothing bad happened by default
328                 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
329
330                 // Is the code a number, then we have to change it
331                 switch ($errorCode) {
332                         case 0: // Silently ignored, the socket is connected
333                                 break;
334
335                         case 11:  // "Resource temporary unavailable"
336                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
337                                 break;
338
339                         case 13:  // "Permission denied"
340                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
341                                 break;
342
343                         case 32:  // "Broken pipe"
344                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
345                                 break;
346
347                         case 104: // "Connection reset by peer"
348                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
349                                 break;
350
351                         case 107: // "Transport end-point not connected"
352                         case 134: // On some (?) systems for 'transport end-point not connected'
353                                 // @TODO On some systems it is 134, on some 107?
354                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
355                                 break;
356
357                         case 110: // "Connection timed out"
358                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
359                                 break;
360
361                         case 111: // "Connection refused"
362                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
363                                 break;
364
365                         case 113: // "No route to host"
366                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
367                                 break;
368
369                         case 114: // "Operation already in progress"
370                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
371                                 break;
372
373                         case 115: // "Operation now in progress"
374                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
375                                 break;
376
377                         default: // Everything else <> 0
378                                 // Unhandled error code detected, so first debug it because we may want to handle it like the others
379                                 self::createDebugInstance(__CLASS__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
380
381                                 // Change it only in this class
382                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
383                                 break;
384                 }
385
386                 // Return translated name
387                 return $errorName;
388         }
389
390         /**
391          * Shuts down a given socket resource. This method does only ease calling
392          * the right visitor.
393          *
394          * @param       $socketResource         A valid socket resource
395          * @return      void
396          */
397         public function shutdownSocket ($socketResource) {
398                 // Debug message
399                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
400
401                 // Set socket resource
402                 $this->setSocketResource($socketResource);
403
404                 // Get a visitor instance
405                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
406
407                 // Debug output
408                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
409
410                 // Call the visitor
411                 $this->accept($visitorInstance);
412         }
413
414         /**
415          * Half-shuts down a given socket resource. This method does only ease calling
416          * an other visitor than shutdownSocket() does.
417          *
418          * @param       $socketResource         A valid socket resource
419          * @return      void
420          */
421         public function halfShutdownSocket ($socketResource) {
422                 // Debug message
423                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
424
425                 // Set socket resource
426                 $this->setSocketResource($socketResource);
427
428                 // Get a visitor instance
429                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
430
431                 // Debug output
432                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
433
434                 // Call the visitor
435                 $this->accept($visitorInstance);
436         }
437
438         // ************************************************************************
439         //                 Socket error handler call-back methods
440         // ************************************************************************
441
442         /**
443          * Handles socket error 'permission denied', but does not clear it for
444          * later debugging purposes.
445          *
446          * @param       $socketResource         A valid socket resource
447          * @param       $socketData                     A valid socket data array (0 = IP/file name, 1 = port)
448          * @return      void
449          * @throws      SocketBindingException  The socket could not be bind to
450          */
451         protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
452                 // Get socket error code for verification
453                 $socketError = socket_last_error($socketResource);
454
455                 // Get error message
456                 $errorMessage = socket_strerror($socketError);
457
458                 // Shutdown this socket
459                 $this->shutdownSocket($socketResource);
460
461                 // Throw it again
462                 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
463         }
464
465         /**
466          * "Listens" for incoming network packages
467          *
468          * @param       $peerSuffix             Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
469          * @return      void
470          * @throws      InvalidSocketException  If an invalid socket resource has been found
471          */
472         protected function doListenSocketSelect ($peerSuffix) {
473                 // Check on all instances
474                 assert($this->getPoolInstance() instanceof Poolable);
475                 assert(is_resource($this->getSocketResource()));
476
477                 // Get all readers
478                 $readers = $this->getPoolInstance()->getAllSingleSockets();
479                 $writers = array();
480                 $excepts = array();
481
482                 // Check if we have some peers left
483                 $left = socket_select(
484                         $readers,
485                         $writers,
486                         $excepts,
487                         0,
488                         150
489                 );
490
491                 // Some new peers found?
492                 if ($left < 1) {
493                         // Debug message
494                         //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
495
496                         // Nothing new found
497                         return;
498                 } // END - if
499
500                 // Debug message
501                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
502
503                 // Do we have changed peers?
504                 if (in_array($this->getSocketResource(), $readers)) {
505                         /*
506                          * Then accept it, if this socket is set to non-blocking IO and the
507                          * connection is NOT sending any data, socket_read() may throw
508                          * error 11 (Resource temporary unavailable). This really nasty
509                          * because if you have blocking IO socket_read() will wait and wait
510                          * and wait ...
511                          */
512                         $newSocket = socket_accept($this->getSocketResource());
513
514                         // Debug message
515                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
516
517                         // Array for timeout settings
518                         $options  = array(
519                                 // Seconds
520                                 'sec'  => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
521                                 // Milliseconds
522                                 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
523                         );
524
525                         // Set timeout to configured seconds
526                         // @TODO Does this work on Windozer boxes???
527                         if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
528                                 // Handle this socket error with a faked recipientData array
529                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
530                         } // END - if
531
532                         // Output result (only for debugging!)
533                         /*
534                         $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
535                         self::createDebugInstance(__CLASS__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, TRUE));
536                         */
537
538                         // Enable SO_OOBINLINE
539                         if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
540                                 // Handle this socket error with a faked recipientData array
541                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
542                         } // END - if
543
544                         // Set non-blocking
545                         if (!socket_set_nonblock($newSocket)) {
546                                 // Handle this socket error with a faked recipientData array
547                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
548                         } // END - if
549
550                         // Add it to the peers
551                         $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
552
553                         // Get peer name
554                         if (!socket_getpeername($newSocket, $peerName)) {
555                                 // Handle this socket error with a faked recipientData array
556                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
557                         } // END - if
558
559                         // Get node instance
560                         $nodeInstance = NodeObjectFactory::createNodeInstance();
561
562                         // Create a faked package data array
563                         $packageData = array(
564                                 NetworkPackage::PACKAGE_DATA_SENDER    => $peerName . $peerSuffix,
565                                 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
566                                 NetworkPackage::PACKAGE_DATA_STATUS    => NetworkPackage::PACKAGE_STATUS_FAKED
567                         );
568
569                         // Get a connection info instance
570                         $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
571
572                         // Will the info instance with listener data
573                         $infoInstance->fillWithListenerInformation($this);
574
575                         // Get a socket registry
576                         $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
577
578                         // Register the socket with the registry and with the faked array
579                         $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
580                 } // END - if
581
582                 // Do we have to rewind?
583                 if (!$this->getIteratorInstance()->valid()) {
584                         // Rewind the list
585                         $this->getIteratorInstance()->rewind();
586                 } // END - if
587
588                 // Get the current value
589                 $currentSocket = $this->getIteratorInstance()->current();
590
591                 // Handle it here, if not main server socket
592                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: currentSocket=' . $currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] . ',type=' . $currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] . ',serverSocket=' . $this->getSocketResource());
593                 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
594                         // ... or else it will raise warnings like 'Transport endpoint is not connected'
595                         $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
596                 } // END - if
597
598                 // Advance to next entry. This should be the last line.
599                 $this->getIteratorInstance()->next();
600         }
601
602 }