3 * A ??? connection helper class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
10 * @todo Find an interface for hub helper
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class BaseIpV4ConnectionHelper extends BaseConnectionHelper {
29 private $connectionPort = 0;
32 * Protected constructor
36 protected function __construct () {
37 // Call parent constructor
38 parent::__construct(__CLASS__);
42 * Getter for port number to satify HandleableProtocol
44 * @return $connectionPort The port number
46 public final function getConnectionPort () {
47 return $this->connectionPort;
51 * Setter for port number to satify HandleableProtocol
53 * @param $connectionPort The port number
56 protected final function setConnectionPort ($connectionPort) {
57 $this->connectionPort = $connectionPort;
61 * Initializes the current connection
64 * @throws SocketOptionException If setting any socket option fails
66 protected function initConnection () {
67 // Get socket resource
68 $socketResource = $this->getSocketResource();
70 // Set the option to reuse the port
71 if (!socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1)) {
72 // Handle this socket error with a faked recipientData array
73 $this->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
76 // @TODO Move this to the socket error handler
77 throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
81 * Set socket to non-blocking mode before trying to establish a link to
82 * it. This is now the default behaviour for all connection helpers who
83 * call initConnection(); .
85 if (!socket_set_nonblock($socketResource)) {
86 // Handle this socket error with a faked recipientData array
87 $helperInstance->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
90 throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
93 // Last step: mark connection as initialized
94 $this->setIsInitialized(TRUE);
98 * Attempts to connect to a peer by given IP number and port from a valid
99 * unlData array with currently configured timeout.
101 * @param $unlData Valid UNL data array
102 * @return $isConnected Whether the connection went fine
103 * @see Please see http://de.php.net/manual/en/function.socket-connect.php#84465 for original code
104 * @todo Rewrite the while() loop to a iterator to not let the software stay very long here
106 protected function connectToPeerByUnlData (array $unlData) {
107 // Only call this if the connection is initialized by initConnection()
108 assert($this->isInitialized());
110 // Is unlData complete?
111 assert(isset($unlData[UniversalNodeLocator::UNL_PART_PROTOCOL]));
112 assert(isset($unlData[UniversalNodeLocator::UNL_PART_ADDRESS]));
113 assert(isset($unlData[UniversalNodeLocator::UNL_PART_PORT]));
118 // "Cache" socket resource and timeout config
119 $socketResource = $this->getSocketResource();
120 $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
123 self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Trying to connect to ' . $unlData[UniversalNodeLocator::UNL_PART_ADDRESS] . ':' . $unlData[UniversalNodeLocator::UNL_PART_PORT] . ' with socketResource[' . gettype($socketResource) . ']=' . $socketResource . ' ...');
125 // Try to connect until it is connected
126 while ($isConnected = !@socket_connect($socketResource, $unlData[UniversalNodeLocator::UNL_PART_ADDRESS], $unlData[UniversalNodeLocator::UNL_PART_PORT])) {
127 // Get last socket error
128 $socketError = socket_last_error($socketResource);
130 // Skip any errors which may happen on non-blocking connections
131 if (($socketError == SOCKET_EINPROGRESS) || ($socketError == SOCKET_EALREADY)) {
132 // Now, is that attempt within parameters?
133 if ((time() - $time) >= $timeout) {
134 // Didn't work within timeout
135 $isConnected = FALSE;
139 // Sleep about one second
141 } elseif ($socketError != 0) {
142 // Stop on everything else pronto
143 $isConnected = FALSE;
148 // Is the peer connected?
149 if ($isConnected === TRUE) {
150 // Connection is fully established here, so change the state.
151 PeerStateFactory::createPeerStateInstanceByName('connected', $this);
154 * There was a problem connecting to the peer (this state is a meta
155 * state until the error handler has found the real cause).
157 PeerStateFactory::createPeerStateInstanceByName('problem', $this);
165 * Marks this connection as shutted down
169 protected final function markConnectionShuttedDown () {
170 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $this->__toString() . ' has been marked as shutted down');
171 $this->shuttedDown = TRUE;
173 // And remove the (now invalid) socket
174 $this->setSocketResource(FALSE);
177 // ************************************************************************
178 // Socket error handler call-back methods
179 // ************************************************************************
182 * Handles socket error 'connection timed out', but does not clear it for
183 * later debugging purposes.
185 * @param $socketResource A valid socket resource
186 * @param $unlData A valid UNL data array
188 * @throws SocketConnectionException The connection attempts fails with a time-out
190 protected function socketErrorConnectionTimedOutHandler ($socketResource, array $unlData) {
191 // Get socket error code for verification
192 $socketError = socket_last_error($socketResource);
195 $errorMessage = socket_strerror($socketError);
197 // Shutdown this socket
198 $this->shutdownSocket($socketResource);
201 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
205 * Handles socket error 'resource temporary unavailable', but does not
206 * clear it for later debugging purposes.
208 * @param $socketResource A valid socket resource
209 * @param $unlData A valid UNL data array
211 * @throws SocketConnectionException The connection attempts fails with a time-out
213 protected function socketErrorResourceUnavailableHandler ($socketResource, array $unlData) {
214 // Get socket error code for verification
215 $socketError = socket_last_error($socketResource);
218 $errorMessage = socket_strerror($socketError);
220 // Shutdown this socket
221 $this->shutdownSocket($socketResource);
224 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
228 * Handles socket error 'connection refused', but does not clear it for
229 * later debugging purposes.
231 * @param $socketResource A valid socket resource
232 * @param $unlData A valid UNL data array
234 * @throws SocketConnectionException The connection attempts fails with a time-out
236 protected function socketErrorConnectionRefusedHandler ($socketResource, array $unlData) {
237 // Get socket error code for verification
238 $socketError = socket_last_error($socketResource);
241 $errorMessage = socket_strerror($socketError);
243 // Shutdown this socket
244 $this->shutdownSocket($socketResource);
247 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
251 * Handles socket error 'no route to host', but does not clear it for later
252 * debugging purposes.
254 * @param $socketResource A valid socket resource
255 * @param $unlData A valid UNL data array
257 * @throws SocketConnectionException The connection attempts fails with a time-out
259 protected function socketErrorNoRouteToHostHandler ($socketResource, array $unlData) {
260 // Get socket error code for verification
261 $socketError = socket_last_error($socketResource);
264 $errorMessage = socket_strerror($socketError);
266 // Shutdown this socket
267 $this->shutdownSocket($socketResource);
270 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
274 * Handles socket error 'operation already in progress' which happens in
275 * method connectToPeerByUnlData() on timed out connection
278 * @param $socketResource A valid socket resource
279 * @param $unlData A valid UNL data array
281 * @throws SocketConnectionException The connection attempts fails with a time-out
283 protected function socketErrorOperationAlreadyProgressHandler ($socketResource, array $unlData) {
284 // Get socket error code for verification
285 $socketError = socket_last_error($socketResource);
288 $errorMessage = socket_strerror($socketError);
290 // Half-shutdown this socket (see there for difference to shutdownSocket())
291 $this->halfShutdownSocket($socketResource);
294 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
298 * Handles socket error 'connection reset by peer', but does not clear it for
299 * later debugging purposes.
301 * @param $socketResource A valid socket resource
302 * @param $unlData A valid UNL data array
304 * @throws SocketConnectionException The connection attempts fails with a time-out
306 protected function socketErrorConnectionResetByPeerHandler ($socketResource, array $unlData) {
307 // Get socket error code for verification
308 $socketError = socket_last_error($socketResource);
311 $errorMessage = socket_strerror($socketError);
313 // Shutdown this socket
314 $this->shutdownSocket($socketResource);
317 throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
321 * Handles socket "error" 'operation now in progress' which can be safely
322 * passed on with non-blocking connections.
324 * @param $socketResource A valid socket resource
325 * @param $unlData A valid UNL data array
328 protected function socketErrorOperationInProgressHandler ($socketResource, array $unlData) {
329 self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Operation is now in progress, this is usual for non-blocking connections and is no bug.');