added EventHandler idea (not implemented, yet)
[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         private $flags = 0;
71         
72         public function __construct() {
73                 $this->client = new Client();
74                 $this->setSetting("recv_timeout", 1000);
75         }
76         
77         public function initialize() {
78                 if($this->server) {
79                         trigger_error("Uplink already initialized.", E_USER_ERROR);
80                         return;
81                 }
82                 $self_numeric = $this->getSetting("numeric");
83                 $self_name = $this->getSetting("name");
84                 $self_description = $this->getSetting("description");
85                 if(!$self_numeric || !$self_name) {
86                         trigger_error("Server Settings missing.", E_USER_ERROR);
87                         return;
88                 }
89                 $this->server = new P10_Server($self_name, $self_numeric, null, time(), time(), $self_description);
90         }
91         
92         public function loop() {
93                 if($this->server == null) {
94                         trigger_error("Uplink not initialized.", E_USER_ERROR);
95                         return;
96                 }
97                 if(!$this->client->connected()) {
98                         if(($this->flags & self::FLAG_P10SESSION)) {
99                                 //Server got disconnected
100                                 $this->server->disconnectServer(true);
101                                 $this->flags &= ~self::FLAG_P10SESSION;
102                         }
103                         $host = $this->getSetting("host");
104                         $port = $this->getSetting("port");
105                         if($host == null || $port == null) {
106                                 trigger_error("Uplink Settings missing.", E_USER_ERROR);
107                                 return;
108                         }
109                         if(($this->flags & self::FLAG_SECURITY_QUIT) || ($this->flags & self::FLAG_NOT_CONNECTABLE)) {
110                                 sleep(1);
111                         }
112                         $state = $this->client->connect($host, $port, $this->getSetting("bind"), $this->getSetting("ssl"), $this->getSetting("recv_timeout"));
113                         if(!$state) {
114                                 usleep($this->getSetting("recv_timeout") / 1000);
115                                 $this->flags |= self::FLAG_NOT_CONNECTABLE;
116                                 return;
117                         }
118                         $this->flags = 0;
119                         $this->loginServer();
120                 }
121                 //try to receive new data from the Uplink
122                 $lines = $this->client->recv();
123                 if($lines == null) return;
124                 foreach($lines as $line) {
125                         $this->parseLine($line);
126                 }
127         }
128         
129         public function setUplinkHost($host, $port, $ssl = false, $bind = null) {
130                 $this->setSetting("host", $host);
131                 $this->setSetting("port", $port);
132                 $this->setSetting("ssl", $ssl);
133                 $this->setSetting("bind", $bind);
134         }
135         
136         public function setLoopTimeout($timeout) {
137                 $this->setSetting("recv_timeout", $timeout);
138         }
139         
140         public function setUplinkServer($numeric, $name, $password, $description) {
141                 $this->setSetting("numeric", Numerics::intToNum($numeric, 2));
142                 $this->setSetting("name", $name);
143                 $this->setSetting("password", $password);
144                 $this->setSetting("description", $description);
145         }
146         
147         public function setValidateServer($name, $password) {
148                 $this->setSetting("their_name", $name);
149                 $this->setSetting("their_password", $password);
150         }
151         
152         private function setSetting($setting, $value) {
153                 $this->settings[$setting] = $value;
154         }
155         
156         private function getSetting($setting) {
157                 if(array_key_exists($setting, $this->settings)) {
158                         return $this->settings[$setting];
159                 } else {
160                         return null;
161                 }
162         }
163         
164         private function loginServer() {
165                 $password = $this->getSetting("password");
166                 $this->send("PASS", $password);
167                 $this->send("SERVER", $this->server->getName(), $this->server->getStartTime(), $this->server->getLinkTime(), $this->server->getNumeric(), $this->server->getDescription());
168         }
169         
170         private function parseLine($line) {
171                 $highExplode = explode(" :", $line, 2);
172                 $tokens = explode(" ", $highExplode[0]);
173                 if(count($highExplode) > 1)
174                         $tokens[] = $highExplode[1];
175                 $cmdPos = (($this->flags & self::FLAG_P10SESSION) ? 1 : 0);
176                 if($cmdPos == 1) $from = $tokens[0];
177                 else $from = null;
178                 $arguments = array_slice($tokens, $cmdPos + 1);
179                 switch(strtoupper($tokens[$cmdPos])) {
180                 //pre P10 Session
181                         case "PASS":
182                                 $this->recv_pass($from, $arguments);
183                                 break;
184                         case "SERVER":
185                                 $this->recv_server($from, $arguments);
186                                 break;
187                         case "ERROR":
188                                 $this->recv_error($from, $arguments);
189                                 break;
190                 //P10 Session
191                         case "S":
192                                 $this->recv_server($from, $arguments);
193                                 break;
194                         case "G":
195                                 $this->recv_ping($from, $arguments);
196                                 break;
197                         case "N":
198                                 $this->recv_nick($from, $arguments);
199                                 break;
200                         case "EB":
201                                 $this->recv_end_of_burst($from, $arguments);
202                                 break;
203                         case "EA":
204                                 $this->recv_end_of_burst_ack($from, $arguments);
205                                 break;
206                         case "SQ":
207                                 $this->recv_server_quit($from, $arguments);
208                                 break;
209                         case "Q":
210                                 $this->recv_quit($from, $arguments);
211                                 break;
212                         case "B":
213                                 $this->recv_burst($from, $arguments);
214                                 break;
215                 //default
216                         default:
217                                 //unknown cmd
218                                 break;
219                 }
220         }
221         
222         private function send($command) {
223                 if(func_num_args() > 1) {
224                         $args = array_slice(func_get_args(), 1);
225                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, $args);
226                 } else {
227                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, array());
228                 }
229                 $this->client->send($command);
230         }
231         
232         /********************************************************************************************
233          *                                     INCOMING COMMANDS                                    *
234          ********************************************************************************************/
235         
236         private function recv_pass($from, $args) {
237                 $their_pass = $this->getSetting("their_password");
238                 if($their_pass) {
239                         if($args[0] != $their_pass) {
240                                 //security QUIT
241                                 $this->flags |= self::FLAG_SECURITY_QUIT;
242                                 $this->send("ERROR", "Incorrect password received.");
243                                 $this->client->disconnect();
244                         }
245                 }
246         }
247         
248         private function recv_error($from, $args) {
249                 //we received an error - the socket is dead for us, now
250                 //maybe we want to log this, later
251                 $this->client->disconnect();
252         }
253         
254         private function recv_server($from, $args) {
255                 if($from == null) {
256                         //our uplink Server
257                         $their_name = $this->getSetting("their_name");
258                         if($their_name && $args[0] != $their_name) {
259                                 $this->flags |= self::FLAG_SECURITY_QUIT;
260                                 $this->send("ERROR", "Invalid Server name");
261                                 $this->client->disconnect();
262                                 return;
263                         }
264                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $this->server, $args[2], $args[3], $args[7]);
265                         $this->server->addServer($new_server);
266                         $this->flags |= self::FLAG_P10SESSION | self::FLAG_BURST_PENDING;
267                 } else {
268                         //another server got a new slave server ^^
269                         $server = P10_Server::getServerByNum($from);
270                         if($server == null) {
271                                 trigger_error("Parent Server (".$from.") does not exist or was not found on recv_server.", E_USER_ERROR);
272                                 return;
273                         }
274                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $server, $args[2], $args[3], $args[7]);
275                         $server->addServer($new_server);
276                 }
277         }
278         
279         private function recv_ping($from, $args) {
280                 $this->send("Z", $args[0]); //simply PONG
281         }
282         
283         private function recv_nick($from, $args) {
284                 if(count($args) <= 2) {
285                         //Nick change
286                         $user = P10_User::getUserByNum($from);
287                         if($user == null) {
288                                 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);
289                                 return;
290                         }
291                         $nick->setNick($args[0]);
292                 } else {
293                         //New User
294                         $numeric = $args[count($args)-2];
295                         $nick = $args[0];
296                         $server = P10_Server::getServerByNum($from);
297                         if($server == null) {
298                                 trigger_error("Server (".$from.") the User (".$nick.") is coming from does not exist or was not found on recv_nick.", E_USER_ERROR);
299                                 return;
300                         }
301                         if(substr($numeric,0,2) != $from) {
302                                 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);
303                         }
304                         $connect_time = $args[2];
305                         $ident = $args[3];
306                         $host = $args[4];
307                         $modes = implode(" ",array_slice($args, 5, count($args)-8));
308                         $modes = new P10_UserModeSet($modes);
309                         $ip = Numerics::parseIP($args[count($args)-3]);
310                         $realname = $args[count($args)-1];
311                         new P10_User($nick, $numeric, $server, $connect_time, $ident, $host, $ip, $realname, $modes);
312                 }
313         }
314         
315         private function recv_end_of_burst($from, $args) {
316                 if(($this->flags & self::FLAG_BURST_PENDING)) {
317                         $this->burst();
318                         $this->send("EA");
319                         $this->flags &= ~self::FLAG_BURST_PENDING;
320                 }
321         }
322         
323         private function recv_end_of_burst_ack($from, $args) {
324                 //nothing to do here?
325         }
326         
327         private function recv_server_quit($from, $args) {
328                 $server = P10_Server::getServerByName($args[0]);
329                 if($server == null) {
330                         trigger_error("Server (".$args[0].") not found.", E_USER_ERROR);
331                         return;
332                 }
333                 $server->disconnectServer();
334         }
335         
336         private function recv_quit($from, $args) {
337                 $user = P10_User::getUserByNum($from);
338                 if($user == null) {
339                         trigger_error("Server tries to quit an user that does not exist or was not found on recv_quit.", E_USER_ERROR);
340                         return;
341                 }
342                 $user->quit($args[0]);
343         }
344         
345         private function recv_burst($from, $args) {
346                 $name = $args[0];
347                 $create_time = $args[1];
348                 $channel = P10_Channel::getChannelByName($name);
349                 if($channel == null)
350                         $channel = new P10_Channel($name);
351                 $modes = $channel->getModes();
352                 $userstr = $args[count($args)-1];
353                 $modeparamcount = count($args)-3;
354                 if($userstr[0] == "%") {
355                         //ban list
356                         $banlist = explode(" ", substr($userstr, 1));
357                         foreach($banlist as $ban) {
358                                 //TODO: save bans
359                         }
360                         $userstr = $args[count($args)-2];
361                         $modeparamcount--;
362                 }
363                 $users = explode(",",$userstr);
364                 $isop = false; $isvoice = false;
365                 foreach($users as $user) {
366                         $uexp = explode(":", $user);
367                         if(strlen($uexp[0]) != 5) {
368                                 trigger_error("burst parse error: '".$uexp[0]."' is not an user numeric.", E_USER_ERROR);
369                                 return;
370                         }
371                         if(count($uexp) > 1) {
372                                 $isop = false;
373                                 $isvoice = false;
374                                 for($i = 0; $i < strlen($uexp[1]); $i++) {
375                                         if($uexp[1][0] == "@") $isop = true;
376                                         if($uexp[1][0] == "+") $isvoice = true;
377                                 }
378                         }
379                         $user = P10_User::getUserByNum($uexp[0]);
380                         if($user == null) {
381                                 trigger_error("burst parse error: cant find User '".$uexp[0]."'.", E_USER_ERROR);
382                                 return;
383                         }
384                         $channel->burstUser($user, $isop, $isvoice);
385                 }
386                 $modes->parseModes(implode(array_slice($args, 2, $modeparamcount)));
387         }
388         
389         /********************************************************************************************
390          *                                     SERVER FUNCTIONS                                     *
391          ********************************************************************************************/
392         
393         private function burst() {
394                 foreach($this->server->getUsers() as $user) {
395                         $nick = $user->getNick();
396                         $connect_time = $user->getConnectTime();
397                         $ident = $user->getIdent();
398                         $host = $user->getHost();
399                         $modes = $user->getModes()->getModeString();
400                         $ip = Numerics::numericFromIP($user->getIP());
401                         $numeric = $user->getNumeric();
402                         $realname = $user->getRealname();
403                         $this->send("N", $nick, $connect_time, $ident, $host, $modes, $ip, $numeric, $realname);
404                 }
405                 $this->send("EB");
406         }
407         
408 }
409
410 ?>