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