3 * A TCP connection helper class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 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 TcpConnectionHelper extends BaseConnectionHelper implements ConnectionHelper {
27 * Protected constructor
31 protected function __construct () {
32 // Call parent constructor
33 parent::__construct(__CLASS__);
36 $this->setProtocol('tcp');
40 * Creates a socket resource ("connection") for given recipient in package data
42 * @param $packageData Raw package data
43 * @return $socketResource Socket resource
44 * @throws SocketCreationException If the socket could not be created
45 * @throws SocketOptionException If a socket option could not be set
46 * @throws SocketConnectionException If a connection could not be opened
47 * @todo $errorCode/-Message are now in handleSocketError()'s call-back methods
49 public static function createConnectionFromPackageData (array $packageData) {
51 $helperInstance = new TcpConnectionHelper();
53 // Create a socket instance
54 $socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
56 // Is the socket resource valid?
57 if (!is_resource($socketResource)) {
58 // Something bad happened
59 throw new SocketCreationException(array($helperInstance, gettype($socketResource)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
62 // Get socket error code for verification
63 $socketError = socket_last_error($socketResource);
65 // Check if there was an error else
66 if ($socketError > 0) {
67 // Handle this socket error with a faked recipientData array
68 $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
71 throw new SocketCreationException(array($helperInstance, gettype($socketResource), $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
74 // Set the option to reuse the port
75 if (!socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1)) {
76 // Handle this socket error with a faked recipientData array
77 $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
80 throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
84 $helperInstance->setSocketResource($socketResource);
86 // @TODO The whole resolving part should be moved out and made more configurable
87 // Init recipient data
88 $recipientData = NULL;
90 // Try to solve the recipient
92 // Resolve any session ids; 0 = IP, 1 = Port
93 $recipientData = explode(':', HubTools::resolveSessionId($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]));
94 } catch (NoValidHostnameException $e) {
96 $helperInstance->debugOutput('CONNECTION: Failed to resolve ' . $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ':' . $e->getMessage());
98 // Is the recipient equal as configured IP
99 if (substr($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], 0, strlen($helperInstance->getConfigInstance()->getConfigEntry('external_ip'))) == $helperInstance->getConfigInstance()->getConfigEntry('external_ip')) {
100 // This connects to ship-simu.org and requests /ip.php which will return our external IP number
101 $recipientData[0] = ConsoleTools::determineExternalIp();
103 // Do we have hostname:ip match?
104 if (strpos($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], ':') === false) {
106 $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ' does not contain ":". Please fix this.');
109 // "explode" the hostname:ip, so index 1 will be the port number
110 $recipientArray = explode(':', $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]);
113 $recipientData[1] = $recipientArray[1];
115 // It doesn't match, we need to take care of this later
116 $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . '!=' . $helperInstance->getConfigInstance()->getConfigEntry('external_ip'));
121 $helperInstance->setAddress($recipientData[0]);
122 $helperInstance->setPort($recipientData[1]);
125 $helperInstance->debugOutput('CONNECTION: Connecting to ' . $recipientData[0] . ':' . $recipientData[1]);
128 if (!@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
129 // Handle socket error
130 // @TODO Handle 115 error ("operation in progress")
131 $helperInstance->handleSocketError($socketResource, $recipientData);
133 // Get socket error code for verification
134 $socketError = socket_last_error($socketResource);
136 // And throw again, but not for 'Operation now in progress'; the shutdownSocket() method should wait a little
137 if ($socketError != 115) {
139 $errorMessage = socket_strerror($socketError);
141 // Shutdown this socket
142 $helperInstance->shutdownSocket($socketResource);
145 throw new SocketConnectionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
148 $helperInstance->debugOutput('CONNECTION: Operation is in progress, this usual for non-blocking connections.');
153 // Set socket in non-blocking mode
154 if (!socket_set_nonblock($socketResource)) {
155 // Handle this socket error with a faked recipientData array
156 $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
159 throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
162 // Connection is fully established here, so change the state
163 PeerStateFactory::createPeerStateInstanceByName('connected', $helperInstance);
165 // Okay, that should be it. Return it...
166 return $socketResource;
170 * Do the shutdown sequence for this connection helper
173 * @throws SocketShutdownException If the current socket could not be shut down
174 * @todo We may want to implement a filter for ease notification of other objects like our pool
176 public function doShutdown () {
178 $this->debugOutput('HELPER: Shutting down socket resource ' . $this->getSocketResource());
180 // Clear any previous errors
181 socket_clear_error($this->getSocketResource());
183 // Call the shutdown function on the currently set socket
184 if (!@socket_shutdown($this->getSocketResource())) {
185 // Could not shutdown socket, this is fine if e.g. the other side is not connected, so analyse it
186 if (socket_last_error($this->getSocketResource()) != 107) {
187 // Something bad happened while we shutdown a socket
188 throw new SocketShutdownException($this, BaseListener::EXCEPTION_INVALID_SOCKET);
192 // Mark this connection as shutted down
193 $this->markConnectionShuttedDown();