3 * A general hub node class
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Hub Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.org
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.
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.
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/>.
24 class BaseHubNode extends BaseHubSystem implements Updateable, AddableCriteria {
28 const NODE_TYPE_BOOT = 'boot';
29 const NODE_TYPE_MASTER = 'master';
30 const NODE_TYPE_LIST = 'list';
31 const NODE_TYPE_REGULAR = 'regular';
33 // Exception constants
34 const EXCEPTION_HUB_ALREADY_ANNOUNCED = 0xe00;
37 const OBJECT_LIST_SEPARATOR = ',';
40 * Universal node locator of bootstrap node
42 private $bootUnl = '';
45 * Whether this node is anncounced (keep on FALSE!)
48 private $hubIsAnnounced = FALSE;
51 * Whether this hub is active (default: FALSE)
53 private $isActive = FALSE;
56 * Whether this node accepts announcements (default: FALSE)
58 private $acceptAnnouncements = FALSE;
61 * Whether this node accepts DHT bootstrap requests (default: FALSE)
63 private $acceptDhtBootstrap = FALSE;
66 * Protected constructor
68 * @param $className Name of the class
71 protected function __construct ($className) {
72 // Call parent constructor
73 parent::__construct($className);
75 // Get a wrapper instance
76 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_info_db_wrapper_class');
79 $this->setWrapperInstance($wrapperInstance);
81 // Get a crypto instance
82 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
85 $this->setCryptoInstance($cryptoInstance);
87 // Set the node instance in registry
88 Registry::getRegistry()->addInstance('node', $this);
90 // Init state which sets the state to 'init'
95 * Initializes the node's state which sets it to 'init'
99 private function initState() {
100 // Get the state factory and create the initial state.
101 NodeStateFactory::createNodeStateInstanceByName('init');
105 * Generates a private key and hashes it (for speeding up things)
107 * @param $searchInstance An instance of a LocalSearchCriteria class
110 private function generatePrivateKeyAndHash (LocalSearchCriteria $searchInstance) {
111 // Get an RNG instance
112 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
114 // Generate a pseudo-random string
115 $randomString = $rngInstance->randomString(255);
117 // Hash and encrypt the string so we become a node id (also documented as "hub id")
118 $this->setPrivateKey($this->getCryptoInstance()->encryptString($randomString));
119 $this->setPrivateKeyHash($this->getCryptoInstance()->hashString($this->getPrivateKey()));
121 // Register the node id with our wrapper
122 $this->getWrapperInstance()->registerPrivateKey($this, $this->getRequestInstance(), $searchInstance);
125 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new private key with hash: ' . $this->getPrivateKeyHash() . '');
129 * Generates a random string from various data inluding UUID if PECL
130 * extension uuid is installed.
132 * @param $length Length of the random part
133 * @return $randomString Random string
134 * @todo Make this code more generic and move it to CryptoHelper or
136 protected function generateRamdomString ($length) {
137 // Get an RNG instance
138 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
140 // Generate a pseudo-random string
141 $randomString = $rngInstance->randomString($length) . ':' . $this->getBootUniversalNodeLocator() . ':' . $this->getRequestInstance()->getRequestElement('mode');
143 // Add UUID for even more entropy for the hasher
144 $randomString .= $this->getCryptoInstance()->createUuid();
147 return $randomString;
151 * Getter for boot UNL (Universal Node Locator)
153 * @return $bootUnl The UNL (Universal Node Locator) of the boot node
155 protected final function getBootUniversalNodeLocator () {
156 return $this->bootUnl;
160 * Checks whether the given IP address matches one of the bootstrap nodes
162 * @param $remoteAddr IP address to checkout against our bootstrapping list
163 * @return $isFound Whether the IP is found
165 protected function ifAddressMatchesBootstrapNodes ($remoteAddr) {
166 // By default nothing is found
169 // Run through all configured IPs
170 foreach (explode(BaseHubSystem::BOOTSTRAP_NODES_SEPARATOR, $this->getConfigInstance()->getConfigEntry('hub_bootstrap_nodes')) as $unl) {
172 if ($unl == $remoteAddr) {
177 $this->bootUnl = $unl;
180 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __METHOD__ . ':' . __LINE__ . ']: UNL matches remote address ' . $unl . '.');
182 // Stop further searching
184 } elseif ($unl == $this->getConfigInstance()->getConfigEntry('node_listen_addr')) {
186 * IP matches listen address. At this point we really don't care
187 * if we can really listen on that address
191 // Remember the port number
192 $this->bootUnl = $unl;
195 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: ' . __FUNCTION__ . '[' . __METHOD__ . ':' . __LINE__ . ']: UNL matches listen address ' . $unl . '.');
197 // Stop further searching
207 * Tries to detect own UNL (Universal Node Locator)
209 * @return $unl Node's own universal node locator
211 public function detectOwnUniversalNodeLocator () {
213 if (!isset($GLOBALS[__METHOD__])) {
214 // Get the UNL array back
215 $unlData = $this->getUniversalNodeLocatorArray();
217 // There are 2 UNLs, internal and external.
218 if ($this->getConfigInstance()->getConfigEntry('allow_publish_internal_address') == 'N') {
219 // Public "external" UNL address
220 $GLOBALS[__METHOD__] = $unlData[NodeInformationDatabaseWrapper::DB_COLUMN_EXTERNAL_UNL];
222 // Non-public "internal" UNL address
223 $GLOBALS[__METHOD__] = $unlData[NodeInformationDatabaseWrapper::DB_COLUMN_INTERNAL_UNL];
228 return $GLOBALS[__METHOD__];
232 * Outputs the console teaser. This should only be executed on startup or
233 * full restarts. This method generates some space around the teaser.
237 public function outputConsoleTeaser () {
238 // Get the app instance (for shortening our code)
239 $app = $this->getApplicationInstance();
242 self::createDebugInstance(__CLASS__)->debugOutput(' ');
243 self::createDebugInstance(__CLASS__)->debugOutput($app->getAppName() . ' v' . $app->getAppVersion() . ' - ' . $this->getRequestInstance()->getRequestElement('mode') . ' mode active');
244 self::createDebugInstance(__CLASS__)->debugOutput('Copyright (c) 2007 - 2008 Roland Haeder, 2009 - 2015 Hub Developer Team');
245 self::createDebugInstance(__CLASS__)->debugOutput(' ');
246 self::createDebugInstance(__CLASS__)->debugOutput('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
247 self::createDebugInstance(__CLASS__)->debugOutput('This is free software, and you are welcome to redistribute it under certain');
248 self::createDebugInstance(__CLASS__)->debugOutput('conditions; see docs/COPYING for details.');
249 self::createDebugInstance(__CLASS__)->debugOutput(' ');
253 * Generic method to acquire a hub-id. On first run this generates a new one
254 * based on many pseudo-random data. On any later run, unless the id
255 * got not removed from database, it will be restored from the database.
257 * @param $requestInstance A Requestable class
258 * @param $responseInstance A Responseable class
261 public function bootstrapAcquireNodeId (Requestable $requestInstance, Responseable $responseInstance) {
262 // Is there a node id?
263 if ($this->getWrapperInstance()->ifNodeDataIsFound($this)) {
264 // Get the node id from result and set it
265 $this->setNodeId($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID));
268 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Re-using found node-id: ' . $this->getNodeId() . '');
270 // Get an RNG instance
271 $rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
273 // Generate a pseudo-random string
274 $randomString = $rngInstance->randomString(255);
276 // Hash and encrypt the string so we become a node id (also documented as "hub id")
277 $this->setNodeId($this->getCryptoInstance()->hashString($this->getCryptoInstance()->encryptString($randomString)));
279 // Register the node id with our wrapper
280 $this->getWrapperInstance()->registerNodeId($this, $this->getRequestInstance());
283 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new node-id: ' . $this->getNodeId() . '');
288 * Generates a session id which will be sent to the other hubs and peers
292 public function bootstrapGenerateSessionId () {
293 // Now get a search criteria instance
294 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
296 // Search for the node number one which is hard-coded the default
297 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR , 1);
298 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_MODE, $this->getRequestInstance()->getRequestElement('mode'));
299 $searchInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID , $this->getNodeId());
300 $searchInstance->setLimit(1);
302 // Remember it for later usage
303 $this->setSearchInstance($searchInstance);
305 // Get a random string
306 $randomString = $this->generateRamdomString(255);
308 // Hash and encrypt the string so we become a "node id" aka Hub-Id
309 $this->setSessionId($this->getCryptoInstance()->hashString($this->getCryptoInstance()->encryptString($randomString)));
311 // Register the node id with our wrapper
312 $this->getWrapperInstance()->registerSessionId($this, $this->getRequestInstance(), $searchInstance);
315 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Created new session-id: ' . $this->getSessionId() . '');
317 // Change the state because the node has aquired a session id
318 $this->getStateInstance()->nodeGeneratedSessionId();
322 * Generate a private key for en-/decryption
326 public function bootstrapGeneratePrivateKey () {
328 if ($this->getWrapperInstance()->ifNodeDataIsFound($this)) {
329 // Is the element set?
330 if (is_null($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY))) {
332 * Auto-generate the private key for e.g. out-dated database
333 * "tables". This allows a smooth update for the underlaying
336 $this->generatePrivateKeyAndHash($this->getSearchInstance());
338 // Get the node id from result and set it
339 $this->setPrivateKey(base64_decode($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY)));
340 $this->setPrivateKeyHash($this->getField(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH));
343 self::createDebugInstance(__CLASS__)->debugOutput('BOOTSTRAP: Re-using found private key hash: ' . $this->getPrivateKeyHash() . '');
347 * Generate it in a private method (no confusion with 'private
348 * method access' and 'private key' here! ;-)).
350 $this->generatePrivateKeyAndHash($this->getSearchInstance());
355 * Adds hub data elements to a given dataset instance
357 * @param $criteriaInstance An instance of a storeable criteria
358 * @param $requestInstance An instance of a Requestable class
361 public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance = NULL) {
362 // Make sure the request instance is set as it is not optional.
363 assert($requestInstance instanceof Requestable);
365 // Add node number and type
366 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_NR , 1);
367 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_MODE, $requestInstance->getRequestElement('mode'));
370 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_NODE_ID, $this->getNodeId());
372 // Add the session id if acquired
373 if ($this->getSessionId() != '') {
374 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_SESSION_ID, $this->getSessionId());
377 // Add the private key if acquired
378 if ($this->getPrivateKey() != '') {
379 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY, base64_encode($this->getPrivateKey()));
380 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH, $this->getPrivateKeyHash());
383 // Add own external and internal addresses as UNLs
384 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_INTERNAL_UNL, HubTools::determineOwnInternalAddress());
385 $criteriaInstance->addCriteria(NodeInformationDatabaseWrapper::DB_COLUMN_EXTERNAL_UNL, HubTools::determineOwnExternalAddress());
389 * Updates a given field with new value
391 * @param $fieldName Field to update
392 * @param $fieldValue New value to store
394 * @throws DatabaseUpdateSupportException If this class does not support database updates
395 * @todo Try to make this method more generic so we can move it in BaseFrameworkSystem
397 public function updateDatabaseField ($fieldName, $fieldValue) {
399 $this->partialStub('Unfinished!');
402 // Get a critieria instance
403 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
405 // Add search criteria
406 $searchInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_USERNAME, $this->getUserName());
407 $searchInstance->setLimit(1);
409 // Now get another criteria
410 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
412 // Add criteria entry which we shall update
413 $updateInstance->addCriteria($fieldName, $fieldValue);
415 // Add the search criteria for searching for the right entry
416 $updateInstance->setSearchInstance($searchInstance);
418 // Set wrapper class name
419 $updateInstance->setWrapperConfigEntry('user_db_wrapper_class');
421 // Remember the update in database result
422 $this->getResultInstance()->add2UpdateQueue($updateInstance);
426 * Announces this hub to the upper (bootstrap or list) hubs. After this is
427 * successfully done the given task is unregistered from the handler. This
428 * might look a bit overloaded here but the announcement phase isn't a
429 * simple "Hello there" message, it may later on also contain more
430 * informations like the object list.
432 * @param $taskInstance The task instance running this announcement
434 * @throws NodeAlreadyAnnouncedException If this hub is already announced
435 * @todo Change the first if() block to check for a specific state
437 public function announceToUpperNodes (Taskable $taskInstance) {
438 // Is this hub node announced?
439 if ($this->hubIsAnnounced === TRUE) {
440 // Already announced!
441 throw new NodeAlreadyAnnouncedException($this, self::EXCEPTION_HUB_ALREADY_ANNOUNCED);
445 self::createDebugInstance(__CLASS__)->debugOutput('HUB-Announcement: START (taskInstance=' . $taskInstance->__toString(). ')');
447 // Get a helper instance
448 $helperInstance = ObjectFactory::createObjectByConfiguredName('node_announcement_helper_class');
450 // Load the announcement descriptor
451 $helperInstance->loadDescriptorXml($this);
453 // Compile all variables
454 $helperInstance->getTemplateInstance()->compileConfigInVariables();
456 // "Publish" the descriptor by sending it to the bootstrap/list nodes
457 $helperInstance->sendPackage($this);
459 // Change the state, this should be the last line except debug output
460 $this->getStateInstance()->nodeAnnouncingToUpperHubs();
463 self::createDebugInstance(__CLASS__)->debugOutput('HUB-Announcement: FINISHED');
467 * Does a self-connect attempt on the public IP address. This should make
468 * it sure, we are reachable from outside world. For this kind of package we
469 * don't need that overload we have in the announcement phase.
471 * @param $taskInstance The task instance running this announcement
474 public function doSelfConnection (Taskable $taskInstance) {
476 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Self Connection: START (taskInstance=' . $taskInstance->__toString(). ')');
478 // Get a helper instance
479 $helperInstance = ObjectFactory::createObjectByConfiguredName('node_self_connect_helper_class', array($this));
481 // Load the descriptor (XML) file
482 $helperInstance->loadDescriptorXml($this);
484 // Compile all variables
485 $helperInstance->getTemplateInstance()->compileConfigInVariables();
487 // And send the package away
488 $helperInstance->sendPackage($this);
491 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Self Connection: FINISHED');
495 * Activates the hub by doing some final preparation and setting
496 * $hubIsActive to TRUE.
498 * @param $requestInstance A Requestable class
499 * @param $responseInstance A Responseable class
502 public function activateNode (Requestable $requestInstance, Responseable $responseInstance) {
503 // Checks whether a listener is still active and shuts it down if one
504 // is still listening.
505 if (($this->determineIfListenerIsActive()) && ($this->isNodeActive())) {
506 // Shutdown them down before they can hurt anything
507 $this->shutdownListenerPool();
510 // Get the controller here
511 $controllerInstance = Registry::getRegistry()->getInstance('controller');
513 // Run all filters for the hub activation
514 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
516 // ----------------------- Last step from here ------------------------
517 // Activate the hub. This is ALWAYS the last step in this method
518 $this->getStateInstance()->nodeIsActivated();
519 // ---------------------- Last step until here ------------------------
523 * Initializes the listener pool (class)
527 public function initializeListenerPool () {
529 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Initialize listener: START');
531 // Get a new pool instance
532 $this->setListenerPoolInstance(ObjectFactory::createObjectByConfiguredName('listener_pool_class', array($this)));
534 // Get an instance of the low-level listener
535 $listenerInstance = ObjectFactory::createObjectByConfiguredName('tcp_listener_class', array($this));
537 // Setup address and port
538 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
541 * All nodes can now use the same configuration entry because it can be
542 * customized in config-local.php.
544 $listenerInstance->setListenPortByConfiguration('node_listen_port');
546 // Initialize the listener
547 $listenerInstance->initListener();
549 // Get a decorator class
550 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('node_tcp_listener_class', array($listenerInstance));
552 // Add this listener to the pool
553 $this->getListenerPoolInstance()->addListener($decoratorInstance);
555 // Get a decorator class
556 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_tcp_listener_class', array($listenerInstance));
558 // Add this listener to the pool
559 $this->getListenerPoolInstance()->addListener($decoratorInstance);
561 // Get an instance of the low-level listener
562 $listenerInstance = ObjectFactory::createObjectByConfiguredName('udp_listener_class', array($this));
564 // Setup address and port
565 $listenerInstance->setListenAddressByConfiguration('node_listen_addr');
568 * All nodes can now use the same configuration entry because it can be
569 * customized in config-local.php.
571 $listenerInstance->setListenPortByConfiguration('node_listen_port');
573 // Initialize the listener
574 $listenerInstance->initListener();
576 // Get a decorator class
577 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('node_udp_listener_class', array($listenerInstance));
579 // Add this listener to the pool
580 $this->getListenerPoolInstance()->addListener($decoratorInstance);
582 // Get a decorator class
583 $decoratorInstance = ObjectFactory::createObjectByConfiguredName('client_udp_listener_class', array($listenerInstance));
585 // Add this listener to the pool
586 $this->getListenerPoolInstance()->addListener($decoratorInstance);
589 self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Initialize listener: FINISHED.');
593 * Getter for isActive attribute
595 * @return $isActive Whether the hub is active
597 public final function isNodeActive () {
598 return $this->isActive;
602 * Enables (default) or disables isActive flag
604 * @param $isActive Whether the hub is active
607 public final function enableIsActive ($isActive = TRUE) {
608 $this->isActive = (bool) $isActive;
612 * Checks whether this node accepts announcements
614 * @return $acceptAnnouncements Whether this node accepts announcements
616 public final function isAcceptingAnnouncements () {
617 // Check it (this node must be active and not shutdown!)
618 $acceptAnnouncements = (($this->acceptAnnouncements === TRUE) && ($this->isNodeActive()));
621 return $acceptAnnouncements;
625 * Checks whether this node accepts DHT bootstrap requests
627 * @return $acceptDhtBootstrap Whether this node accepts DHT bootstrap requests
629 public final function isAcceptingDhtBootstrap () {
630 // Check it (this node must be active and not shutdown!)
631 $acceptDhtBootstrap = (($this->acceptDhtBootstrap === TRUE) && ($this->isNodeActive()));
634 return $acceptDhtBootstrap;
638 * Checks whether this node has attempted to announce itself
640 * @return $hasAnnounced Whether this node has attempted to announce itself
641 * @todo Add checking if this node has been announced to the sender node
643 public function ifNodeIsAnnouncing () {
645 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeIsAnnouncing(): state=' . $this->getStateInstance()->getStateName());
647 // Simply check the state of this node
648 $hasAnnounced = ($this->getStateInstance() instanceof NodeAnnouncingState);
651 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeIsAnnouncing(): hasAnnounced=' . intval($hasAnnounced));
654 return $hasAnnounced;
658 * Checks whether this node has attempted to announce itself and completed it
660 * @return $hasAnnouncementCompleted Whether this node has attempted to announce itself and completed it
661 * @todo Add checking if this node has been announced to the sender node
663 public function ifNodeHasAnnouncementCompleted () {
665 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeHasAnnouncementCompleted(): state=' . $this->getStateInstance()->getStateName());
667 // Simply check the state of this node
668 $hasAnnouncementCompleted = ($this->getStateInstance() instanceof NodeAnnouncementCompletedState);
671 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: ifNodeHasAnnouncementCompleted(): hasAnnouncementCompleted=' . intval($hasAnnouncementCompleted));
674 return $hasAnnouncementCompleted;
678 * Enables whether this node accepts announcements
680 * @param $acceptAnnouncements Whether this node accepts announcements (default: TRUE)
683 protected final function enableAcceptingAnnouncements ($acceptAnnouncements = TRUE) {
684 $this->acceptAnnouncements = $acceptAnnouncements;
688 * Enables whether this node accepts DHT bootstrap requests
690 * @param $acceptDhtBootstrap Whether this node accepts DHT bootstrap requests (default: TRUE)
693 public final function enableAcceptDhtBootstrap ($acceptDhtBootstrap = TRUE) {
694 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Enabling DHT bootstrap requests ...');
695 $this->acceptDhtBootstrap = $acceptDhtBootstrap;
699 * Checks wether this node is accepting node-list requests
701 * @return $acceptsRequest Wether this node accepts node-list requests
703 public function isAcceptingNodeListRequests () {
705 * Only 'regular' nodes does not accept such requests, checking
706 * HubRegularNode is faster, but if e.g. HubRegularI2PNode will be
707 * added then the next check will be TRUE.
709 $acceptsRequest = ((!$this instanceof HubRegularNode) && ($this->getRequestInstance()->getRequestElement('mode') != self::NODE_TYPE_REGULAR));
712 return $acceptsRequest;
716 * Determines an instance of a LocateableNode class
718 * @return $unlInstance An instance of a LocateableNode class for this node
720 public function determineUniversalNodeLocator () {
722 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
724 // Determine UNL based on this node:
725 // 1) Get discovery class
726 $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
729 $unlInstance = $discoveryInstance->discoverUniversalNodeLocatorByNode($this);
732 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unlInstance= ' . $unlInstance->__toString() . ' - EXIT!');
737 * "Getter" for an array of an instance of a LocateableNode class
739 * @return $unlData An array from an instance of a LocateableNode class for this node
741 public final function getUniversalNodeLocatorArray () {
743 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
745 // Get the Universal Node Locator (UNL) instance
746 $unlInstance = $this->determineUniversalNodeLocator();
748 // Make sure the instance is valid
749 if (!$unlInstance instanceof LocateableNode) {
750 // No valid instance, so better debug this
751 $this->debugBackTrace('unlInstance[' . gettype($unlInstance) . ']=' . $unlInstance);
754 // ... and the array from it
755 $unlData = $unlInstance->getUnlData();
758 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: EXIT!');
763 * Updates/refreshes node data (e.g. status).
766 * @todo Find more to do here
768 public function updateNodeData () {
769 // Set some dummy configuration entries, e.g. node_status
770 $this->getConfigInstance()->setConfigEntry('node_status', $this->getStateInstance()->getStateName());
774 * Handles message answer by given data array
776 * @param $messageData A valid answer message data array
777 * @param $packageInstance An instance of a Receivable class
779 * @todo Handle thrown exception
781 public function handleAnswerStatusByMessageData (array $messageData, Receivable $packageInstance) {
783 assert(!empty($messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]));
785 // Construct configuration entry for handling class' name
786 $classConfigEntry = strtolower($messageData[NetworkPackage::MESSAGE_ARRAY_TYPE] . '_status_' . $messageData[BaseXmlAnswerTemplateEngine::ANSWER_STATUS]) . '_handler_class';
788 // Try to get a class
789 $handlerInstance = ObjectFactory::createObjectByConfiguredName($classConfigEntry);
792 $handlerInstance->handleAnswerMessageData($messageData, $packageInstance);
796 * "Getter" for an array of all accepted object types
798 * @return $objectList Array of all accepted object types
800 public function getListFromAcceptedObjectTypes () {
801 // Get registry instance
802 $objectRegistryInstance = ObjectTypeRegistryFactory::createObjectTypeRegistryInstance();
805 $objectList = $objectRegistryInstance->getEntries(XmlObjectRegistryTemplateEngine::OBJECT_TYPE_DATA_NAME);
812 * Adds all required elements from given array into data set instance
814 * @param $dataSetInstance An instance of a StoreableCriteria class
815 * @param $nodeData An array with valid node data
818 public function addArrayToDataSet (StoreableCriteria $dataSetInstance, array $nodeData) {
819 // Add all data the array provides
820 foreach (NodeDistributedHashTableDatabaseWrapper::getAllElements() as $element) {
821 // Is the element there?
822 if (isset($nodeData[$element])) {
824 $dataSetInstance->addCriteria($element, $nodeData[$element]);
826 // Output warning message
827 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: addArrayToDataSet(): Element ' . $element . ' not found in nodeData array.');