IRCRelay/Sourcecode

From Qontrol.nl Wiki
Jump to: navigation, search
#!/usr/bin/php
<?php
/* Copyright 2010 Ivo Smits <Ivo@UCIS.nl>. All rights reserved.
   Redistribution and use in source and binary forms, with or without modification, are
   permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, this list of
      conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice, this list
      of conditions and the following disclaimer in the documentation and/or other materials
      provided with the distribution.

   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

   The views and conclusions contained in the software and documentation are those of the
   authors and should not be interpreted as representing official policies, either expressed
   or implied, of Ivo Smits.*/

print("UCIS IRC Relay bot (c) 2010 Ivo Smits <Ivo@UCIS.nl>\n");
print("More information: http://wiki.qontrol.nl/IRCRelay\n");
print("\n");

class Network {
	public $key = NULL;
	public $name = NULL;
	public $socket = NULL;
	public $server = NULL;
	public $port = 6667;
	public $nick = NULL;
	public $realnick = NULL;
	public $connected = FALSE;
	public $connecting = FALSE;
	public $timeout = 0;
	public $channels = array();
	public $addressfamily = AF_INET;
	public $active = FALSE;
	public $ident = 'none';
	public $realname = 'Not set - http://wiki.qontrol.nl/IRCRelay';
	public $debug = FALSE;
}
class NetworkChannel {
	public $network;
	public $channel;
	public $name;
	public $display;
}
class Channel {
	public $name = NULL;
	public $links = array();
	public function __construct($name) { $this->name = $name; }
}

$networks = array();
$channels = array();
$status = NULL;
$adminpass = NULL;

prepare();
configure();
init();
readloop();

function getchannel($name) {
	global $channels;
	if (array_key_exists($name, $channels)) return $channels[$name];
	$ch = new Channel($name);
	$channels[$name] = $ch;
	return $ch;
}
function configure() {
	global $networks;
	global $channels;
	global $adminpass;

	print("Loading configuration...\n");
	require 'config.php';

	if (isset($config['password'])) $adminpass = $config['password'];
	foreach ($config['networks'] as $key => $nc) {
		$net = new Network();
		$net->key = $key;
		$net->server = $nc['server'];
		$net->nick = $nc['nick'];
		$net->name = isset($nc['name']) ? $nc['name'] : $key;
		if (isset($nc['port'])) $net->port = $nc['port'];
		if (isset($nc['ident'])) $net->ident = $nc['ident'];
		if (isset($nc['realname'])) $net->realname = $nc['realname'];
		if (isset($nc['ipv6']) && $nc['ipv6']) $net->addressfamily = AF_INET6;
		if (isset($nc['debug']) && $nc['debug']) $net->debug = TRUE;
		foreach ($nc['channels'] as $chn => $cf) {
			$ch = getchannel($cf['link']);
			$nch = new NetworkChannel();
			$nch->name = $chn;
			$nch->network = $net;
			$nch->channel = $ch;
			$nch->display = isset($cf['display']) ? $cf['display'] : $net->key;
			$ch->links[] = $nch;
			$net->channels[$chn] = $nch;
		}
		$networks[$key] = $net;
		$net->active = TRUE;
		print('NET '.$net->key.' create'."\n");
	}
}

function prepare() {
	global $channels, $status;
	print("Starting IRC Relay...\n");
	$ch = new Channel('status');
	$channels[$ch->name] = $ch;
	$status = $ch;
}

function init() {
	global $networks;
	print("Initializing...\n");
}

