]> git.mxchange.org Git - hub.git/blob - application/hub/main/database/wrapper/states/class_PeerStateLookupDatabaseWrapper.php
450609e1ed24a29f6350a5eacb175024669e662c
[hub.git] / application / hub / main / database / wrapper / states / class_PeerStateLookupDatabaseWrapper.php
1 <?php
2 /**
3  * A database wrapper for peer state lookups
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 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 PeerStateLookupDatabaseWrapper extends BaseDatabaseWrapper implements LookupablePeerState {
25         // Exception constants
26         const EXCEPTION_PEER_ALREADY_REGISTERED = 0x300;
27
28         // Constants for database table names
29         const DB_TABLE_PEER_LOOKUP = 'peer_states';
30
31         // Constants for database column names
32         const DB_COLUMN_PEER_IP           = 'peer_ip';
33         const DB_COLUMN_PEER_PORT         = 'peer_port';
34         const DB_COLUMN_PEER_SESSION_ID   = 'peer_session_id';
35         const DB_COLUMN_SOCKET_ERROR_CODE = 'socket_error_code';
36         const DB_COLUMN_SOCKET_ERROR_MSG  = 'socket_error_msg';
37
38         /**
39          * Protected constructor
40          *
41          * @return      void
42          */
43         protected function __construct () {
44                 // Call parent constructor
45                 parent::__construct(__CLASS__);
46         }
47
48         /**
49          * Creates an instance of this database wrapper by a provided user class
50          *
51          * @return      $wrapperInstance        An instance of the created wrapper class
52          */
53         public static final function createPeerStateLookupDatabaseWrapper () {
54                 // Get a new instance
55                 $wrapperInstance = new PeerStateLookupDatabaseWrapper();
56
57                 // Set (primary!) table name
58                 $wrapperInstance->setTableName(self::DB_TABLE_PEER_LOOKUP);
59
60                 // Return the instance
61                 return $wrapperInstance;
62         }
63
64         /**
65          * Getter for index key
66          *
67          * @return      $indexKey       Index key
68          */
69         public final function getIndexKey () {
70                 return $this->getDatabaseInstance()->getIndexKey();
71         }
72
73         /**
74          * Checks wether given 'sender' is a new peer
75          *
76          * @param       $packageData    Raw package data
77          * @return      $isNewPeer              Wether 'sender' is a new peer to this peer
78          */
79         public function isSenderNewPeer (array $packageData) {
80                 //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: ' . __FUNCTION__ . ' called with packageData()=' . count($packageData) . ' - ENTERED!');
81                 // Is always new peer by default
82                 $isNewPeer = true;
83
84                 // Is the package valid?
85                 if (!isset($packageData[NetworkPackage::PACKAGE_DATA_SENDER])) {
86                         // Invalid package found, please report this
87                         die(__METHOD__ . ': packageData=' . print_r($packageData, true));
88                 } // END - if
89
90                 // Resolve session id > IP:port
91                 //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: sender=' . $packageData[NetworkPackage::PACKAGE_DATA_SENDER] . ' - resolving ...');
92                 $ipPort = HubTools::resolveSessionId($packageData[NetworkPackage::PACKAGE_DATA_SENDER]);
93                 //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: ipPort=' . $ipPort);
94
95                 // Is it not invalid:invalid?
96                 if ($ipPort != NodeListDatabaseWrapper::INVALID_IP_PORT) {
97                         // Get a search criteria instance
98                         $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
99
100                         // Add 'sender' as the peer's IP address
101                         $searchInstance->addCriteria(self::DB_COLUMN_PEER_IP, $ipPort);
102                         $searchInstance->setLimit(1);
103
104                         // Count the query
105                         $entries = $this->doSelectCountByCriteria($searchInstance);
106
107                         // Is it there?
108                         //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: entries=' . $entries);
109                         $isNewPeer = ($entries === 0);
110                 } // END - if
111
112                 // Return the result
113                 //* DEBUG: */ $this->debugOutput('DATABASE-WRAPPER: isNewPeer=' . intval($isNewPeer) . ' - EXIT!');
114                 return $isNewPeer;
115         }
116
117         /**
118          * Registers a new peer with given package data. We use the session id from it.
119          *
120          * @param       $packageData            Raw package data
121          * @param       $socketResource         A valid socket resource
122          * @return      void
123          * @throws      PeerAlreadyRegisteredException  If a peer is already registered
124          */
125         public function registerPeerByPackageData (array $packageData, $socketResource) {
126                 // Make sure only new peers can be registered with package data
127                 if (!$this->isSenderNewPeer($packageData)) {
128                         // Throw an exception because this should normally not happen
129                         throw new PeerAlreadyRegisteredException(array($this, $packageData), self::EXCEPTION_PEER_ALREADY_REGISTERED);
130                 } // END - if
131
132                 // Generate a dataset instance
133                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_PEER_LOOKUP));
134
135                 // Session ids must be unique
136                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_PEER_SESSION_ID);
137
138                 // Add session id
139                 $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_SESSION_ID, $packageData[NetworkPackage::PACKAGE_DATA_SENDER]);
140
141                 // Get peer name
142                 if (!@socket_getpeername($socketResource, $peerName, $peerPort)) {
143                         // Get last error
144                         $lastError = socket_last_error($socketResource);
145
146                         // ... and cleartext message from it and put both into criteria
147                         $dataSetInstance->addCriteria(self::DB_COLUMN_SOCKET_ERROR_CODE, $lastError);
148                         $dataSetInstance->addCriteria(self::DB_COLUMN_SOCKET_ERROR_MSG , socket_strerror($lastError));
149                 } // END - if
150
151                 // Add ip address and port
152                 $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_IP  , $peerName);
153                 $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_PORT, $peerPort);
154
155                 // "Insert" the data set
156                 $this->getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
157         }
158
159         /**
160          * Registers the given peer state and raw package data
161          *
162          * @param       $stateInstance  A PeerStateable class instance
163          * @param       $packageData    Valid package data array
164          * @return      void
165          * @todo        Unfinished area
166          */
167         public function registerPeerState (PeerStateable $stateInstance, array $packageData) {
168                 $this->debugBackTrace('stateInstance=' . $stateInstance->__toString() . ' - UNFINISHED AREA!');
169         }
170
171         /**
172          * Purges old entries of given socket resource. We use the IP address from that resource.
173          *
174          * @param       $socketResource         A valid socket resource
175          * @return      void
176          * @throws      InvalidSocketException  If the socket resource was invalid
177          */
178         public function purgeOldEntriesBySocketResource ($socketResource) {
179                 // Get peer name
180                 if (!@socket_getpeername($socketResource, $peerName, $peerPort)) {
181                         // Get last error
182                         $lastError = socket_last_error($socketResource);
183
184                         // Doesn't work!
185                         throw new InvalidSocketException(array($this, gettype($socketResource), $lastError, socket_strerror($lastError)), BaseListener::EXCEPTION_INVALID_SOCKET);
186                 } // END - if
187         }
188 }
189
190 // [EOF]
191 ?>