]> git.mxchange.org Git - hub.git/blob - application/hub/main/helper/connection/tcp/class_TcpConnectionHelper.php
Refacturing to pass a ProtocolHandler instance instead of the direct name. This
[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@shipsimu.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.shipsimu.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->setProtocolName('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                 // Debug message
81                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Setting socket resource ... (' . gettype($socketResource) . ')');
82
83                 // Set the resource
84                 $helperInstance->setSocketResource($socketResource);
85
86                 // Init connection
87                 $helperInstance->initConnection();
88
89                 // @TODO The whole resolving part should be moved out and made more configurable
90                 // Init recipient data
91                 $recipientData = NULL;
92
93                 // Try to solve the recipient
94                 try {
95                         // Resolve any session ids; 0 = IP, 1 = Port
96                         $recipientData = explode(':', HubTools::resolveSessionId($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]));
97                 } catch (NoValidHostnameException $e) {
98                         // Debug message
99                         self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Failed to resolve ' . $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ':' . $e->getMessage());
100
101                         // Is the recipient equal as configured IP
102                         if (substr($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], 0, strlen($helperInstance->getConfigInstance()->getConfigEntry('external_ip'))) == $helperInstance->getConfigInstance()->getConfigEntry('external_ip')) {
103                                 // This connects to shipsimu.org and requests /ip.php which will return our external IP number
104                                 $recipientData[0] = ConsoleTools::determineExternalIp();
105
106                                 // Do we have hostname:ip match?
107                                 if (strpos($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], ':') === FALSE) {
108                                         // No hostname:ip!
109                                         $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ' does not contain ":". Please fix this.');
110                                 } // END - if
111
112                                 // "explode" the hostname:ip, so index 1 will be the port number
113                                 $recipientArray = explode(':', $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]);
114
115                                 // Add the port
116                                 $recipientData[1] = $recipientArray[1];
117                         } else {
118                                 // It doesn't match, we need to take care of this later
119                                 $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . '!=' . $helperInstance->getConfigInstance()->getConfigEntry('external_ip'));
120                         }
121                 }
122
123                 // Set ip/port
124                 $helperInstance->setAddress($recipientData[0]);
125                 $helperInstance->setPort($recipientData[1]);
126
127                 // Now connect to it
128                 if (!$helperInstance->connectToPeerByRecipientData($recipientData)) {
129                         // Handle socket error
130                         $helperInstance->handleSocketError(__METHOD__, __LINE__, $socketResource, $recipientData);
131                 } // END - if
132
133                 // Okay, that should be it. Return it...
134                 return $socketResource;
135         }
136
137         /**
138          * Do the shutdown sequence for this connection helper
139          *
140          * @return      void
141          * @throws      SocketShutdownException         If the current socket could not be shut down
142          * @todo        We may want to implement a filter for ease notification of other objects like our pool
143          */
144         public function doShutdown () {
145                 // Debug message
146                 self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down socket resource ' . $this->getSocketResource());
147
148                 // Clear any previous errors
149                 socket_clear_error($this->getSocketResource());
150
151                 // Call the shutdown function on the currently set socket
152                 if (!socket_shutdown($this->getSocketResource())) {
153                         // Could not shutdown socket, this is fine if e.g. the other side is not connected, so analyse it
154                         if (socket_last_error($this->getSocketResource()) != 107) {
155                                 // Something bad happened while we shutdown a socket
156                                 throw new SocketShutdownException($this, BaseListener::EXCEPTION_INVALID_SOCKET);
157                         } // END - if
158                 } // END - if
159
160                 // Try to make blocking IO for socket_close()
161                 socket_set_block($this->getSocketResource());
162
163                 // Drop all data (don't sent any on socket closure)
164                 socket_set_option($this->getSocketResource(), SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 0));
165
166                 // Finally close socket to free some resources
167                 socket_close($this->getSocketResource());
168
169                 // Mark this connection as shutted down
170                 $this->markConnectionShuttedDown();
171         }
172 }
173
174 // [EOF]
175 ?>