]> git.mxchange.org Git - hub.git/blob - application/hub/main/helper/connection/tcp/class_TcpConnectionHelper.php
all socketErrorFooHandler() methods shall be protected, else they can't be called...
[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 - 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
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 socket resource ("connection") for given recipient in package data
41          *
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
48          */
49         public static function createConnectionFromPackageData (array $packageData) {
50                 // Create an instance
51                 $helperInstance = new TcpConnectionHelper();
52
53                 // Create a socket instance
54                 $socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
55
56                 // Is the socket resource valid?
57                 if (!is_resource($socketResource)) {
58                         /*
59                          * Something bad happened, calling handleSocketError() is not
60                          * possible here because that method would throw an
61                          * InvalidSocketException back.
62                          */
63                         throw new SocketCreationException(array($helperInstance, gettype($socketResource)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
64                 } // END - if
65
66                 // Get socket error code for verification
67                 $socketError = socket_last_error($socketResource);
68
69                 // Check if there was an error else
70                 if ($socketError > 0) {
71                         // Handle this socket error with a faked recipientData array
72                         $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
73
74                         // Then throw again
75                         throw new SocketCreationException(array($helperInstance, gettype($socketResource), $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
76                 } // END - if
77
78                 // Set the option to reuse the port
79                 if (!socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1)) {
80                         // Handle this socket error with a faked recipientData array
81                         $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
82
83                         // And throw again
84                         throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
85                 } // END - if
86
87                 // Set socket in non-blocking mode
88                 if (!socket_set_nonblock($socketResource)) {
89                         // Handle this socket error with a faked recipientData array
90                         $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
91
92                         // And throw again
93                         throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
94                 } // END - if
95
96                 // Set the resource
97                 $helperInstance->setSocketResource($socketResource);
98
99                 // @TODO The whole resolving part should be moved out and made more configurable
100                 // Init recipient data
101                 $recipientData = NULL;
102
103                 // Try to solve the recipient
104                 try {
105                         // Resolve any session ids; 0 = IP, 1 = Port
106                         $recipientData = explode(':', HubTools::resolveSessionId($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]));
107                 } catch (NoValidHostnameException $e) {
108                         // Debug message
109                         $helperInstance->debugOutput('CONNECTION: Failed to resolve ' . $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ':' . $e->getMessage());
110
111                         // Is the recipient equal as configured IP
112                         if (substr($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], 0, strlen($helperInstance->getConfigInstance()->getConfigEntry('external_ip'))) == $helperInstance->getConfigInstance()->getConfigEntry('external_ip')) {
113                                 // This connects to ship-simu.org and requests /ip.php which will return our external IP number
114                                 $recipientData[0] = ConsoleTools::determineExternalIp();
115
116                                 // Do we have hostname:ip match?
117                                 if (strpos($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], ':') === false) {
118                                         // No hostname:ip!
119                                         $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ' does not contain ":". Please fix this.');
120                                 } // END - if
121
122                                 // "explode" the hostname:ip, so index 1 will be the port number
123                                 $recipientArray = explode(':', $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]);
124
125                                 // Add the port
126                                 $recipientData[1] = $recipientArray[1];
127                         } else {
128                                 // It doesn't match, we need to take care of this later
129                                 $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . '!=' . $helperInstance->getConfigInstance()->getConfigEntry('external_ip'));
130                         }
131                 }
132
133                 // Set ip/port
134                 $helperInstance->setAddress($recipientData[0]);
135                 $helperInstance->setPort($recipientData[1]);
136
137                 // Debug message
138                 $helperInstance->debugOutput('CONNECTION: Connecting to ' . $recipientData[0] . ':' . $recipientData[1]);
139
140                 // Now connect to it
141                 if (!@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
142                         // Handle socket error
143                         // @TODO Handle 115 error ("operation in progress")
144                         $helperInstance->handleSocketError($socketResource, $recipientData);
145                         /*
146                         // Get socket error code for verification
147                         $socketError = socket_last_error($socketResource);
148
149                         // And throw again, but not for 'Operation now in progress'; the shutdownSocket() method should wait a little
150                         if ($socketError != 115) {
151                                 // Get error message
152                                 $errorMessage = socket_strerror($socketError);
153
154                                 // Shutdown this socket
155                                 $helperInstance->shutdownSocket($socketResource);
156
157                                 // Throw it again
158                                 throw new SocketConnectionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
159                         } else {
160                                 // Debug output
161                                 $helperInstance->debugOutput('CONNECTION: Operation is in progress, this usual for non-blocking connections.');
162                         }
163                         */
164                 } // END - if
165
166                 // Connection is fully established here, so change the state
167                 PeerStateFactory::createPeerStateInstanceByName('connected', $helperInstance);
168
169                 // Okay, that should be it. Return it...
170                 return $socketResource;
171         }
172
173         /**
174          * Do the shutdown sequence for this connection helper
175          *
176          * @return      void
177          * @throws      SocketShutdownException         If the current socket could not be shut down
178          * @todo        We may want to implement a filter for ease notification of other objects like our pool
179          */
180         public function doShutdown () {
181                 // Debug message
182                 $this->debugOutput('HELPER: Shutting down socket resource ' . $this->getSocketResource());
183
184                 // Clear any previous errors
185                 socket_clear_error($this->getSocketResource());
186
187                 // Call the shutdown function on the currently set socket
188                 if (!@socket_shutdown($this->getSocketResource())) {
189                         // Could not shutdown socket, this is fine if e.g. the other side is not connected, so analyse it
190                         if (socket_last_error($this->getSocketResource()) != 107) {
191                                 // Something bad happened while we shutdown a socket
192                                 throw new SocketShutdownException($this, BaseListener::EXCEPTION_INVALID_SOCKET);
193                         } // END - if
194                 } // END - if
195
196                 // Mark this connection as shutted down
197                 $this->markConnectionShuttedDown();
198         }
199 }
200
201 // [EOF]
202 ?>