added recv_join & recv_part
[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  * void setEventHandler(EventHandler $event_handler)
51  *     sets the EventHandlder
52  */
53 require_once("Client.class.php");
54 require_once("Numerics.class.php");
55 require_once("P10Formatter.class.php");
56 require_once("P10_Server.class.php");
57 require_once("P10_User.class.php");
58 require_once("P10_Channel.class.php");
59 require_once("P10_ModeSets.class.php");
60
61 class Uplink {
62         private $client;
63         private $settings = array();
64         private $server;
65         
66         const FLAG_P10SESSION      = 0x0001; //connection is in P10 mode (server is connected)
67         const FLAG_SECURITY_QUIT   = 0x0002; //local connection abort because of security issues
68         const FLAG_NOT_CONNECTABLE = 0x0004; //remote server is not connectable
69         const FLAG_BURST_PENDING   = 0x0008; //we still have to burst
70         const FLAG_CONNECTED       = 0x0010; //connected and synced (ready)
71         const FLAG_GOT_PASS        = 0x0020; //got PASS from the remote Server
72         private $flags = 0;
73         
74         public function __construct() {
75                 $this->client = new Client();
76                 $this->setSetting("recv_timeout", 1000);
77         }
78         
79         public function initialize() {
80                 if($this->server) {
81                         trigger_error("Uplink already initialized.", E_USER_ERROR);
82                         return;
83                 }
84                 $self_numeric = $this->getSetting("numeric");
85                 $self_name = $this->getSetting("name");
86                 $self_description = $this->getSetting("description");
87                 if(!$self_numeric || !$self_name) {
88                         trigger_error("Server Settings missing.", E_USER_ERROR);
89                         return;
90                 }
91                 $this->server = new P10_Server($self_name, $self_numeric, null, time(), time(), $self_description);
92         }
93         
94         public function loop() {
95                 if($this->server == null) {
96                         trigger_error("Uplink not initialized.", E_USER_ERROR);
97                         return;
98                 }
99                 if(!$this->client->connected()) {
100                         if(($this->flags & self::FLAG_P10SESSION)) {
101                                 //Server got disconnected
102                                 $this->server->disconnectServer(true);
103                                 $this->flags &= ~self::FLAG_P10SESSION;
104                         }
105                         $host = $this->getSetting("host");
106                         $port = $this->getSetting("port");
107                         if($host == null || $port == null) {
108                                 trigger_error("Uplink Settings missing.", E_USER_ERROR);
109                                 return;
110                         }
111                         if(($this->flags & self::FLAG_SECURITY_QUIT) || ($this->flags & self::FLAG_NOT_CONNECTABLE)) {
112                                 sleep(1);
113                         }
114                         $state = $this->client->connect($host, $port, $this->getSetting("bind"), $this->getSetting("ssl"), $this->getSetting("recv_timeout"));
115                         if(!$state) {
116                                 usleep($this->getSetting("recv_timeout") / 1000);
117                                 $this->flags |= self::FLAG_NOT_CONNECTABLE;
118                                 return;
119                         }
120                         $this->flags = 0;
121                         $this->loginServer();
122                 }
123                 //try to receive new data from the Uplink
124                 $lines = $this->client->recv();
125                 if($lines == null) return;
126                 foreach($lines as $line) {
127                         $this->parseLine($line);
128                 }
129         }
130         
131         public function setUplinkHost($host, $port, $ssl = false, $bind = null) {
132                 $this->setSetting("host", $host);
133                 $this->setSetting("port", $port);
134                 $this->setSetting("ssl", $ssl);
135                 $this->setSetting("bind", $bind);
136         }
137         
138         public function setLoopTimeout($timeout) {
139                 $this->setSetting("recv_timeout", $timeout);
140         }
141         
142         public function setUplinkServer($numeric, $name, $password, $description) {
143                 $this->setSetting("numeric", Numerics::intToNum($numeric, 2));
144                 $this->setSetting("name", $name);
145                 $this->setSetting("password", $password);
146                 $this->setSetting("description", $description);
147         }
148         
149         public function setValidateServer($name, $password) {
150                 $this->setSetting("their_name", $name);
151                 $this->setSetting("their_password", $password);
152         }
153         
154         private function setSetting($setting, $value) {
155                 $this->settings[$setting] = $value;
156         }
157         
158         private function getSetting($setting) {
159                 if(array_key_exists($setting, $this->settings)) {
160                         return $this->settings[$setting];
161                 } else {
162                         return null;
163                 }
164         }
165         
166         private function loginServer() {
167                 $password = $this->getSetting("password");
168                 $this->send("PASS", $password);
169                 $this->send("SERVER", $this->server->getName(), $this->server->getStartTime(), $this->server->getLinkTime(), $this->server->getNumeric(), $this->server->getDescription());
170         }
171         
172         private function parseLine($line) {
173                 $highExplode = explode(" :", $line, 2);
174                 $tokens = explode(" ", $highExplode[0]);
175                 if(count($highExplode) > 1)
176                         $tokens[] = $highExplode[1];
177                 $cmdPos = (($this->flags & self::FLAG_P10SESSION) ? 1 : 0);
178                 if($cmdPos == 1) $from = $tokens[0];
179                 else $from = null;
180                 $arguments = array_slice($tokens, $cmdPos + 1);
181                 switch(strtoupper($tokens[$cmdPos])) {
182                 //pre P10 Session
183                         case "PASS":
184                                 $this->recv_pass($from, $arguments);
185                                 break;
186                         case "SERVER":
187                                 $this->recv_server($from, $arguments);
188                                 break;
189                         case "ERROR":
190                                 $this->recv_error($from, $arguments);
191                                 break;
192                 //P10 Session
193                         case "S":
194                                 $this->recv_server($from, $arguments);
195                                 break;
196                         case "G":
197                                 $this->recv_ping($from, $arguments);
198                                 break;
199                         case "N":
200                                 $this->recv_nick($from, $arguments);
201                                 break;
202                         case "EB":
203                                 $this->recv_end_of_burst($from, $arguments);
204                                 break;
205                         case "EA":
206                                 $this->recv_end_of_burst_ack($from, $arguments);
207                                 break;
208                         case "SQ":
209                                 $this->recv_server_quit($from, $arguments);
210                                 break;
211                         case "Q":
212                                 $this->recv_quit($from, $arguments);
213                                 break;
214                         case "B":
215                                 $this->recv_burst($from, $arguments);
216                                 break;
217                         case "J":
218                         case "C":
219                                 $this->recv_join($from, $arguments);
220                                 break;
221                         case "L":
222                                 $this->recv_part($from, $arguments);
223                                 break;
224                 //default
225                         default:
226                                 //unknown cmd
227                                 break;
228                 }
229         }
230         
231         private function send($command) {
232                 if(func_num_args() > 1) {
233                         $args = array_slice(func_get_args(), 1);
234                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, $args);
235                 } else {
236                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, array());
237                 }
238                 $this->client->send($command);
239         }
240         
241         /********************************************************************************************
242          *                                     INCOMING COMMANDS                                    *
243          ********************************************************************************************/
244         
245         private function recv_pass($from, $args) {
246                 $their_pass = $this->getSetting("their_password");
247                 if($their_pass) {
248                         if($args[0] != $their_pass) {
249                                 //security QUIT
250                                 $this->flags |= self::FLAG_SECURITY_QUIT;
251                                 $this->send("ERROR", "Incorrect password received.");
252                                 $this->client->disconnect();
253                                 return;
254                         }
255                         $this->flags |= self::FLAG_GOT_PASS;
256                 }
257         }
258         
259         private function recv_error($from, $args) {
260                 //we received an error - the socket is dead for us, now
261                 //maybe we want to log this, later
262                 $this->client->disconnect();
263         }
264         
265         private function recv_server($from, $args) {
266                 if($from == null) {
267                         //our uplink Server
268                         $their_name = $this->getSetting("their_name");
269                         if($their_name && $args[0] != $their_name) {
270                                 $this->flags |= self::FLAG_SECURITY_QUIT;
271                                 $this->send("ERROR", "Invalid Server name");
272                                 $this->client->disconnect();
273                                 return;
274                         }
275                         if($this->getSetting("their_password") && !($this->flags & self::FLAG_GOT_PASS)) {
276                                 $this->flags |= self::FLAG_SECURITY_QUIT;
277                                 $this->send("ERROR", "PASS missing.");
278                                 $this->client->disconnect();
279                                 return;
280                         }
281                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $this->server, $args[2], $args[3], $args[7]);
282                         $this->server->addServer($new_server);
283                         $this->flags |= self::FLAG_P10SESSION | self::FLAG_BURST_PENDING;
284                 } else {
285                         //another server got a new slave server ^^
286                         $server = P10_Server::getServerByNum($from);
287                         if($server == null) {
288                                 trigger_error("Parent Server (".$from.") does not exist or was not found on recv_server.", E_USER_ERROR);
289                                 return;
290                         }
291                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $server, $args[2], $args[3], $args[7]);
292                         $server->addServer($new_server);
293                 }
294         }
295         
296         private function recv_ping($from, $args) {
297                 $this->send("Z", $args[0]); //simply PONG
298         }
299         
300         private function recv_nick($from, $args) {
301                 if(count($args) <= 2) {
302                         //Nick change
303                         $user = P10_User::getUserByNum($from);
304                         if($user == null) {
305                                 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);
306                                 return;
307                         }
308                         $nick->setNick($args[0]);
309                 } else {
310                         //New User
311                         $numeric = $args[count($args)-2];
312                         $nick = $args[0];
313                         $server = P10_Server::getServerByNum($from);
314                         if($server == null) {
315                                 trigger_error("Server (".$from.") the User (".$nick.") is coming from does not exist or was not found on recv_nick.", E_USER_ERROR);
316                                 return;
317                         }
318                         if(substr($numeric,0,2) != $from) {
319                                 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);
320                         }
321                         $connect_time = $args[2];
322                         $ident = $args[3];
323                         $host = $args[4];
324                         $modes = implode(" ",array_slice($args, 5, count($args)-8));
325                         $modes = new P10_UserModeSet($modes);
326                         $ip = Numerics::parseIP($args[count($args)-3]);
327                         $realname = $args[count($args)-1];
328                         new P10_User($nick, $numeric, $server, $connect_time, $ident, $host, $ip, $realname, $modes);
329                 }
330         }
331         
332         private function recv_end_of_burst($from, $args) {
333                 if(($this->flags & self::FLAG_BURST_PENDING)) {
334                         $this->burst();
335                         $this->send("EA");
336                         $this->flags &= ~self::FLAG_BURST_PENDING;
337                 }
338         }
339         
340         private function recv_end_of_burst_ack($from, $args) {
341                 $this->flags |= self::FLAG_CONNECTED;
342         }
343         
344         private function recv_server_quit($from, $args) {
345                 $server = P10_Server::getServerByName($args[0]);
346                 if($server == null) {
347                         trigger_error("Server (".$args[0].") not found.", E_USER_ERROR);
348                         return;
349                 }
350                 $server->disconnectServer();
351         }
352         
353         private function recv_quit($from, $args) {
354                 $user = P10_User::getUserByNum($from);
355                 if($user == null) {
356                         trigger_error("Server tries to quit an user that does not exist or was not found on recv_quit.", E_USER_ERROR);
357                         return;
358                 }
359                 $user->quit($args[0]);
360         }
361         
362         private function recv_burst($from, $args) {
363                 $name = $args[0];
364                 $create_time = $args[1];
365                 $channel = P10_Channel::getChannelByName($name);
366                 if($channel == null)
367                         $channel = new P10_Channel($name);
368                 $channel->setCreateTime($create_time);
369                 $modes = $channel->getModes();
370                 $userstr = $args[count($args)-1];
371                 $modeparamcount = count($args)-3;
372                 if($userstr[0] == "%") {
373                         //ban list
374                         $banlist = explode(" ", substr($userstr, 1));
375                         foreach($banlist as $ban) {
376                                 //TODO: save bans
377                         }
378                         $userstr = $args[count($args)-2];
379                         $modeparamcount--;
380                 }
381                 if($userstr[0] == "+") { //MODE String
382                         $modeparamcount++;
383                         $userstr = "";
384                 }
385                 $users = explode(",",$userstr);
386                 $isop = false; $isvoice = false;
387                 foreach($users as $user) {
388                         $uexp = explode(":", $user);
389                         if(strlen($uexp[0]) != 5) {
390                                 trigger_error("burst parse error: '".$uexp[0]."' is not an user numeric.", E_USER_ERROR);
391                                 return;
392                         }
393                         if(count($uexp) > 1) {
394                                 $isop = false;
395                                 $isvoice = false;
396                                 for($i = 0; $i < strlen($uexp[1]); $i++) {
397                                         if($uexp[1][0] == "@") $isop = true;
398                                         if($uexp[1][0] == "+") $isvoice = true;
399                                 }
400                         }
401                         $user = P10_User::getUserByNum($uexp[0]);
402                         if($user == null) {
403                                 trigger_error("burst parse error: cant find User '".$uexp[0]."'.", E_USER_ERROR);
404                                 return;
405                         }
406                         $channel->burstUser($user, $isop, $isvoice);
407                 }
408                 $modes->parseModes(implode(array_slice($args, 2, $modeparamcount)));
409         }
410         
411         private function recv_join($from, $args) {
412                 $user = P10_User::getUserByNum($from);
413                 if($user == null) {
414                         trigger_error("Server tries to join an user that does not exist or was not found on recv_join.", E_USER_ERROR);
415                         return;
416                 }
417                 $channel = P10_Channel::getChannelByName($args[0]);
418                 if($channel == null)
419                         $channel = new P10_Channel($args[0]);
420                 $channel->joinUser($user);
421         }
422         
423         private function recv_part($from, $args) {
424                 $user = P10_User::getUserByNum($from);
425                 if($user == null) {
426                         trigger_error("Server tries to part an user that does not exist or was not found on recv_join.", E_USER_ERROR);
427                         return;
428                 }
429                 $channel = P10_Channel::getChannelByName($args[0]);
430                 if($channel == null)
431                         $channel = new P10_Channel($args[0]);
432                 $channel->partUser($user, $args[1]);
433         }
434         
435         /********************************************************************************************
436          *                                     SERVER FUNCTIONS                                     *
437          ********************************************************************************************/
438         
439         private function burst() {
440                 foreach($this->server->getUsers() as $user) {
441                         $nick = $user->getNick();
442                         $connect_time = $user->getConnectTime();
443                         $ident = $user->getIdent();
444                         $host = $user->getHost();
445                         $modes = $user->getModes()->getModeString();
446                         $ip = Numerics::numericFromIP($user->getIP());
447                         $numeric = $user->getNumeric();
448                         $realname = $user->getRealname();
449                         $this->send("N", $nick, $connect_time, $ident, $host, $modes, $ip, $numeric, $realname);
450                 }
451                 foreach(P10_Channel::getChannels() as $channel) {
452                         $sorted_users = array('ov' => array(), 'o' => array(), 'v' => array(), '-' => array());
453                         $local_users = false;
454                         foreach($channel->getUsers() as $user) {
455                                 if(substr($user->getNumeric(), 0, 2) != $this->server->getNumeric()) continue; //skip users that are not on the local server
456                                 $privs = $channel->getUserPrivs($user);
457                                 $strPrivs = "";
458                                 if(($privs & P10_Channel::USERPRIV_OPED)) $strPrivs .= "o";
459                                 if(($privs & P10_Channel::USERPRIV_VOICE)) $strPrivs .= "v";
460                                 if($strPrivs == "") $strPrivs = "-";
461                                 $local_users = true;
462                                 $sorted_users[$strPrivs][] = $user;
463                         }
464                         if(!$local_users) continue;
465                         $userStr = "";
466                         foreach($sorted_users['-'] as $user) {
467                                 if($userStr != "") $userStr.=",";
468                                 $userStr .= $user->getNumeric();
469                         }
470                         foreach($sorted_users['ov'] as $i => $user) {
471                                 if($userStr != "") $userStr.=",";
472                                 $userStr .= $user->getNumeric();
473                                 if($i == 0) $userStr .= ":ov";
474                         }
475                         foreach($sorted_users['o'] as $i => $user) {
476                                 if($userStr != "") $userStr.=",";
477                                 $userStr .= $user->getNumeric();
478                                 if($i == 0) $userStr .= ":o";
479                         }
480                         foreach($sorted_users['v'] as $i => $user) {
481                                 if($userStr != "") $userStr.=",";
482                                 $userStr .= $user->getNumeric();
483                                 if($i == 0) $userStr .= ":v";
484                         }
485                         $banString = "";
486                         //TODO: Build ban String
487                         $burstString = "";
488                         $modeString = $channel->getModes()->getModeString();
489                         if($modeString != "+") {
490                                 $burstString .= $modeString;
491                         }
492                         if($userStr != "") {
493                                 if($burstString != "") $burstString .= " ";
494                                 $burstString .= $userStr;
495                         }
496                         if($banString != "") {
497                                 if($burstString != "") $burstString .= " ";
498                                 $burstString .= ":%".$banString;
499                         }
500                         $this->send("B", $channel->getName(), $channel->getCreateTime(), $burstString);
501                 }
502                 $this->send("EB");
503         }
504         
505 }
506
507 ?>