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