Continued:
[core.git] / inc / main / classes / listener / socket / class_SocketFileListener.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Listener\Socket;
4
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7
8 /**
9  * A file-based socket listener
10  *
11  * @author              Roland Haeder <webmaster@ship-simu.org>
12  * @version             0.0.0
13  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
14  * @license             GNU GPL 3.0 or any newer version
15  * @link                http://www.ship-simu.org
16  *
17  * This program is free software: you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation, either version 3 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program. If not, see <http://www.gnu.org/licenses/>.
29  */
30 class SocketFileListener extends BaseListener implements Listenable {
31         /**
32          * Protected constructor
33          *
34          * @return      void
35          */
36         protected function __construct () {
37                 // Call parent constructor
38                 parent::__construct(__CLASS__);
39
40                 // Set the protocol to file
41                 $this->setProtocolName('file');
42         }
43
44         /**
45          * Creates an instance of this class
46          *
47          * @return      $listenerInstance       An instance a prepared listener class
48          */
49         public final static function createSocketFileListener () {
50                 // Get new instance
51                 $listenerInstance = new SocketFileListener();
52
53                 // Return the prepared instance
54                 return $listenerInstance;
55         }
56
57         /**
58          * Initializes the listener by setting up the required socket server
59          *
60          * @return      void
61          */
62         public function initListener() {
63                 // Init socket
64                 $mainSocket = socket_create(AF_UNIX, SOCK_STREAM, 0);
65
66                 // Is the socket resource valid?
67                 if (!is_resource($mainSocket)) {
68                         // Something bad happened
69                         throw new InvalidSocketException(array($this, $mainSocket), BaseListener::EXCEPTION_INVALID_SOCKET);
70                 } // END - if
71
72                 // Get socket error code for verification
73                 $socketError = socket_last_error($mainSocket);
74
75                 // Check if there was an error else
76                 if ($socketError > 0) {
77                         // Handle this socket error with a faked recipientData array
78                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array('null', '0'));
79                 } // END - if
80
81                 // Create file name
82                 $socketFile = self::createTempPathForFile($this->getConfigInstance()->getConfigEntry('ipc_socket_file_name'));
83
84                 // Debug message
85                 self::createDebugInstance(__CLASS__)->debugOutput('SOCKET-FILE-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: socketFile=' . $socketFile . ' ...');
86
87                 // File name must not be empty
88                 assert(!empty($socketFile));
89
90                 // Is the file there?
91                 if ((self::isReachableFilePath($socketFile)) && (file_exists($socketFile))) {
92                         // Old socket found
93                         self::createDebugInstance(__CLASS__)->debugOutput('SOCKET-FILE-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: WARNING: Old socket at ' . $socketFile . ' found. Will not start.');
94
95                         // Shutdown this socket
96                         $this->shutdownSocket($mainSocket);
97
98                         // Quit here
99                         exit;
100                 } // END - if
101
102                 // Debug message
103                 self::createDebugInstance(__CLASS__)->debugOutput('SOCKET-FILE-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Binding to ' . $socketFile . ' ...');
104
105                 // Try to bind to it
106                 if (!socket_bind($mainSocket, $socketFile)) {
107                         // Handle error here
108                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array($socketFile, '0'));
109                         /*
110                         // Get socket error code for verification
111                         $socketError = socket_last_error($mainSocket);
112
113                         // Get error message
114                         $errorMessage = socket_strerror($socketError);
115
116                         // Shutdown this socket
117                         $this->shutdownSocket($mainSocket);
118
119                         // And throw again
120                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
121                         */
122                 } // END - if
123
124                 // Start listen for connections
125                 self::createDebugInstance(__CLASS__)->debugOutput('SOCKET-FILE-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Listening for connections.');
126                 if (!socket_listen($mainSocket)) {
127                         // Handle this socket error with a faked recipientData array
128                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array($socketFile, '0'));
129                         /*
130                         // Get socket error code for verification
131                         $socketError = socket_last_error($mainSocket);
132
133                         // Get error message
134                         $errorMessage = socket_strerror($socketError);
135
136                         // Shutdown this socket
137                         $this->shutdownSocket($mainSocket);
138
139                         // And throw again
140                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
141                         */
142                 } // END - if
143
144                 // Now, we want non-blocking mode
145                 self::createDebugInstance(__CLASS__)->debugOutput('SOCKET-FILE-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Setting non-blocking mode.');
146                 if (!socket_set_nonblock($mainSocket)) {
147                         // Handle this socket error with a faked recipientData array
148                         $this->handleSocketError(__METHOD__, __LINE__, $mainSocket, array($socketFile, '0'));
149                         /*
150                         // Get socket error code for verification
151                         $socketError = socket_last_error($mainSocket);
152
153                         // Get error message
154                         $errorMessage = socket_strerror($socketError);
155
156                         // Shutdown this socket
157                         $this->shutdownSocket($mainSocket);
158
159                         // And throw again
160                         throw new InvalidSocketException(array($this, $mainSocket, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
161                         */
162                 } // END - if
163
164                 // Set the main socket
165                 $this->registerServerSocketResource($mainSocket);
166
167                 // Initialize the peer pool instance
168                 $poolInstance = ObjectFactory::createObjectByConfiguredName('application_pool_class', array($this));
169
170                 // Add main socket
171                 $poolInstance->addPeer($mainSocket, BaseConnectionHelper::CONNECTION_TYPE_SERVER);
172
173                 // And add it to this listener
174                 $this->setPoolInstance($poolInstance);
175
176                 // Initialize iterator for listening on packages
177                 $iteratorInstance = ObjectFactory::createObjectByConfiguredName('socket_listen_iterator_class', array($poolInstance->getPoolEntriesInstance()));
178
179                 // Rewind it and remember it in this class
180                 $iteratorInstance->rewind();
181                 $this->setIteratorInstance($iteratorInstance);
182
183                 // Initialize the raw data handler
184                 $handlerInstance = ObjectFactory::createObjectByConfiguredName('socket_raw_data_handler_class');
185
186                 // Set it in this class
187                 $this->setHandlerInstance($handlerInstance);
188
189                 // Output message
190                 self::createDebugInstance(__CLASS__)->debugOutput('SOCKET-FILE-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: Socket listener now ready on socket ' . $socketFile . ' for service.');
191         }
192
193         /**
194          * "Listens" for incoming network packages
195          *
196          * @return      void
197          */
198         public function doListen() {
199                 // Call super method
200                 $this->doListenSocketSelect('');
201         }
202
203         /**
204          * Checks whether the listener would accept the given package data array
205          *
206          * @param       $packageData    Raw package data
207          * @return      $accepts                Whether this listener does accept
208          */
209         public function ifListenerAcceptsPackageData (array $packageData) {
210                 $this->partialStub('Need to implement this method.');
211         }
212
213         /**
214          * Monitors incoming raw data from the handler and transfers it to the
215          * given receiver instance.
216          *
217          * @return      void
218          */
219         public function monitorIncomingRawData () {
220                 $this->partialStub('Need to implement this method.');
221         }
222
223 }