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