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