]> git.mxchange.org Git - hub.git/blob - application/hub/main/database/wrapper/class_PeerStateLookupDatabaseWrapper.php
03fe0217e65429cd3a1a1ccd964f5de84a07e415
[hub.git] / application / hub / main / database / wrapper / 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, 2010 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 {
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
36         /**
37          * Protected constructor
38          *
39          * @return      void
40          */
41         protected function __construct () {
42                 // Call parent constructor
43                 parent::__construct(__CLASS__);
44         }
45
46         /**
47          * Creates an instance of this database wrapper by a provided user class
48          *
49          * @return      $wrapperInstance        An instance of the created wrapper class
50          */
51         public final static function createPeerStateLookupDatabaseWrapper () {
52                 // Get a new instance
53                 $wrapperInstance = new PeerStateLookupDatabaseWrapper();
54
55                 // Set (primary!) table name
56                 $wrapperInstance->setTableName(self::DB_TABLE_PEER_LOOKUP);
57
58                 // Return the instance
59                 return $wrapperInstance;
60         }
61
62         /**
63          * Getter for index key
64          *
65          * @return      $indexKey       Index key
66          */
67         public final function getIndexKey () {
68                 return $this->getDatabaseInstance()->getIndexKey();
69         }
70
71         /**
72          * Checks wether given 'sender' is a new peer
73          *
74          * @param       $packageData    Raw package data
75          * @return      $isNewPeer              Wether 'sender' is a new peer to this node
76          */
77         public function isSenderNewPeer (array $packageData) {
78                 // Is always new peer by default
79                 $isNewPeer = true;
80
81                 // Is the package valid?
82                 if (!isset($packageData[NetworkPackage::INDEX_PACKAGE_SENDER])) {
83                         // Invalid package found, please report this
84                         die('packageData='.print_r($packageData, true));
85                 } // END - if
86
87                 // Remove session id > IP:port
88                 $ipPort = HubTools::resolveSessionId($packageData[NetworkPackage::INDEX_PACKAGE_SENDER]);
89
90                 // Is it not invalid:invalid?
91                 if ($ipPort != 'invalid:invalid') {
92                         // Get a search criteria instance
93                         $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
94
95                         // Add 'sender' as the peer's IP address
96                         $searchInstance->addCriteria(self::DB_COLUMN_PEER_IP, $ipPort);
97                         $searchInstance->setLimit(1);
98
99                         // Count the query
100                         $entries = $this->doSelectCountByCriteria($searchInstance);
101
102                         // Is it there?
103                         $isNewPeer = ($entries === 0);
104                 } // END - if
105
106                 // Return the result
107                 return $isNewPeer;
108         }
109
110         /**
111          * Registers a new peer with given package data. We use the session id from it.
112          *
113          * @param       $packageData            Raw package data
114          * @param       $socketResource         A valid socket resource
115          * @return      void
116          * @throws      PeerAlreadyRegisteredException  If a peer is already registered
117          * @throws      InvalidSocketException  If the socket resource was invalid
118          */
119         public function registerPeerByPackageData (array $packageData, $socketResource) {
120                 // Make sure only new peers can be registered with package data
121                 if (!$this->isSenderNewPeer($packageData)) {
122                         // Throw an exception because this should normally not happen
123                         throw new PeerAlreadyRegisteredException(array($this, $packageData), self::EXCEPTION_PEER_ALREADY_REGISTERED);
124                 } // END - if
125
126                 // Generate a dataset instance
127                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_PEER_LOOKUP));
128
129                 // Session ids must be unique
130                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_PEER_SESSION_ID);
131
132                 // Add session id
133                 $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_SESSION_ID, $packageData[NetworkPackage::INDEX_PACKAGE_SENDER]);
134
135                 // Get peer name
136                 if (!socket_getpeername($socketResource, $peerName, $peerPort)) {
137                         // Get last error
138                         $lastError = socket_last_error($socketResource);
139
140                         // Doesn't work!
141                         throw new InvalidSocketException(array($this, gettype($socketResource), $lastError, socket_strerror($lastError)), BaseListener::EXCEPTION_INVALID_SOCKET);
142                 } // END - if
143
144                 // Add ip address and port
145                 $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_IP  , $peerName);
146                 $dataSetInstance->addCriteria(self::DB_COLUMN_PEER_PORT, $peerPort);
147
148                 // "Insert" the data set
149                 $this->getDatabaseInstance()->queryInsertDataSet($dataSetInstance);
150         }
151
152         /**
153          * Purges old entries of given socket resource. We use the IP address from that resource.
154          *
155          * @param       $socketResource         A valid socket resource
156          * @return      void
157          * @throws      InvalidSocketException  If the socket resource was invalid
158          */
159         public function purgeOldEntriesBySocketResource ($socketResource) {
160                 // Get peer name
161                 if (!socket_getpeername($socketResource, $peerName, $peerPort)) {
162                         // Get last error
163                         $lastError = socket_last_error($socketResource);
164
165                         // Doesn't work!
166                         throw new InvalidSocketException(array($this, gettype($socketResource), $lastError, socket_strerror($lastError)), BaseListener::EXCEPTION_INVALID_SOCKET);
167                 } // END - if
168         }
169 }
170
171 // [EOF]
172 ?>