]> git.mxchange.org Git - hub.git/blob - application/hub/main/helper/connection/tcp/class_TcpConnectionHelper.php
Added line numbers to debug lines as this will become the 'norm'
[hub.git] / application / hub / main / helper / connection / tcp / class_TcpConnectionHelper.php
1 <?php
2 /**
3  * A TCP connection helper class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 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
11  *
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.
16  *
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.
21  *
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/>.
24  */
25 class TcpConnectionHelper extends BaseConnectionHelper implements ConnectionHelper {
26         /**
27          * Protected constructor
28          *
29          * @return      void
30          */
31         protected function __construct () {
32                 // Call parent constructor
33                 parent::__construct(__CLASS__);
34
35                 // Set protocol
36                 $this->setProtocol('tcp');
37         }
38
39         /**
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.
43          *
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
50          */
51         public static function createConnectionFromPackageData (array $packageData) {
52                 // Create an instance
53                 $helperInstance = new TcpConnectionHelper();
54
55                 // Create a socket instance
56                 $socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
57
58                 // Is the socket resource valid?
59                 if (!is_resource($socketResource)) {
60                         /*
61                          * Something bad happened, calling handleSocketError() is not
62                          * possible here because that method would throw an
63                          * InvalidSocketException back.
64                          */
65                         throw new SocketCreationException(array($helperInstance, gettype($socketResource)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
66                 } // END - if
67
68                 // Get socket error code for verification
69                 $socketError = socket_last_error($socketResource);
70
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'));
75
76                         // Then throw again
77                         throw new SocketCreationException(array($helperInstance, gettype($socketResource), $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
78                 } // END - if
79
80                 // Set the resource
81                 $helperInstance->setSocketResource($socketResource);
82
83                 // Init connection
84                 $helperInstance->initConnection();
85
86                 // @TODO The whole resolving part should be moved out and made more configurable
87                 // Init recipient data
88                 $recipientData = NULL;
89
90                 // Try to solve the recipient
91                 try {
92                         // Resolve any session ids; 0 = IP, 1 = Port
93                         $recipientData = explode(':', HubTools::resolveSessionId($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]));
94                 } catch (NoValidHostnameException $e) {
95                         // Debug message
96                         self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __LINE__ . ']: Failed to resolve ' . $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ':' . $e->getMessage());
97
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();
102
103                                 // Do we have hostname:ip match?
104                                 if (strpos($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], ':') === false) {
105                                         // No hostname:ip!
106                                         $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ' does not contain ":". Please fix this.');
107                                 } // END - if
108
109                                 // "explode" the hostname:ip, so index 1 will be the port number
110                                 $recipientArray = explode(':', $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]);
111
112                                 // Add the port
113                                 $recipientData[1] = $recipientArray[1];
114                         } else {
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'));
117                         }
118                 }
119
120                 // Set ip/port
121                 $helperInstance->setAddress($recipientData[0]);
122                 $helperInstance->setPort($recipientData[1]);
123
124                 // Now connect to it
125                 if (!$helperInstance->connectToPeerByRecipientData($recipientData)) {
126                         // Handle socket error
127                         $helperInstance->handleSocketError(__METHOD__, __LINE__, $socketResource, $recipientData);
128                 } // END - if
129
130                 // Okay, that should be it. Return it...
131                 return $socketResource;
132         }
133
134         /**
135          * Do the shutdown sequence for this connection helper
136          *
137          * @return      void
138          * @throws      SocketShutdownException         If the current socket could not be shut down
139          * @todo        We may want to implement a filter for ease notification of other objects like our pool
140          */
141         public function doShutdown () {
142                 // Debug message
143                 self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __LINE__ . ']: Shutting down socket resource ' . $this->getSocketResource());
144
145                 // Clear any previous errors
146                 socket_clear_error($this->getSocketResource());
147
148                 // Call the shutdown function on the currently set socket
149                 if (!socket_shutdown($this->getSocketResource())) {
150                         // Could not shutdown socket, this is fine if e.g. the other side is not connected, so analyse it
151                         if (socket_last_error($this->getSocketResource()) != 107) {
152                                 // Something bad happened while we shutdown a socket
153                                 throw new SocketShutdownException($this, BaseListener::EXCEPTION_INVALID_SOCKET);
154                         } // END - if
155                 } // END - if
156
157                 // Try to make blocking IO for socket_close()
158                 socket_set_block($this->getSocketResource());
159
160                 // Drop all data (don't sent any on socket closure)
161                 socket_set_option($this->getSocketResource(), SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 0));
162
163                 // Finally close socket to free some resources
164                 socket_close($this->getSocketResource());
165
166                 // Mark this connection as shutted down
167                 $this->markConnectionShuttedDown();
168         }
169 }
170
171 // [EOF]
172 ?>