added recv_server_quit and recv_quit
[PHP-P10.git] / Uplink / Uplink.class.php
1 <?php
2 /********************************* PHP-P10 ******************************
3  *    P10 uplink class by pk910   (c)2011 pk910                         *
4  ************************************************************************
5  *                          Version 2 (OOP)                             *
6  *                                                                      *
7  * PHP-P10 is free software; you can redistribute it and/or modify      *
8  * it under the terms of the GNU General Public License as published by *
9  * the Free Software Foundation; either version 2 of the License, or    *
10  * (at your option) any later version.                                  *
11  *                                                                      *
12  * This program is distributed in the hope that it will be useful,      *
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
15  * GNU General Public License for more details.                         *
16  *                                                                      *
17  * You should have received a copy of the GNU General Public License    *
18  * along with PHP-P10; if not, write to the Free Software Foundation,   *
19  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.       *
20  *                                                                      *
21  ************************************************************************
22  * 
23  *  Uplink/Uplink.class.php
24  *
25  * This file contains the basic P10 Protocol handler.
26  *
27  ************************************************************************
28  * accessable methods:
29  *
30  * void initialize()
31  *     has to be called after the settings have been set.
32  *
33  * void loop() 
34  *     loop function that should be calles as many times as possible. 
35  *     It reads from the socket and BLOCKS the script execution for a 
36  *     specific time if nothing is received.
37  *
38  * void setUplinkHost(String $host, int $port, bool $ssl = false, String $bind = null)
39  *     sets the Uplink connection information.
40  *
41  * void setLoopTimeout(int $timeout)
42  *     sets the maximum time loop() is blocking the script execution.
43  *
44  * void setUplinkServer(int $numeric, String $name, String $password, String $description)
45  *     sets the own P10 Server information.
46  *
47  * void setValidateServer(String $name, String $password)
48  *     sets additional security relevant information about the remote server.
49  */
50 require_once("Client.class.php");
51 require_once("Numerics.class.php");
52 require_once("P10Formatter.class.php");
53 require_once("P10_Server.class.php");
54 require_once("P10_User.class.php");
55 require_once("P10_ModeSets.class.php");
56
57 class Uplink {
58         private $client = new Client();
59         private $settings = array();
60         private $server;
61         
62         const FLAG_P10SESSION      = 0x0001; //connection is in P10 mode (server is connected)
63         const FLAG_SECURITY_QUIT   = 0x0002; //local connection abort because of security issues
64         const FLAG_NOT_CONNECTABLE = 0x0004; //remote server is not connectable
65         const FLAG_BURST_PENDING   = 0x0008; //we still have to burst
66         private $flags = 0;
67         
68         public function __construct() {
69                 $this->setSettings("recv_timeout", 1000);
70         }
71         
72         public function initialize() {
73                 if($this->server) {
74                         trigger_error("Uplink already initialized.", E_USER_ERROR);
75                         return;
76                 }
77                 $self_numeric = $this->getSetting("numeric");
78                 $self_name = $this->getSetting("name");
79                 $self_description = $this->getSetting("description");
80                 if(!$self_numeric || !$self_name) {
81                         trigger_error("Server Settings missing.", E_USER_ERROR);
82                         return;
83                 }
84                 $this->server = new P10_Server($self_name, $self_numeric, null, time(), time(), $self_description);
85         }
86         
87         public function loop() {
88                 if($this->server == null) {
89                         trigger_error("Uplink not initialized.", E_USER_ERROR);
90                         return;
91                 }
92                 if(!$this->client->connected()) {
93                         if(($this->flags & self::FLAG_P10SESSION)) {
94                                 //Server got disconnected
95                                 $this->server->disconnectServer(true);
96                                 $this->flags &= ~self::FLAG_P10SESSION;
97                         }
98                         $host = $this->getSetting("host");
99                         $port = $this->getSetting("port");
100                         if($host == null || $port == null) {
101                                 trigger_error("Uplink Settings missing.", E_USER_ERROR);
102                                 return;
103                         }
104                         if(($this->flags & self::FLAG_SECURITY_QUIT) || ($this->flags & self::FLAG_NOT_CONNECTABLE)) {
105                                 sleep(1);
106                         }
107                         $state = $this->client->connect($host, $port, $this->getSettings("bind"), $this->getSettings("ssl"), $this->getSettings("recv_timeout"));
108                         if(!$state) {
109                                 usleep($this->getSetting("recv_timeout") / 1000);
110                                 $this->flags |= self::FLAG_NOT_CONNECTABLE;
111                                 return;
112                         }
113                         $this->flags = 0;
114                         $this->loginServer();
115                 }
116                 //try to receive new data from the Uplink
117                 $lines = $this->client->recv();
118                 if($lines == null) return;
119                 foreach($lines as $line) {
120                         $this->parseLine($line);
121                 }
122         }
123         
124         public function setUplink($host, $port, $ssl = false, $bind = null) {
125                 $this->setSetting("host", $host);
126                 $this->setSetting("port", $port);
127                 $this->setSetting("ssl", $ssl);
128                 $this->setSetting("bind", $bind);
129         }
130         
131         public function setLoopTimeout($timeout) {
132                 $this->setSetting("recv_timeout", $timeout);
133         }
134         
135         public function setUplinkServer($numeric, $name, $password, $description) {
136                 $this->setSetting("numeric", Numerics::intToNum($numeric, 2));
137                 $this->setSetting("name", $name);
138                 $this->setSetting("password", $password);
139                 $this->setSetting("description", $description);
140         }
141         
142         public function setValidateServer($name, $password) {
143                 $this->setSetting("their_name", $name);
144                 $this->setSetting("their_password", $password);
145         }
146         
147         private function setSetting($setting, $value) {
148                 $this->settings[$setting] = $value;
149         }
150         
151         private function getSetting($setting) {
152                 if(array_key_exists($setting, $this->settings)) {
153                         return $this->settings[$setting];
154                 } else {
155                         return null;
156                 }
157         }
158         
159         private function loginServer() {
160                 $password = $this->getSetting("password");
161                 $this->send("PASS", $password);
162                 $this->send("SERVER", $this->server->getName(), $this->server->getStartTime(), $this->server->getLinkTime(), $this->server->getNumeric(), $this->server->getDescription());
163         }
164         
165         private function parseLine($line) {
166                 $highExplode = explode(" :", $line, 2);
167                 $tokens = explode(" ", $highExplode[0]);
168                 if(count($highExplode) > 1)
169                         $tokens[] = $highExplode[1];
170                 $cmdPos = (($this->flags & self::FLAG_P10SESSION) ? 1 : 0);
171                 if($cmdPos == 1) $from = $tokens[0];
172                 else $from = null;
173                 $arguments = array_slice($tokens, $cmdPos + 1);
174                 switch(strtoupper($tokens[$cmdPos])) {
175                 //pre P10 Session
176                         case "PASS":
177                                 $this->recv_pass($from, $arguments);
178                                 break;
179                         case "SERVER":
180                                 $this->recv_server($from, $arguments);
181                                 break;
182                         case "ERROR":
183                                 $this->recv_error($from, $arguments);
184                                 break;
185                 //P10 Session
186                         case "S":
187                                 $this->recv_server($from, $arguments);
188                                 break;
189                         case "G":
190                                 $this->recv_ping($from, $arguments);
191                                 break;
192                         case "N":
193                                 $this->recv_nick($from, $arguments);
194                                 break;
195                         case "EB":
196                                 $this->recv_end_of_burst($from, $arguments);
197                                 break;
198                         case "EA":
199                                 $this->recv_end_of_burst_ack($from, $arguments);
200                                 break;
201                         case "SQ":
202                                 $this->recv_server_quit($from, $arguments);
203                                 break;
204                         case "Q":
205                                 $this->recv_quit($from, $arguments);
206                                 break;
207                 //default
208                         default:
209                                 //unknown cmd
210                                 break;
211                 }
212         }
213         
214         private function send($command) {
215                 if(func_num_args() > 1) {
216                         $args = array_slice(func_get_args(), 1);
217                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, $args);
218                 }
219                 $this->client->send($command);
220         }
221         
222         /********************************************************************************************
223          *                                     INCOMING COMMANDS                                    *
224          ********************************************************************************************/
225         
226         private function recv_pass($from, $args) {
227                 $their_pass = $this->getSetting("their_password");
228                 if($their_pass) {
229                         if($args[0] != $their_pass) {
230                                 //security QUIT
231                                 $this->flags |= self::FLAG_SECURITY_QUIT;
232                                 $this->send("ERROR", "Incorrect password received.");
233                                 $this->client->disconnect();
234                         }
235                 }
236         }
237         
238         private function recv_error($from, $args) {
239                 //we received an error - the socket is dead for us, now
240                 //maybe we want to log this, later
241                 $this->client->disconnect();
242         }
243         
244         private function recv_server($from, $args) {
245                 if($from == null) {
246                         //our uplink Server
247                         $their_name = $this->getSetting("their_name");
248                         if($their_name && $args[0] != $their_name) {
249                                 $this->flags |= self::FLAG_SECURITY_QUIT;
250                                 $this->send("ERROR", "Invalid Server name");
251                                 $this->client->disconnect();
252                                 return;
253                         }
254                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $this->server, $args[2], $args[3], $args[7]);
255                         $this->server->add_server($new_server);
256                         $this->flags |= self::FLAG_P10SESSION | self::FLAG_BURST_PENDING;
257                 } else {
258                         //another server got a new slave server ^^
259                         $server = P10_Server::getServerByNum($from);
260                         if($server == null) {
261                                 trigger_error("Parent Server (".$from.") does not exist or was not found on recv_server.", E_USER_ERROR);
262                                 return;
263                         }
264                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $server, $args[2], $args[3], $args[7]);
265                         $server->add_server($new_server);
266                 }
267         }
268         
269         private function recv_ping($from, $args) {
270                 $this->send("Z", $args[0]); //simply PONG
271         }
272         
273         private function recv_nick($from, $args) {
274                 if(count($args) <= 2) {
275                         //Nick change
276                         $user = P10_User::getUserByNum($from);
277                         if($user == null) {
278                                 trigger_error("Server tries to change the nick of an user that does not exist or was not found on recv_nick.", E_USER_ERROR);
279                                 return;
280                         }
281                         $nick->setNick($args[0]);
282                 } else {
283                         //New User
284                         $numeric = $args[count($args)-2];
285                         $nick = $args[0];
286                         $server = P10_Server::getServerByNum($from);
287                         if($server == null) {
288                                 trigger_error("Server (".$from.") the User (".$nick.") is coming from does not exist or was not found on recv_nick.", E_USER_ERROR);
289                                 return;
290                         }
291                         if(substr($numeric,0,2) != $from) {
292                                 trigger_error("A Server (".$from.") tries to connect a User with an invalid User numeric ('".$numeric."' does not belong to the Server)", E_USER_WARNING);
293                         }
294                         $connect_time = $args[2];
295                         $ident = $args[3];
296                         $host = $args[4];
297                         $modes = implode(" ",array_slice($args, 5, count($args)-8));
298                         $modes = new UserModeSet($modes);
299                         $ip = Numerics::parseIP($args[count($args)-3]);
300                         $realname = $args[count($args)-1];
301                         new P10_User($nick, $numeric, $server, $connect_time, $ident, $host, $ip, $realname, $modes);
302                 }
303         }
304         
305         private function recv_end_of_burst($from, $args) {
306                 if(($this->flags & self::FLAG_BURST_PENDING)) {
307                         $this->burst();
308                         $this->send("EA");
309                         $this->flags &= ~self::FLAG_BURST_PENDING;
310                 }
311         }
312         
313         private function recv_end_of_burst_ack($from, $args) {
314                 //nothing to do here?
315         }
316         
317         private function recv_server_quit($from, $args) {
318                 $server = P10_Server::getServerByName($args[0]);
319                 if($server == null) {
320                         trigger_error("Server (".$args[0].") not found.", E_USER_ERROR);
321                         return;
322                 }
323                 $server->disconnectServer();
324         }
325         
326         private function recv_quit($from, $args) {
327                 $user = P10_User::getUserByNum($from);
328                 if($user == null) {
329                         trigger_error("Server tries to quit an user that does not exist or was not found on recv_quit.", E_USER_ERROR);
330                         return;
331                 }
332                 $user->quit($args[0]);
333         }
334         
335         /********************************************************************************************
336          *                                     SERVER FUNCTIONS                                     *
337          ********************************************************************************************/
338         
339         private function burst() {
340                 foreach($this->server->getUsers() as $user) {
341                         $nick = $user->getNick();
342                         $connect_time = $user->getConnectTime();
343                         $ident = $user->getIdent();
344                         $host = $user->getHost();
345                         $modes = $user->getModes()->getModeString();
346                         $ip = Numerics::numericFromIP($user->getIP());
347                         $numeric = $user->getNumeric();
348                         $realname = $user->getRealname();
349                         $this->send("N", $nick, $connect_time, $ident, $host, $modes, $ip, $numeric, $realname);
350                 }
351                 $this->send("EB");
352         }
353         
354 }
355
356 ?>