]> git.mxchange.org Git - hub.git/blob - application/hub/main/nodes/class_BaseHubNode.php
Rewrites, some more methods:
[hub.git] / application / hub / main / nodes / class_BaseHubNode.php
1 <?php
2 /**
3  * A general hub node class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24 class BaseHubNode extends BaseHubSystem implements Updateable {
25         /**
26          * Node types
27          */
28         const NODE_TYPE_BOOT    = 'boot';
29         const NODE_TYPE_MASTER  = 'master';
30         const NODE_TYPE_LIST    = 'list';
31         const NODE_TYPE_REGULAR = 'regular';
32
33         // Exception constants
34         const EXCEPTION_HUB_ALREADY_ANNOUNCED = 0xe00;
35
36         // Other constants
37         const OBJECT_LIST_SEPARATOR = ',';
38
39         /**
40          * IP/port number of bootstrapping node
41          */
42         private $bootIpPort = '';
43
44         /**
45          * Query connector instance
46          */
47         private $queryConnectorInstance = NULL;
48
49         /**
50          * Queue connector instance
51          */
52         private $queueConnectorInstance = NULL;
53
54         /**
55          * Whether this node is anncounced (KEEP ON false!)
56          * @deprecated
57          */
58         private $hubIsAnnounced = false;
59
60         /**
61          * Whether this hub is active (default: false)
62          */
63         private $isActive = false;
64
65         /**
66          * Whether this node accepts announcements (default: false)
67          */
68         private $acceptAnnouncements = false;
69
70         /**
71          * Protected constructor
72          *
73          * @param       $className      Name of the class
74          * @return      void
75          */
76         protected function __construct ($className) {
77                 // Call parent constructor
78                 parent::__construct($className);
79
80                 // Get a wrapper instance
81                 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_info_db_wrapper_class');
82
83                 // Set it here
84                 $this->setWrapperInstance($wrapperInstance);
85
86                 // Get a crypto instance
87                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
88
89                 // Set it here
90                 $this->setCryptoInstance($cryptoInstance);
91
92                 // Init state which sets the state to 'init'
93                 $this->initState();
94         }
95
96         /**
97          * Initializes the node's state which sets it to 'init'
98          *
99          * @return      void
100          */
101         private function initState() {
102                 /*
103                  * Get the state factory and create the initial state, we don't need
104                  * the state instance here
105                  */
106                 NodeStateFactory::createNodeStateInstanceByName('init', $this);
107         }
108
109         /**
110          * Generates a random string from various data inluding UUID if PECL
111          * extension uuid is installed.
112          *
113          * @param       $length                 Length of the random part
114          * @return      $randomString   Random string
115          * @todo        Make this code more generic and move it to CryptoHelper or
116          */
117         protected function generateRamdomString ($length) {
118                 // Get an RNG instance
119                 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
120
121                 // Generate a pseudo-random string
122                 $randomString = $rngInstance->randomString($length) . ':' . $this->getBootIpPort() . ':' . $this->getRequestInstance()->getRequestElement('mode');
123
124                 // Add UUID for even more entropy for the hasher
125                 $randomString .= $this->getCryptoInstance()->createUuid();
126
127                 // Return it
128                 return $randomString;
129         }
130
131         /**
132          * Generates a private key and hashes it (for speeding up things)
133          *
134          * @param       $searchInstance         An instance of a LocalSearchCriteria class
135          * @return void
136          */
137         private function generatePrivateKeyAndHash (LocalSearchCriteria $searchInstance) {
138                 // Generate a pseudo-random string
139                 $randomString = $this->generateRandomString(255);
140
141                 // Hash and encrypt the string so we become a node id (also documented as "hub id")
142                 $this->setPrivateKey($this->getCryptoInstance()->encryptString($randomString));
143                 $this->setPrivateKeyHash($this->getCryptoInstance()->hashString($this->getPrivateKey()));
144
145                 // Register the node id with our wrapper
146                 $this->getWrapperInstance()->registerPrivateKey($this, $this->getRequestInstance(), $searchInstance);
147
148                 // Output message
149                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new private key with hash: ' . $this->getPrivateKeyHash() . '');
150         }
151
152         /**
153          * Setter for query instance
154          *
155          * @param       $connectorInstance              Our new query instance
156          * @return      void
157          */
158         private final function setQueryConnectorInstance (Connectable $connectorInstance) {
159                 $this->queryConnectorInstance = $connectorInstance;
160         }
161
162         /**
163          * Getter for query instance
164          *
165          * @return      $connectorInstance              Our new query instance
166          */
167         public final function getQueryConnectorInstance () {
168                 return $this->queryConnectorInstance;
169         }
170
171         /**
172          * Setter for queue instance
173          *
174          * @param       $connectorInstance              Our new queue instance
175          * @return      void
176          */
177         private final function setQueueConnectorInstance (Connectable $connectorInstance) {
178                 $this->queueConnectorInstance = $connectorInstance;
179         }
180
181         /**
182          * Getter for queue instance
183          *
184          * @return      $connectorInstance              Our new queue instance
185          */
186         public final function getQueueConnectorInstance () {
187                 return $this->queueConnectorInstance;
188         }
189
190         /**
191          * Getter for boot IP/port combination
192          *
193          * @return      $bootIpPort             The IP/port combination of the boot node
194          */
195         protected final function getBootIpPort () {
196                 return $this->bootIpPort;
197         }
198
199         /**
200          * Checks whether the given IP address matches one of the bootstrapping nodes
201          *
202          * @param       $remoteAddr             IP address to checkout against our bootstrapping list
203          * @return      $isFound                Whether the IP is found
204          */
205         protected function ifAddressMatchesBootstrappingNodes ($remoteAddr) {
206                 // By default nothing is found
207                 $isFound = false;
208
209                 // Run through all configured IPs
210                 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPARATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $ipPort) {
211                         // Split it up in IP/port
212                         $ipPortArray = explode(':', $ipPort);
213
214                         // Does it match?
215                         if ($ipPortArray[0] == $remoteAddr) {
216                                 // Found it!
217                                 $isFound = true;
218
219                                 // Remember the port number
220                                 $this->bootIpPort = $ipPort;
221
222                                 // Output message
223                                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches remote address ' . $ipPort . '.');
224
225                                 // Stop further searching
226                                 break;
227                         } elseif ($ipPortArray[0] == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
228                                 /*
229                                  * IP matches listen address. At this point we really don't care
230                                  * if we can really listen on that address
231                                  */
232                                 $isFound = true;
233
234                                 // Remember the port number
235                                 $this->bootIpPort = $ipPort;
236
237                                 // Output message
238                                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __LINE__ . ']: IP matches listen address ' . $ipPort . '.');
239
240                                 // Stop further searching
241                                 break;
242                         }
243                 } // END - foreach
244
245                 // Return the result
246                 return $isFound;
247         }
248
249         /**
250          * Outputs the console teaser. This should only be executed on startup or
251          * full restarts. This method generates some space around the teaser.
252          *
253          * @return      void
254          */
255         public function outputConsoleTeaser () {
256                 // Get the app instance (for shortening our code)
257                 $app = $this->getApplicationInstance();
258
259                 // Output all lines
260                 self::createDebugInstance(__CLASS__)->debugOutput(' ');
261                 self::createDebugInstance(__CLASS__)->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
262                 self::createDebugInstance(__CLASS__)->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2012 Hub Developer Team');
263                 self::createDebugInstance(__CLASS__)->debugOutput(' ');
264                 self::createDebugInstance(__CLASS__)->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
265                 self::createDebugInstance(__CLASS__)->debugOutput('This is free software, and you are welcome to redistribute it under certain');
266                 self::createDebugInstance(__CLASS__)->debugOutput('conditions; see docs/COPYING for details.');
267                 self::createDebugInstance(__CLASS__)->debugOutput(' ');
268         }
269
270         /**
271          * Generic method to acquire a hub-id. On first run this generates a new one
272          * based on many pseudo-random data. On any later run, unless the id
273          * got not removed from database, it will be restored from the database.
274          *
275          * @param       $requestInstance        A Requestable class
276          * @param       $responseInstance       A Responseable class
277          * @return      void
278          */
279         public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
280                 // Now get a search criteria instance
281                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
282
283                 // Search for the node number one which is hard-coded the default
284                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
285                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
286                 $searchInstance->setLimit(1);
287
288                 // Get a result back
289                 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
290
291                 // Is it valid?
292                 if ($resultInstance->next()) {
293                         // Save the result instance in this class
294                         $this->setResultInstance($resultInstance);
295
296                         // Get the node id from result and set it
297                         $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
298
299                         // Output message
300                         self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
301                 } else {
302                         // Generate a pseudo-random string
303                         $randomString = $this->generateRandomString(255);
304
305                         // Hash and encrypt the string so we become a node id (also documented as "hub id")
306                         $this->setNodeId($this->getCryptoInstance()->hashString($this->getCryptoInstance()->encryptString($randomString)));
307
308                         // Register the node id with our wrapper
309                         $this->getWrapperInstance()->registerNodeId($this, $this->getRequestInstance());
310
311                         // Output message
312                         self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
313                 }
314         }
315
316         /**
317          * Generates a session id which will be sent to the other hubs and peers
318          *
319          * @return      void
320          */
321         public function bootstrapGenerateSessionId () {
322                 // Now get a search criteria instance
323                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
324
325                 // Search for the node number one which is hard-coded the default
326                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
327                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
328                 $searchInstance->setLimit(1);
329
330                 // Get a random string
331                 $randomString = $this->generateRamdomString(255);
332
333                 // Hash and encrypt the string so we become a "node id" aka Hub-Id
334                 $this->setSessionId($this->getCryptoInstance()->hashString($this->getCryptoInstance()->encryptString($randomString)));
335
336                 // Register the node id with our wrapper
337                 $this->getWrapperInstance()->registerSessionId($this, $this->getRequestInstance(), $searchInstance);
338
339                 // Output message
340                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
341
342                 // Change the state because the node has auired a hub id
343                 $this->getStateInstance()->nodeGeneratedSessionId();
344         }
345
346         /**
347          * Generate a private key for en-/decryption
348          *
349          * @return      void
350          */
351         public function bootstrapGeneratePrivateKey () {
352                 // Now get a search criteria instance
353                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
354
355                 // Search for the node number one which is hard-coded the default
356                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
357                 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $this->getRequestInstance()->getRequestElement('mode'));
358                 $searchInstance->setLimit(1);
359
360                 // Get a result back
361                 $resultInstance = $this->getWrapperInstance()->doSelectByCriteria($searchInstance);
362
363                 // Is it valid?
364                 if ($resultInstance->next()) {
365                         // Save the result instance in this class
366                         $this->setResultInstance($resultInstance);
367
368                         // Is the element set?
369                         if (is_null($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY))) {
370                                 /*
371                                  * Auto-generate the private key for e.g. out-dated database
372                                  * "tables". This allows a smooth update for the underlaying
373                                  * database table.
374                                  */
375                                 $this->generatePrivateKeyAndHash($searchInstance);
376                         } else {
377                                 // Get the node id from result and set it
378                                 $this->setPrivateKey(base64_decode($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY)));
379                                 $this->setPrivateKeyHash($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH));
380
381                                 // Output message
382                                 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Re-using found private key hash: ' . $this->getPrivateKeyHash() . '');
383                         }
384                 } else {
385                         /*
386                          * Generate it in a private method (no confusion with 'private
387                          * method access' and 'private key' here! ;-)).
388                          */
389                         $this->generatePrivateKeyAndHash($searchInstance);
390                 }
391         }
392
393         /**
394          * Adds hub data elements to a given dataset instance
395          *
396          * @param       $criteriaInstance       An instance of a storeable criteria
397          * @param       $requestInstance        An instance of a Requestable class
398          * @return      void
399          */
400         public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance) {
401                 // Add node number and type
402                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR, 1);
403                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_TYPE, $requestInstance->getRequestElement('mode'));
404
405                 // Add the node id
406                 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
407
408                 // Add the session id if acquired
409                 if ($this->getSessionId() != '') {
410                         $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
411                 } // END - if
412
413                 // Add the private key if acquired
414                 if ($this->getPrivateKey() != '') {
415                         $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY, base64_encode($this->getPrivateKey()));
416                         $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH, $this->getPrivateKeyHash());
417                 } // END - if
418         }
419
420         /**
421          * Updates a given field with new value
422          *
423          * @param       $fieldName              Field to update
424          * @param       $fieldValue             New value to store
425          * @return      void
426          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
427          * @todo        Try to make this method more generic so we can move it in BaseFrameworkSystem
428          */
429         public function updateDatabaseField ($fieldName, $fieldValue) {
430                 // Unfinished
431                 $this->partialStub('Unfinished!');
432                 return;
433
434                 // Get a critieria instance
435                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
436
437                 // Add search criteria
438                 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
439                 $searchInstance->setLimit(1);
440
441                 // Now get another criteria
442                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
443
444                 // Add criteria entry which we shall update
445                 $updateInstance->addCriteria($fieldName, $fieldValue);
446
447                 // Add the search criteria for searching for the right entry
448                 $updateInstance->setSearchInstance($searchInstance);
449
450                 // Set wrapper class name
451                 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
452
453                 // Remember the update in database result
454                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
455         }
456
457         /**
458          * Announces this hub to the upper (bootstrap or list) hubs. After this is
459          * successfully done the given task is unregistered from the handler. This
460          * might look a bit overloaded here but the announcement phase isn't a
461          * simple "Hello there" message, it may later on also contain more
462          * informations like the object list.
463          *
464          * @param       $taskInstance   The task instance running this announcement
465          * @return      void
466          * @throws      NodeAlreadyAnnouncedException   If this hub is already announced
467          * @todo        Change the first if() block to check for a specific state
468          */
469         public function announceToUpperNodes (Taskable $taskInstance) {
470                 // Is this hub node announced?
471                 if ($this->hubIsAnnounced === true) {
472                         // Already announced!
473                         throw new NodeAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
474                 } // END - if
475
476                 // Debug output
477                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
478
479                 // Get a helper instance
480                 $helperInstance = ObjectFactory::createObjectByConfiguredName('node_announcement_helper_class');
481
482                 // Load the announcement descriptor
483                 $helperInstance->loadDescriptorXml($this);
484
485                 // Compile all variables
486                 $helperInstance->getTemplateInstance()->compileConfigInVariables();
487
488                 // "Publish" the descriptor by sending it to the bootstrap/list nodes
489                 $helperInstance->sendPackage($this);
490
491                 // Change the state, this should be the last line except debug output
492                 $this->getStateInstance()->nodeAnnouncedToUpperHubs();
493
494                 // Debug output
495                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-Announcement: FINISHED');
496         }
497
498         /**
499          * Does a self-connect attempt on the public IP address. This should make
500          * it sure, we are reachable from outside world. For this kind of package we
501          * don't need that overload we have in the announcement phase.
502          *
503          * @param       $taskInstance   The task instance running this announcement
504          * @return      void
505          */
506         public function doSelfConnection (Taskable $taskInstance) {
507                 // Debug output
508                 self::createDebugInstance(__CLASS__)->debugOutput('HUB: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
509
510                 // Get a helper instance
511                 $helperInstance = ObjectFactory::createObjectByConfiguredName('node_self_connect_helper_class', array($this));
512
513                 // Load the descriptor (XML) file
514                 $helperInstance->loadDescriptorXml($this);
515
516                 // Compile all variables
517                 $helperInstance->getTemplateInstance()->compileConfigInVariables();
518
519                 // And send the package away
520                 $helperInstance->sendPackage($this);
521
522                 // Debug output
523                 self::createDebugInstance(__CLASS__)->debugOutput('HUB: Self Connection: FINISHED');
524         }
525
526         /**
527          * Activates the hub by doing some final preparation and setting
528          * $hubIsActive to true
529          *
530          * @param       $requestInstance        A Requestable class
531          * @param       $responseInstance       A Responseable class
532          * @return      void
533          */
534         public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
535                 // Checks whether a listener is still active and shuts it down if one
536                 // is still listening.
537                 if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
538                         // Shutdown them down before they can hurt anything
539                         $this->shutdownListenerPool();
540                 } // END - if
541
542                 // Get the controller here
543                 $controllerInstance = Registry::getRegistry()->getInstance('controller');
544
545                 // Run all filters for the hub activation
546                 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
547
548                 // ----------------------- Last step from here ------------------------
549                 // Activate the hub. This is ALWAYS the last step in this method
550                 $this->getStateInstance()->nodeIsActivated();
551                 // ---------------------- Last step until here ------------------------
552         }
553
554         /**
555          * Initializes the listener pool (class)
556          *
557          * @return      void
558          */
559         public function initializeListenerPool () {
560                 // Debug output
561                 self::createDebugInstance(__CLASS__)->debugOutput('HUB: Initialize listener: START');
562
563                 // Get a new pool instance
564                 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
565
566                 // Get an instance of the low-level listener
567                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
568
569                 // Setup address and port
570                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
571
572                 /*
573                  * All nodes can now use the same configuration entry because it can be
574                  * customized in config-local.php.
575                  */
576                 $listenerInstance->setListenPortByConfiguration('node_listen_port');
577
578                 // Initialize the listener
579                 $listenerInstance->initListener();
580
581                 // Get a decorator class
582                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('node_tcp_listener_class', array($listenerInstance));
583
584                 // Add this listener to the pool
585                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
586
587                 // Get a decorator class
588                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
589
590                 // Add this listener to the pool
591                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
592
593                 // Get an instance of the low-level listener
594                 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
595
596                 // Setup address and port
597                 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
598
599                 /*
600                  * All nodes can now use the same configuration entry because it can be
601                  * customized in config-local.php.
602                  */
603                 $listenerInstance->setListenPortByConfiguration('node_listen_port');
604
605                 // Initialize the listener
606                 $listenerInstance->initListener();
607
608                 // Get a decorator class
609                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('node_udp_listener_class', array($listenerInstance));
610
611                 // Add this listener to the pool
612                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
613
614                 // Get a decorator class
615                 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
616
617                 // Add this listener to the pool
618                 $this->getListenerPoolInstance()->addListener($decoratorInstance);
619
620                 // Debug output
621                 self::createDebugInstance(__CLASS__)->debugOutput('HUB: Initialize listener: FINISHED.');
622         }
623
624         /**
625          * Getter for isActive attribute
626          *
627          * @return      $isActive       Whether the hub is active
628          */
629         public final function isNodeActive () {
630                 return $this->isActive;
631         }
632
633         /**
634          * Enables (default) or disables isActive flag
635          *
636          * @param       $isActive       Whether the hub is active
637          * @return      void
638          */
639         public final function enableIsActive ($isActive = true) {
640                 $this->isActive = (bool) $isActive;
641         }
642
643         /**
644          * Checks whether this node accepts announcements
645          *
646          * @return      $acceptAnnouncements    Whether this node accepts announcements
647          */
648         public final function isAcceptingAnnouncements () {
649                 // Check it (this node must be active and not shutdown!)
650                 $acceptAnnouncements = (($this->acceptAnnouncements === true) && ($this->isNodeActive()));
651
652                 // Return it
653                 return $acceptAnnouncements;
654         }
655
656         /**
657          * Checks whether this node has attempted to announce itself
658          *
659          * @return      $hasAnnounced   Whether this node has attempted to announce itself
660          * @todo        Add checking if this node has been announced to the sender node
661          */
662         public function ifNodeHasAnnounced () {
663                 // Debug message
664                 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE: ifNodeHasAnnounced(): state=' . $this->getStateInstance()->getStateName());
665
666                 // Simply check the state of this node
667                 $hasAnnounced = ($this->getStateInstance() instanceof NodeAnnouncedState);
668
669                 // Debug message
670                 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE: ifNodeHasAnnounced(): hasAnnounced=' . intval($hasAnnounced));
671
672                 // Return it
673                 return $hasAnnounced;
674         }
675
676         /**
677          * Checks whether this node has attempted to announce itself and completed it
678          *
679          * @return      $hasAnnouncementCompleted       Whether this node has attempted to announce itself and completed it
680          * @todo        Add checking if this node has been announced to the sender node
681          */
682         public function ifNodeHasAnnouncementCompleted () {
683                 // Debug message
684                 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE: ifNodeHasAnnouncementCompleted(): state=' . $this->getStateInstance()->getStateName());
685
686                 // Simply check the state of this node
687                 $hasAnnouncementCompleted = ($this->getStateInstance() instanceof NodeAnnouncementCompletedState);
688
689                 // Debug message
690                 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE: ifNodeHasAnnouncementCompleted(): hasAnnouncementCompleted=' . intval($hasAnnouncementCompleted));
691
692                 // Return it
693                 return $hasAnnouncementCompleted;
694         }
695
696         /**
697          * Enables whether this node accepts announcements
698          *
699          * @param       $acceptAnnouncements    Whether this node accepts announcements (default: true)
700          * @return      void
701          */
702         protected final function enableAcceptingAnnouncements ($acceptAnnouncements = true) {
703                 $this->acceptAnnouncements = $acceptAnnouncements;
704         }
705
706         /**
707          * Checks wether this node is accepting node-list requests
708          *
709          * @return      $acceptsRequest         Wether this node accepts node-list requests
710          */
711         public function isAcceptingNodeListRequests () {
712                 /*
713                  * Only 'regular' nodes does not accept such requests, checking
714                  * HubRegularNode is faster, but if e.g. HubRegularI2PNode will be
715                  * added then the next check will be true.
716                  */
717                 $acceptsRequest = ((!$this instanceof HubRegularNode) && ($this->getRequestInstance()->getRequestElement('mode') != self::NODE_TYPE_REGULAR));
718
719                 // Return it
720                 return $acceptsRequest;
721         }
722
723         /**
724          * "Getter" for address:port combination
725          *
726          * @return      $addressPort    A address:port combination for this node
727          */
728         public final function getAddressPort () {
729                 // Get IP and port
730                 $addressPort = $this->getConfigInstance()->detectServerAddress() . ':' . $this->getConfigInstance()->getConfigEntry('node_listen_port');
731
732                 // Return it
733                 return $addressPort;
734         }
735
736         /**
737          * Updates/refreshes node data (e.g. status).
738          *
739          * @return      void
740          * @todo        Find more to do here
741          */
742         public function updateNodeData () {
743                 // Set some dummy configuration entries, e.g. node_status
744                 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
745         }
746
747         /**
748          * Handles message answer by given data array
749          *
750          * @param       $messageData            A valid answer message data array
751          * @param       $packageInstance        An instance of a Receivable class
752          * @return      void
753          * @todo        Handle thrown exception
754          */
755         public function handleAnswerStatusByMessageData (array $messageData, Receivable $packageInstance) {
756                 // Is it not empty?
757                 assert(!empty($messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]));
758
759                 // Construct configuration entry for handling class' name
760                 $classConfigEntry = strtolower($messageData[NetworkPackage::MESSAGE_ARRAY_TYPE] . '_status_' . $messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]) . '_handler_class';
761
762                 // Try to get a class
763                 $handlerInstance = ObjectFactory::createObjectByConfiguredName($classConfigEntry);
764
765                 // Handle it there
766                 $handlerInstance->handleAnswerMessageData($messageData, $packageInstance);
767         }
768
769         /**
770          * "Getter" for an array of all accepted object types
771          *
772          * @return      $objectList             Array of all accepted object types
773          */
774         public function getListFromAcceptedObjectTypes () {
775                 // Get registry instance
776                 $objectRegistryInstance = ObjectTypeRegistryFactory::createObjectTypeRegistryInstance();
777
778                 // Get all entries
779                 $objectList = $objectRegistryInstance->getEntries(XmlObjectRegistryTemplateEngine::OBJECT_TYPE_DATA_NAME);
780
781                 // ... and return it
782                 return $objectList;
783         }
784 }
785
786 // [EOF]
787 ?>