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