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