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