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