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