3 * A TCP connection helper class
5 * @author Roland Haeder <webmaster@shipsimu.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.shipsimu.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 BaseIpV4ConnectionHelper implements ConnectionHelper {
27 * Protected constructor
31 protected function __construct () {
32 // Call parent constructor
33 parent::__construct(__CLASS__);
36 $this->setProtocolName('tcp');
40 * Creates a half-connected socket resource ("connection") for given
41 * recipient in package data. After you called this method you still need to
42 * connect to the other node.
44 * @param $packageData Raw package data
45 * @return $socketResource Socket resource
46 * @throws SocketCreationException If the socket could not be created
47 * @throws SocketOptionException If a socket option could not be set
48 * @throws SocketConnectionException If a connection could not be opened
49 * @todo $errorCode/-Message are now in handleSocketError()'s call-back methods
51 public static function createConnectionFromPackageData (array $packageData) {
53 $helperInstance = new TcpConnectionHelper();
55 // Create a socket instance
56 $socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
58 // Is the socket resource valid?
59 if (!is_resource($socketResource)) {
61 * Something bad happened, calling handleSocketError() is not
62 * possible here because that method would throw an
63 * InvalidSocketException back.
65 throw new SocketCreationException(array($helperInstance, gettype($socketResource)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
68 // Get socket error code for verification
69 $socketError = socket_last_error($socketResource);
71 // Check if there was an error else
72 if ($socketError > 0) {
73 // Handle this socket error with a faked recipientData array
74 $helperInstance->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
77 throw new SocketCreationException(array($helperInstance, gettype($socketResource), $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
81 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Setting socket resource ... (' . gettype($socketResource) . ')');
84 $helperInstance->setSocketResource($socketResource);
87 $helperInstance->initConnection();
89 // @TODO The whole resolving part should be moved out and made more configurable
90 // Init recipient data
93 // Try to solve the recipient
95 // Resolve any session ids; 0 = IP, 1 = Port
96 $handlerInstance = ProtocolHandlerFactory::createProtocolHandlerFromPackageData($packageData);
99 $unlData = $handlerInstance->getUniversalNodeLocatorData();
101 // Set handler instance
102 $helperInstance->setHandlerInstance($handlerInstance);
103 } catch (NoValidHostnameException $e) {
105 self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Failed to resolve ' . $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ':' . $e->getMessage());
107 // Is the recipient equal as configured IP
108 if (substr($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], 0, strlen($helperInstance->getConfigInstance()->getConfigEntry('external_address'))) == $helperInstance->getConfigInstance()->getConfigEntry('external_address')) {
109 // This may connect to shipsimu.org and requests 'ip.php' which will return our external IP address
110 $unlData[UniversalNodeLocator::UNL_PART_ADDRESS] = HubTools::determineExternalAddress();
112 // Do we have ip:port match?
113 // @TODO Rewrite this test for UNLs
114 if (strpos($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], ':') === FALSE) {
116 $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ' does not contain ":". Please fix this.');
119 // "explode" the ip:port, so index 1 will be the port number
120 // @TODO Rewrite this test for UNLs
121 $recipientArray = explode(':', $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]);
124 $unlData[UniversalNodeLocator::UNL_PART_PORT] = $recipientArray[UniversalNodeLocator::UNL_PART_PORT];
126 // It doesn't match, we need to take care of this later
127 $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . '!=' . $helperInstance->getConfigInstance()->getConfigEntry('external_address'));
131 // Set address and maybe port
132 $helperInstance->setAddress($unlData[UniversalNodeLocator::UNL_PART_ADDRESS]);
133 $helperInstance->setConnectionPort($unlData[UniversalNodeLocator::UNL_PART_PORT]);
136 if (!$helperInstance->connectToPeerByUnlData($unlData)) {
137 // Handle socket error
138 $helperInstance->handleSocketError(__METHOD__, __LINE__, $socketResource, $unlData);
141 // Okay, that should be it. Return it...
142 return $socketResource;
146 * Do the shutdown sequence for this connection helper
149 * @throws SocketShutdownException If the current socket could not be shut down
150 * @todo We may want to implement a filter for ease notification of other objects like our pool
152 public function doShutdown () {
154 self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down socket resource ' . $this->getSocketResource());
156 // Clear any previous errors
157 socket_clear_error($this->getSocketResource());
159 // Call the shutdown function on the currently set socket
160 if (!socket_shutdown($this->getSocketResource())) {
161 // Could not shutdown socket, this is fine if e.g. the other side is not connected, so analyse it
162 if (socket_last_error($this->getSocketResource()) != 107) {
163 // Something bad happened while we shutdown a socket
164 throw new SocketShutdownException($this, BaseListener::EXCEPTION_INVALID_SOCKET);
168 // Try to make blocking IO for socket_close()
169 socket_set_block($this->getSocketResource());
171 // Drop all data (don't sent any on socket closure)
172 socket_set_option($this->getSocketResource(), SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 0));
174 // Finally close socket to free some resources
175 socket_close($this->getSocketResource());
177 // Mark this connection as shutted down
178 $this->markConnectionShuttedDown();