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