3 * A default peer pool class
5 * @author Roland Haeder <webmaster@shipsimu.org>
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
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 DefaultPeerPool extends BasePool implements PoolablePeer {
26 * Protected constructor
30 protected function __construct () {
31 // Call parent constructor
32 parent::__construct(__CLASS__);
36 * Creates an instance of this class
38 * @param $listenerInstance A Listenable instance
39 * @return $poolInstance An instance a Poolable class
41 public static final function createDefaultPeerPool (Listenable $listenerInstance) {
43 $poolInstance = new DefaultPeerPool();
45 // Set the application instance
46 $poolInstance->setListenerInstance($listenerInstance);
48 // Return the prepared instance
53 * Validates given socket
55 * @param $socketResource A valid socket resource
57 * @throws InvalidSocketException If the given socket has an error
59 private function validateSocket ($socketResource) {
60 // Is it a valid resource?
61 if (!is_resource($socketResource)) {
63 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
67 $errorCode = socket_last_error($socketResource);
69 // Is it without any errors?
71 // Handle the socket error with a faked recipientData array
72 $this->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
75 $errorMessage = socket_strerror($errorCode);
77 // Shutdown this socket
78 $this->getListenerInstance()->shutdownSocket($socketResource);
81 throw new InvalidSocketException(array($this, $socketResource, $errorCode, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
87 * Adds a socket resource to the peer pool
89 * @param $socketResource A valid (must be!) socket resource
90 * @param $connectionType Type of connection, can only be 'incoming', 'outgoing' or 'server'
92 * @throws InvalidSocketException If the given resource is invalid or errorous
93 * @throws InvalidConnectionTypeException If the provided connection type is not valid
95 public function addPeer ($socketResource, $connectionType) {
97 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('DEFAULT-PEER-POOL[' . __METHOD__ . ':' . __LINE__ . ']: socketResource[' . gettype($socketResource) . ']=' . $socketResource . ',connectionType=' . $connectionType . ' - ENTERED!');
99 // Validate the socket
100 $this->validateSocket($socketResource);
102 // Is the connection type valid?
103 if (!$this->isValidConnectionType($connectionType)) {
104 // Is not a valid connection type!
105 throw new InvalidConnectionTypeException(array($this, $connectionType), self::EXCEPTION_INVALID_CONNECTION_TYPE);
108 // Default is this peer's IP
109 $peerName = '0.0.0.0';
111 // The socket resource should not match server socket
112 if ($socketResource != $this->getListenerInstance()->getSocketResource()) {
113 // Try to determine the peer's IP number
114 if (!socket_getpeername($socketResource, $peerName)) {
115 // Handle the socket error with a faked recipientData array
116 $this->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
119 $lastError = socket_last_error($socketResource);
122 throw new InvalidSocketException(array($this, $socketResource, $lastError, socket_strerror($lastError)), BaseListener::EXCEPTION_INVALID_SOCKET);
126 // Server sockets won't work with socket_getpeername()
127 self::createDebugInstance(__CLASS__)->debugOutput('POOL[' . __METHOD__ . ':' . __LINE__ . ']: Socket resource is server socket (' . $socketResource . '). This is not a bug.');
131 self::createDebugInstance(__CLASS__)->debugOutput('POOL[' . __METHOD__ . ':' . __LINE__ . ']: Adding peer ' . $peerName . ',socketResource=' . $socketResource . ',type=' . $connectionType);
133 // Construct the array
134 $socketArray = array(
135 self::SOCKET_ARRAY_RESOURCE => $socketResource,
136 self::SOCKET_ARRAY_CONN_TYPE => $connectionType
139 // Add it finally to the pool
140 $this->addPoolEntry($socketArray);
144 * Getter for array of all socket resources
146 * @return $sockets An array with all sockets
148 public final function getAllSockets () {
150 $sockets = $this->getArrayFromList('pool');
157 * Getter for array of all socket arrays
159 * @return $sockets An array with all socket arrays
161 public final function getAllSingleSockets () {
162 // Get the array list
163 $socketArrays = $this->getArrayFromList('pool');
168 // "Walk" through all socket arrays
169 foreach ($socketArrays as $socketArray) {
171 array_push($sockets, $socketArray[self::SOCKET_ARRAY_RESOURCE]);
179 * "Getter" for all sockets of specified type
181 * @param $connectionType Type of connection, can only be 'incoming', 'outgoing' or 'server'
182 * @return $sockets An array with sockets of given type
183 * @throws InvalidConnectionTypeException If the provided connection type is not valid
185 public function getSocketsByConnectionType ($connectionType) {
186 // Is the connection type valid?
187 if (!$this->isValidConnectionType($connectionType)) {
188 // Is not a valid connection type!
189 throw new InvalidConnectionTypeException(array($this, $connectionType), self::EXCEPTION_INVALID_CONNECTION_TYPE);
192 // Get the array list
193 $socketArrays = $this->getArrayFromList('pool');
198 // "Walk" through all socket arrays
199 foreach ($socketArrays as $socketArray) {
201 if ($socketArray[self::SOCKET_ARRAY_CONN_TYPE] === $connectionType) {
203 array_push($sockets, $socketArray[self::SOCKET_ARRAY_RESOURCE]);
212 * "Getter" for a valid socket resource from given packae data.
214 * @param $packageData Raw package data
215 * @param $connectionType Type of connection, can be 'incoming', 'outgoing', 'server' or default
216 * @return $socketResource Socket resource
217 * @throws InvalidConnectionTypeException If the provided connection type is not valid
219 public function getSocketFromPackageData (array $packageData, $connectionType = NULL) {
220 // Default is no socket
221 $socketResource = FALSE;
223 // Temporary resolve recipient field
224 $unlArray = explode(':', HubTools::resolveSessionId($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]));
226 // Make sure it is a valid Universal Node Locator array (3 elements)
227 assert(count($unlArray) == 3);
230 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('POOL[' . __METHOD__ . ':' . __LINE__ . ']: Checking ' . count($this->getAllSockets()) . ' socket(s),unlArray[0]=' . $unlArray[0] . ',unlArray[1]=' . $unlArray[1] . ' ...');
232 // Default is all sockets
233 $sockets = $this->getAllSockets();
235 // Is connection type set?
236 if ((is_string($connectionType)) && ($this->isValidConnectionType($connectionType))) {
237 // Then get a list of this type
238 $sockets = $this->getSocketsByConnectionType($connectionType);
239 } elseif (is_string($connectionType)) {
240 // Is not a valid connection type!
241 throw new InvalidConnectionTypeException(array($this, $connectionType), self::EXCEPTION_INVALID_CONNECTION_TYPE);
244 // Get all sockets and check them, skip the server socket
245 foreach ($sockets as $socketArray) {
246 // Is this a server socket?
247 if ($socketArray[self::SOCKET_ARRAY_RESOURCE] === $this->getListenerInstance()->getSocketResource()) {
248 // Skip 'server' sockets (local socket)
249 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('POOL[' . __METHOD__ . ':' . __LINE__ . ']: Skipping server socket ' . $socketArray[self::SOCKET_ARRAY_RESOURCE] . ' ...');
253 // Try to get the "peer"'s name
254 if (!socket_getpeername($socketArray[self::SOCKET_ARRAY_RESOURCE], $peerIp)) {
255 // Handle the socket error with given package data
256 $this->handleSocketError(__METHOD__, __LINE__, $socketArray[self::SOCKET_ARRAY_RESOURCE], explode(':', $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]));
260 // If the "peer" IP and recipient is same, use it
261 if ($peerIp == $unlArray[0]) {
262 // IPs match, so take the socket and quit this loop
263 $socketResource = $socketArray[self::SOCKET_ARRAY_RESOURCE];
266 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('POOL[' . __METHOD__ . ':' . __LINE__ . ']: peerIp=' . $peerIp . ' matches with recipient IP address. Taking socket=' . $socketArray[self::SOCKET_ARRAY_RESOURCE] . ',type=' . $socketArray[self::SOCKET_ARRAY_CONN_TYPE]);
271 // Return the determined socket resource
272 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('POOL[' . __METHOD__ . ':' . __LINE__ . ']: socketResource[' . gettype($socketResource) . ']=' . $socketResource);
273 return $socketResource;