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