function readloop() {
	global $networks;

	$ltime = 0;

	print("Running\n");
	while (TRUE) {
		$selread = array();
		$selwrite = array();
		$selerror = array();
		$selcount = 0;

		$ntime = time();
		$tdiff = $ntime - $ltime;
		$ltime = $ntime;

		foreach ($networks as $net) {
			if ($net->connected) {
				$selread[] = $net->socket;
				$selerror[] = $net->socket;
				$selcount++;
			} else if ($net->connecting) {
				$selwrite[] = $net->socket;
				$selerror[] = $net->socket;
				$selcount++;
			} else if ($net->active) {
				$net->timeout -= $tdiff;
				if ($net->timeout <= 0) {
					$net->connecting = TRUE;
					print('NET '.$net->key.' connect '.$net->server.':'.$net->port."\n");
					$net->socket = socket_create($net->addressfamily, SOCK_STREAM, SOL_TCP);
					socket_set_nonblock($net->socket);
					socket_connect($net->socket, $net->server, $net->port);
					$selwrite[] = $net->socket;
					$selerror[] = $net->socket;
				}
			}
		}

		if (!$selcount) {
			sleep(1);
			continue;
		}

		socket_select(&$selread, &$selwrite, &$selerror, 10);

		foreach ($networks as $net) {
			if (in_array($net->socket, $selerror)) {
				print('NET '.$net->key.' socket error'."\n");
				network_reset($net);
			} else if ($net->connected && in_array($net->socket, $selread)) {
				if (!network_read($net)) {
					print('NET '.$net->key.' read error'."\n");
					network_reset($net);
				}
			} else if ($net->connecting && in_array($net->socket, $selwrite)) {
				$net->connected = TRUE;
				$net->connecting = FALSE;
				print('NET '.$net->key.' identify '.$net->nick."\n");
				network_send($net, 'USER '.$net->ident.' host server :'.$net->realname);
				network_send($net, 'NICK '.$net->nick);
			}
		}
	}
}

function network_reset($net) {
	print('NET '.$net->key.' reset'."\n");
	socket_close($net->socket);
	$net->connected = FALSE;
	$net->connecting = FALSE;
	$net->readbuffer = '';
	$net->timeout = 60;
}

function network_read($net) {
	$newdata = socket_read($net->socket, 1024);
	if ($newdata === FALSE || !strlen($newdata)) return FALSE;
	$net->readbuffer .= $newdata;
	$offset = 0;
	$len = strlen($net->readbuffer);
	while ($offset < $len) {
		$posa = strpos($net->readbuffer, "\n", $offset);
		$posb = strpos($net->readbuffer, "\r", $offset);
		if ($posa !== FALSE && $posb !== FALSE) {
			$pos = min($posa, $posb);
		} else if ($posa !== FALSE) {
			$pos = $posa;
		} else if ($posb !== FALSE) {
			$pos = $posb;
		} else {
			break;
		}
		$line = substr($net->readbuffer, $offset, $pos - $offset);
		if (strlen($line)) {
			if (!network_process($net, $line)) return FALSE;
		}
		$offset = $pos + 1;
	}
	if ($offset == $len) {
		$net->readbuffer = '';
	} else if ($offset != 0) {
		$net->readbuffer = substr($net->readbuffer, $offset);
	}
	return TRUE;
}

