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