]> git.mxchange.org Git - hub.git/blob - application/hub/main/listener/tcp/class_TcpListener.php
Merge branch 'master' into refacuring/protocol_handler
[hub.git] / application / hub / main / listener / tcp / class_TcpListener.php
1 <?php
2 /**
3  * A TCP connection listener
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2014 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.shipsimu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24 class TcpListener extends BaseListener implements Listenable {
25         /**
26          * Protected constructor
27          *
28          * @return      void
29          */
30         protected function __construct () {
31                 // Call parent constructor
32                 parent::__construct(__CLASS__);
33
34                 // Set the protocol to TCP
35                 $this->setProtocolName('tcp');
36         }
37
38         /**
39          * Creates an instance of this class
40          *
41          * @param       $nodeInstance           A NodeHelper instance
42          * @return      $listenerInstance       An instance a prepared listener class
43          */
44         public static final function createTcpListener (NodeHelper $nodeInstance) {
45                 // Get new instance
46                 $listenerInstance = new TcpListener();
47
48                 // Set the application instance
49                 $listenerInstance->setNodeInstance($nodeInstance);
50
51                 // Return the prepared instance
52                 return $listenerInstance;
53         }
54
55         /**
56          * Initializes the listener by setting up the required socket server
57          *
58          * @return      void
59          * @throws      InvalidSocketException  Thrown if the socket could not be initialized
60          */
61         public function initListener () {
62                 // Create a streaming socket, of type TCP/IP
63                 $mainSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
64
65                 // Is the socket resource valid?
66                 if (!is_resource($mainSocket)) {
67                         // Something bad happened
68                         throw new InvalidSocketException(array($this, $mainSocket), BaseListener::EXCEPTION_INVALID_SOCKET);
69                 } // END - if
70
71                 // Get socket error code for verification
72                 $socketError = socket_last_error($mainSocket);
73
74                 // Check if there was an error else
75                 if ($socketError > 0) {
76                         // Handle this socket error with a faked recipientData array
77                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
78                         /*
79                         // Then throw again
80                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_INVALID_SOCKET);
81                         */
82                 } // END - if
83
84                 // Set the option to reuse the port
85                 if (!socket_set_option($mainSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
86                         // Handle this socket error with a faked recipientData array
87                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
88                         /*
89                         // Get socket error code for verification
90                         $socketError = socket_last_error($mainSocket);
91
92                         // Get error message
93                         $errorMessage = socket_strerror($socketError);
94
95                         // Shutdown this socket
96                         $this->shutdownSocket($mainSocket);
97
98                         // And throw again
99                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
100                         */
101                 } // END - if
102
103                 /*
104                  * "Bind" the socket to the given address, on given port so this means
105                  * that all connections on this port are now our resposibility to
106                  * send/recv data, disconnect, etc..
107                  */
108                 self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Binding to address ' . $this->getListenAddress() . ':' . $this->getListenPort());
109                 if (!socket_bind($mainSocket, $this->getListenAddress(), $this->getListenPort())) {
110                         // Handle this socket error with a faked recipientData array
111                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
112                         /*
113                         // Get socket error code for verification
114                         $socketError = socket_last_error($mainSocket);
115
116                         // Get error message
117                         $errorMessage = socket_strerror($socketError);
118
119                         // Shutdown this socket
120                         $this->shutdownSocket($mainSocket);
121
122                         // And throw again
123                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
124                         */
125                 } // END - if
126
127                 // Start listen for connections
128                 self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Listening for connections.');
129                 if (!socket_listen($mainSocket)) {
130                         // Handle this socket error with a faked recipientData array
131                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
132                         /*
133                         // Get socket error code for verification
134                         $socketError = socket_last_error($mainSocket);
135
136                         // Get error message
137                         $errorMessage = socket_strerror($socketError);
138
139                         // Shutdown this socket
140                         $this->shutdownSocket($mainSocket);
141
142                         // And throw again
143                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
144                         */
145                 } // END - if
146
147                 // Now, we want non-blocking mode
148                 self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting non-blocking mode.');
149                 if (!socket_set_nonblock($mainSocket)) {
150                         // Handle this socket error with a faked recipientData array
151                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('0.0.0.0', '0'));
152                         /*
153                         // Get socket error code for verification
154                         $socketError = socket_last_error($mainSocket);
155
156                         // Get error message
157                         $errorMessage = socket_strerror($socketError);
158
159                         // Shutdown this socket
160                         $this->shutdownSocket($mainSocket);
161
162                         // And throw again
163                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
164                         */
165                 } // END - if
166
167                 // Set the main socket
168                 $this->registerServerSocketResource($mainSocket);
169
170                 // Initialize the peer pool instance
171                 $poolInstance = ObjectFactory::createObjectByConfiguredName('node_pool_class', array($this));
172
173                 // Add main socket
174                 $poolInstance->addPeer($mainSocket, BaseConnectionHelper::CONNECTION_TYPE_SERVER);
175
176                 // And add it to this listener
177                 $this->setPoolInstance($poolInstance);
178
179                 // Initialize iterator for listening on packages
180                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('network_listen_iterator_class', array($poolInstance->getPoolEntriesInstance()));
181
182                 // Rewind it and remember it in this class
183                 $iteratorInstance->rewind();
184                 $this->setIteratorInstance($iteratorInstance);
185
186                 // Initialize the network package handler
187                 $handlerInstance = ObjectFactory::createObjectByConfiguredName('tcp_raw_data_handler_class');
188
189                 // Set it in this class
190                 $this->setHandlerInstance($handlerInstance);
191
192                 // Output message
193                 self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: TCP listener now ready on IP ' . $this->getListenAddress() . ', port ' . $this->getListenPort() . ' for service.');
194         }
195
196         /**
197          * "Listens" for incoming network packages
198          *
199          * @return      void
200          * @throws      InvalidSocketException  If an invalid socket resource has been found
201          */
202         public function doListen () {
203                 // Get all readers
204                 $readers = $this->getPoolInstance()->getAllSingleSockets();
205                 $writers = array();
206                 $excepts = array();
207
208                 // Check if we have some peers left
209                 $left = socket_select(
210                         $readers,
211                         $writers,
212                         $excepts,
213                         0,
214                         150
215                 );
216
217                 // Some new peers found?
218                 if ($left < 1) {
219                         // Debug message
220                         //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
221
222                         // Nothing new found
223                         return;
224                 } // END - if
225
226                 // Debug message
227                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
228
229                 // Do we have changed peers?
230                 if (in_array($this->getSocketResource(), $readers)) {
231                         /*
232                          * Then accept it, if this socket is set to non-blocking IO and the
233                          * connection is NOT sending any data, socket_read() may throw
234                          * error 11 (Resource temporary unavailable). This really nasty
235                          * because if you have blocking IO socket_read() will wait and wait
236                          * and wait ...
237                          */
238                         $newSocket = socket_accept($this->getSocketResource());
239
240                         // Debug message
241                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
242
243                         // Array for timeout settings
244                         $options  = array(
245                                 // Seconds
246                                 'sec'  => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
247                                 // Milliseconds
248                                 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
249                         );
250
251                         // Set timeout to configured seconds
252                         // @TODO Does this work on Windozer boxes???
253                         if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
254                                 // Handle this socket error with a faked recipientData array
255                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
256                         } // END - if
257
258                         // Output result (only for debugging!)
259                         /*
260                         $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
261                         self::createDebugInstance(__CLASS__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, TRUE));
262                         */
263
264                         // Enable SO_OOBINLINE
265                         if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
266                                 // Handle this socket error with a faked recipientData array
267                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
268                         } // END - if
269
270                         // Set non-blocking
271                         if (!socket_set_nonblock($newSocket)) {
272                                 // Handle this socket error with a faked recipientData array
273                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
274                         } // END - if
275
276                         // Add it to the peers
277                         $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
278
279                         // Get peer name
280                         if (!socket_getpeername($newSocket, $peerName)) {
281                                 // Handle this socket error with a faked recipientData array
282                                 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
283                         } // END - if
284
285                         // Create a faked package data array
286                         $packageData = array(
287                                 NetworkPackage::PACKAGE_DATA_SENDER    => $peerName . ':0',
288                                 NetworkPackage::PACKAGE_DATA_RECIPIENT => $this->getSessionId(),
289                                 NetworkPackage::PACKAGE_DATA_PROTOCOL  => $this->getProtocolName(),
290                                 NetworkPackage::PACKAGE_DATA_STATUS    => NetworkPackage::PACKAGE_STATUS_FAKED
291                         );
292
293                         // Get a socket registry
294                         $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
295
296                         // Register the socket with the registry and with the faked array
297                         $registryInstance->registerSocket($this, $newSocket, $packageData);
298                 } // END - if
299
300                 // Do we have to rewind?
301                 if (!$this->getIteratorInstance()->valid()) {
302                         // Rewind the list
303                         $this->getIteratorInstance()->rewind();
304                 } // END - if
305
306                 // Get the current value
307                 $currentSocket = $this->getIteratorInstance()->current();
308
309                 // Handle it here, if not main server socket
310                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: currentSocket=' . $currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] . ',type=' . $currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] . ',serverSocket=' . $this->getSocketResource());
311                 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
312                         // ... or else it will raise warnings like 'Transport endpoint is not connected'
313                         $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
314                 } // END - if
315
316                 // Advance to next entry. This should be the last line.
317                 $this->getIteratorInstance()->next();
318         }
319
320         /**
321          * Checks whether the listener would accept the given package data array
322          *
323          * @param       $packageData    Raw package data
324          * @return      $accepts                Whether this listener does accept
325          * @throws      UnsupportedOperationException   If this method is called
326          */
327         public function ifListenerAcceptsPackageData (array $packageData) {
328                 // Please don't call this
329                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
330         }
331 }
332
333 // [EOF]
334 ?>