function network_process($net, $line) {
	global $adminpass;
	if ($net->debug) print('NET '.$net->key.' recv '.$line."\n");
	$partsa = explode(' :', $line, 2);
	$parts = explode(' ', $partsa[0]);
	if ($parts[0][0] == ':') {
		$sender = substr(array_shift(&$parts), 1);
	} else {
		$sender = NULL;
	}
	$command = array_shift(&$parts);
	if (count($partsa) > 1) array_push(&$parts, $partsa[1]);
	$partsa = explode('!', $sender);
	$sendernick = $partsa[0];
	switch (strtoupper($command)) {
		case '001': //Welcome
			$net->realnick = $parts[0];
			print('NET '.$net->key.' welcome '.$net->realnick."\n");
			foreach ($net->channels as $ch) network_send($net, "JOIN :".$ch->name);
			break;
		case '433': //Nickname in use
			print('NET '.$net->key.' nickname_in_use'."\n");
			network_send($net, "NICK ".$net->nick.rand(100,999));
			break;
		case 'NICK': //Nickname change
			if (strcasecmp($sendernick, $net->realnick)) {
				$net->realnick = $parts[0];
				print('NET '.$net->key.' nickname '.$net->realnick."\n");
			}
			break;
		case 'PING':
			network_send($net, 'PONG :'.$parts[0]);
			break;
		case 'PRIVMSG':
		case 'NOTICE':
			if ($parts[0][0] == '#') {
				$to = $parts[0];
			} else {
				$to = $sendernick;
				if (!is_null($adminpass) && $parts[1][0] == '.' && substr($parts[1], 1, strlen($adminpass)) === $adminpass) {
					$ret = admincmd(array_slice(explode(' ', $parts[1]), 1));
					network_send($net, 'PRIVMSG '.$to.' :'.$ret);
					break;
				} 
			}
			if (!array_key_exists($to, $net->channels)) {
				print('NET '.$net->key.' privmsg '.$sendernick.' @ '.$to.' - '.$parts[1]."\n");
				break;
			}
			$ch = $net->channels[$to];
			$prefix = '['.$sendernick.(is_null($ch->display) ? '' : ' @ '.$ch->display).'] ';
			if (ord($parts[1][0]) == 1) { //CTCP
				if (substr($parts[1], 1, 6) != 'ACTION') break;
				$msg = chr(1).'ACTION '.$prefix.substr($parts[1], 8, -1).chr(1);
			} else {
				$msg = $prefix.$parts[1];
			}
			channel_send($ch->channel, $msg, $ch, $command == 'NOTICE');
			break;
		case '372': //Motd
		case '376': //End of moth
		case '002': //Your host
		case '003': //This server
		case '004': //Version
		case '005': //Supported
		case '422': //Motd missing
		case '251': case '254': case '255': case '265': case '266': case '396': case '353': case '366':
		case '252': case '375':
		case 'MODE':
		case 'JOIN':
		case 'PART':
		case 'QUIT':
			break;
		default:
			print('NET '.$net->key.' unknown '.$line."\n");
	}
	return TRUE;
}

function network_send($net, $line) {
	if ($net->debug) print('NET '.$net->key.' send '.$line."\n");
	$line .= "\r\n";
	socket_send($net->socket, $line, strlen($line), 0);
}

function channel_send($ch, $message, $source = NULL, $notice = FALSE) {
	foreach ($ch->links as $link) {
		if ($link->network->connected && $link !== $source) {
			network_send($link->network, ($notice ? 'NOTICE ' : 'PRIVMSG ').$link->name.' :'.$message);
		}
	}
}

function admincmd($parts) {
	global $channels, $networks;
	switch (strtolower($parts[0])) {
		case 'die': exit(0);
		case 'c': case 'chn': case 'chan': case 'channel':
			switch (strtolower($parts[1])) {
				case 'join': case 'part': case 'rejoin': case 'msg': case 'links':
					if (!isset($channels[$parts[2]])) return 'ERR Channel does not exist';
					return admincmd_channel($parts[1], $channels[$parts[2]], array_slice($parts, 3));
				case 'list': return 'OK '.implode('; ', array_keys($channels));
				case 'help':
					return 'OK list; links [ch]; join [ch]; part [ch]; rejoin [ch]; msg [ch] [msg]; help';
			}
			break;
		case 'n': case 'net': case 'network':
			switch (strtolower($parts[1])) {
				case 'disconnect': case 'raw': case 'join': case 'part': case 'rejoin': case 'msg': case 'delete': case 'info': case 'status': case 'channels': case 'set': case 'active': case 'ipv6': case 'link': case 'unlink': case 'linkinfo':
					if (!isset($networks[$parts[2]])) return 'ERR Network does not exist';
					return admincmd_network($parts[1], $networks[$parts[2]], array_slice($parts, 3));
				case 'list': return 'OK '.implode('; ', array_keys($networks));
				case 'help':
					return 'OK list; disconnect [net]; raw [net] [text]; join [net] [ch]; part [net] [ch]; rejoin [net] [ch]; msg [net] [ch] [msg]; help; delete; info; status; channels; set [name] [server] [port] [nick]; active [enable]; ipv6 [enable]; link [name] [channel] [display]; unlink [name]; linkinfo [name]';
			}
			break;
		case 'help':
			return 'OK die; channel help; network help';
	}
	return 'ERR Unknown command';
}

function admincmd_channel($cmd, $chn, $parts) {
	switch (strtolower($cmd)) {
		case 'links':
			$arr = array();
			foreach ($chn->links as $link) $arr[] = $link->network->key.'/'.$link->name;
			return 'OK '.implode('; ', $arr);
		case 'join':
			foreach ($chn->links as $link) if ($link->network->connected) network_send($link->network, 'JOIN '.$link->name);
			return 'OK';
		case 'part':
			foreach ($chn->links as $link) if ($link->network->connected) network_send($link->network, 'PART '.$link->name);
			return 'OK';
		case 'rejoin':
			foreach ($chn->links as $link) if ($link->network->connected) network_send($link->network, 'PART '.$link->name);
			foreach ($chn->links as $link) if ($link->network->connected) network_send($link->network, 'JOIN '.$link->name);
			return 'OK';
		case 'msg':
			foreach ($chn->links as $link) if ($link->network->connected) network_send($link->network, 'PRIVMSG '.$link->name.' :'.implode(' ', array_slice($parts, 0)));
			return 'OK';
	}
	return 'ERR Unknown command';
}
function admincmd_network($cmd, $net, $parts) {
	global $channels;
	switch (strtolower($cmd)) {
		case 'disconnect':
			network_reset($net);
			return 'OK';
		case 'raw':
			network_send($net, implode(' ', array_slice($parts, 0)));
			return 'OK';
		case 'join':
			network_send($net, 'JOIN '.$parts[0]);
			return 'OK';
		case 'part':
			network_send($net, 'PART '.$parts[0]);
			return 'OK';
		case 'rejoin':
			network_send($net, 'JOIN '.$parts[0]);
			network_send($net, 'PART '.$parts[0]);
			return 'OK';
		case 'msg':
			network_send($net, 'PRIVMSG '.$parts[0].' :'.implode(' ', array_slice($parts, 1)));
			return 'OK';
		case 'delete':
			network_Reset($net);
			unset($networks[$net->key]);
			return 'OK';
		case 'info':
			return 'OK key='.$net->key.'; name='.$net->name.'; server='.$net->server.'; port='.$net->port.'; nick='.$net->nick.'; active='.$net->active.'; af='.$net->addressfamily;
		case 'status':
			return 'OK connected='.$net->connected.'; connecting='.$net->connecting.'; timeout='.$net->timeout.'; nick='.$net->realnick;
		case 'channels':
			return 'OK '.implode('; ', array_keys($net->channels));
		case 'set':
			$net->name = $parts[0];
			$net->server = $parts[1];
			$net->port = (int)$parts[2];
			$net->nick = $parts[3];
			return 'OK';
		case 'active':
			$net->active = $parts[0];
			return 'OK';
		case 'ipv6':
			$net->addressfamily = $parts[0] ? AF_INET6 : AF_INET;
			return 'OK';
		case 'link':
			if (isset($net->channels[$parts[0]])) return 'ERR Channel already linked';
			$link = new NetworkChannel();
			$link->name = $parts[0];
			$link->network = $net;
			$link->channel = getchannel($parts[1]);
			$link->display = implode(' ', array_slice($parts, 2));
			$link->channel->links[] = $link;
			$net->channels[$link->name] = $link;
			if ($net->connected && $link->name[0] == '#') network_send($net, 'JOIN '.$link->name);
			return 'OK';
		case 'unlink':
			if (!isset($net->channels[$parts[0]])) return 'ERR Channel not linked';
			$link = $net->channels[$parts[0]];
			unset($net->channels[$link->name]);
			foreach ($link->channel->links as $k => $l) if ($l === $link) unset($link->channel->links[$k]);
			if (!count($link->channel->links)) unset($channels[$link->channel->name]);
			if ($net->connected && $link->name[0] == '#') network_send($net, 'PART '.$link->name);
			return 'OK';
		case 'linkinfo':
			if (!isset($net->channels[$parts[0]])) return 'ERR Channel not linked';
			$link = $net->channels[$parts[0]];
			return 'OK channel='.$link->channel->name.'; display='.$link->display;
	}
	return 'ERR Unknown command';
}