<?php
	class RPCVersion2Component extends Component {
		var $llsdapi_actions;
		var $rpcacc;
		var $rpcid;
		var $staging;
		var $debugme;
		var $debugstart;
		var $debugtag;

		/* ugly importer hack. *sigh* */
		function RPCVersion2Component() {
			$this->Component();
			$this->BindLLSDAPIAction("REMOVE", 'RemoveAction');
			$this->BindLLSDAPIAction("ADD", 'AddAction');
			$this->BindLLSDAPIAction("UPDATE", 'UpdateAction');
			$this->BindLLSDAPIAction("LOOKUP", 'LookupAction');
			$this->BindLLSDAPIAction("RECORDS", 'LookupRecords');
			$this->BindLLSDAPIAction("PROXYDUMP", 'ProxyDump');
			$this->BindLLSDAPIAction("TYPELIST", 'TypeList');
		}

		function BindLLSDAPIAction($key, $action) {
			$this->llsdapi_actions[$key] = $action;
		}

		function GetUUIDs() {
			$uuids[] = 'rpc2(\.do){0,1}$';
			return $uuids;
		}

		function FatalError($code, $message, $data='') {
			echo '<?xml version="1.0"?>'.PHP_EOL.
				'<response type="error">'.PHP_EOL.
				tab(1).'<code>'.$code.'</code>'.PHP_EOL.
				tab(1).'<message>'.$message.'</message>'.PHP_EOL.
				(!empty($data) ? tab(1).'<data>'.$data.'</data>'.PHP_EOL : '').
				'</response>'.PHP_EOL;
			die();
		}

		function SuccessMessage($data='') {
			echo '<?xml version="1.0"?>'.PHP_EOL;
			echo '<response type="success"'.(!empty($data) ? '>'.PHP_EOL.$data.'</response' : ' /'). '>'.PHP_EOL;
			die();
		}

		function FormatLLSDObject($objectName, $objectMetadata) {
			$data = tab(1).'<'.$objectName.' ';
			foreach ($objectMetadata as $objectMetadataKey => $objectMetadataValue)
			{
				if (!is_numeric($objectMetadataKey))
					$data .= $objectMetadataKey . '="' . $objectMetadataValue . '" ';
			}
			$data .= '/>'.PHP_EOL;
			return $data;
		}
		
		function UpdateAction($tag, $data) {
			if ($this->debugme) $this->debugtag = microtime(true);
			if (!isset($tag['attributes']['ID']))
			{
				$data .= tab(1).'<warning data="You have not specified the ID to be updated" />'.PHP_EOL;
				return $data;
			}

			$id = intval($tag['attributes']['ID']);

			$tuple = get_db_tuple(get_db_rows("SELECT * FROM blacklist WHERE id='".$id."' LIMIT 1"));
			if (!$tuple)
			{
				$data .= tab(1).'<warning id="'.$id.'" data="The id '.$id.' does not exist" />'.PHP_EOL;
				return $data;
			}
			
			if ($this->debugme) $data .= tab(1).'<debug data="update_idcheck: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			
			if ($tuple['listed'] === 0)
			{
				$data .= tab(1).'<warning id="'.$id.'" data="'.$id.' already delisted and thus cannot be updated" />'.PHP_EOL;
				return $data;
			}
			
			if ($this->debugme) $data .= tab(1).'<debug data="update_listed: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			
			if (!_removeallowed($tuple))
			{
				_activity_log_add(0, 2, "IP <strong>".$tuple['ip']."</strong> attempted to be updated by unauthorized RPC2 call");
				$data .= tab(1).'<warning id="'.$id.'" data="You are not authorized to update this incident" />'.PHP_EOL;
				return $data;
			}
			
			if ($this->debugme) $data .= tab(1).'<debug data="update_allowed: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			
			if (!isset($tag['attributes']['COMMENT']))
			{
				$data .= tab(1).'<warning id="'.$id.'" data="No comment specified, so what is there to update?" />'.PHP_EOL;
				return $data;
			}
			
			$comment = db_escape(strip_tags($tag['attributes']['COMMENT']));
			if (!$this->staging)
			{
				$res = get_db_rows("UPDATE blacklist SET comment='".$comment."', timestamp=now()::abstime::int4 WHERE id='".$id."'");
				_activity_log_add(0, 1, "IP <strong>".$tuple['ip']."</strong> update using RPC2 call.");
			}
			$data .= tab(1).'<success id="'.$id.'" data="Updated '.$id.($this->staging ? ' (simulated)':'').'" />'.PHP_EOL;
				
			if ($this->debugme) $data .= tab(1).'<debug id="'.$id.'" data="update: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			return $data;
		}

		function RemoveAction($tag, $data) {
			if ($this->debugme) $this->debugtag = microtime(true);
			if (!isset($tag['attributes']['ID']))
			{
				$data .= tab(1).'<warning data="You have not specified the ID to be removed" />'.PHP_EOL;
				return $data;
			}

			$id = intval($tag['attributes']['ID']);

			$tuple = get_db_tuple(get_db_rows("SELECT * FROM blacklist WHERE id='".$id."' LIMIT 1"));
			if (!$tuple)
			{
				$data .= tab(1).'<warning id="'.$id.'" data="The id '.$id.' does not exist" />'.PHP_EOL;
				return $data;
			}
			
			if ($this->debugme) $data .= tab(1).'<debug data="remove_idcheck: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			
			if ($tuple['listed'] === 0)
			{
				$data .= tab(1).'<warning id="'.$id.'" data="'.$id.' already delisted" />'.PHP_EOL;
				return $data;
			}
			
			if ($this->debugme) $data .= tab(1).'<debug data="remove_listed: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			if (immutable($tuple['type']))
			{
				_activity_log_add(0, 2, "Immutable IP <strong>".$tuple['ip']."</strong> attempted to be removed by RPC2 call");
				$data .= tab(1).'<warning id="'.$id.'" data="'.$id.' is not removable. Please use the website" />'.PHP_EOL;
				return $data;
			}
			
			if ($this->debugme) $data .= tab(1).'<debug data="remove_immutable: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			
			if (!_removeallowed($tuple))
			{
				_activity_log_add(0, 2, "IP <strong>".$tuple['ip']."</strong> attempted to be removed by unauthorized RPC2 call");
				$data .= tab(1).'<warning id="'.$id.'" data="You are not authorized to remove this incident" />'.PHP_EOL;
				return $data;
			}
			
			if ($this->debugme) $data .= tab(1).'<debug data="remove_allowed: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			if (!$this->staging)
			{
				$res = get_db_rows("UPDATE blacklist SET listed=0,ts_del=".time().",uid_del=".$this->rpcid." WHERE id='".$id."'");
				_activity_log_add(0, 1, "IP <strong>".$tuple['ip']."</strong> removed using RPC2 call.");
			}
			$data .= tab(1).'<success id="'.$id.'" data="Removed '.$id.($this->staging ? ' (simulated)':'').'" />'.PHP_EOL;
			
			if ($this->debugme) $data .= tab(1).'<debug id="'.$id.'" data="remove: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			return $data;
		}

		function ProxyDump($tag, $data)
		{
			if ($this->debugme) $this->debugtag = microtime(true);
			$tmp = array();
			$res = get_db_rows("SELECT ip,port,type,comment,id,listed,timestamp FROM blacklist WHERE listed=1 AND port>0 ORDER BY timestamp DESC;");
			while ($tuple = get_db_tuple($res))
			{
				if (isset($tmp[$tuple['ip']][$tuple['port']]))
					continue;
				$tmp[$tuple['ip']][$tuple['port']] = true;
				$data .= $this->FormatLLSDObject("proxydump", $tuple);
			}
			if ($this->debugme) $data .= tab(1).'<debug data="proxydump: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			return $data;
		}
		
		function TypeList($tag, $data)
		{
			if ($this->debugme) $this->debugtag = microtime(true);
			$res = get_db_rows("SELECT classid AS type, description FROM classes WHERE classid > 2 ORDER BY classid ASC");
			while ($tuple = get_db_tuple($res))
				$data .= $this->FormatLLSDObject("typelist", $tuple);
			if ($this->debugme) $data .= tab(1).'<debug data="typelist: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			return $data;
		}

		function AddAction($tag, $data)
		{
			if ($this->debugme) $this->debugtag = microtime(true);
			$fields = array('listed', 'uid_add');
			$values = array(1, $this->rpcid);

			if (isset($tag['attributes']['IP']))
			{
				$ip = $tag['attributes']['IP'];

				if (!is_valid_ip($ip))
				{
					$data .= tab(1).'<warning ip="'.$ip.'" data="'.$ip.' is not a valid IPv4/IPv6 address." />'.PHP_EOL;
					return $data;
				}
				
				// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="is_valid_ip: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
				
				if (whitelisted($ip))
				{
					$data .= tab(1).'<warning ip="'.$ip.'" data="'.$ip.' is whitelisted." />'.PHP_EOL;
					return $data;
				}
				
				// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="whitelisted: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

				if (_isprivate($ip))
				{
					$data .= tab(1).'<warning ip="'.$ip.'" data="'.$ip.' is a private/unallocated address." />'.PHP_EOL;
					return $data;
				}
				
				// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="_isprivate: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
				
				if (_istor($ip))
				{
					$data .= tab(1).'<warning ip="'.$ip.'" data="'.$ip.' is a tor exit node." />'.PHP_EOL;
					return $data;
				}
				
				// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="_istor: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

				$fields[] = 'ip';
				$values[] = $ip;
			}
			else
			{
				$data .= tab(1).'<warning data="Missing IP parameter." />'.PHP_EOL;
				return $data;
			}
			
			if (isset($tag['attributes']['COMMENT']))
			{
				$fields[] = 'comment';
				$comment = strip_tags($tag['attributes']['COMMENT']);
				$values[] = db_escape(str_replace('"',"'",strip_tags($tag['attributes']['COMMENT'])));
			}

			if (isset($tag['attributes']['TYPE']))
			{
				$type = $tag['attributes']['TYPE'];
				if (!is_valid_type($type))
				{
					$data .= tab(1).'<warning ip="'.$ip.'" data="'.$type.' is not a valid type. Please see http://dronebl.org/classes" />'.PHP_EOL;
					return $data;
				}
				
				// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="is_valid_type: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
				
				// if type = 17 (list scrapes), insert only if not already listed.
				if ($type==17)
				{
					if (_islisted($ip))
					{
						$data .= tab(1).'<warning ip="'.$ip.'" data="'.$ip.' already present. Type 17 does not accept already listed entries" />'.PHP_EOL;
						return $data;
					}

					// Temp hack to make sure scraper doesn't override removals of previous scrapes
					if (isset($comment) && $comment == 'Scraped')
					{
						$tuple = get_db_tuple(get_db_rows("SELECT * FROM blacklist WHERE listed=0 AND ip='".db_escape($ip)."' AND type=17 AND comment='Scraped' LIMIT 1"));
						if ($tuple)
						{
							$data .= tab(1).'<warning ip="'.$ip.'" data="'.$ip.' has already been scraped." />'.PHP_EOL;
							return $data;
						}
					}
					
					// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="type_17: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
				}

				$fields[] = 'type';
				$values[] = $type;
			}
			else
			{
				$data .= tab(1).'<warning ip="'.$ip.'" data="Missing TYPE parameter." />'.PHP_EOL;
				return $data;
			}

			if (isset($tag['attributes']['PORT']))
			{
				$port = intval($tag['attributes']['PORT']);
				if ($port < 1 || $port > 65535)
				{
					$data .= tab(1).'<warning ip="'.$ip.'" data="'.$port.' is an invalid port." />'.PHP_EOL;
					return $data;
				}
				$fields[] = 'port';
				$values[] = $port;
				if (newFilter($ip, $type, $this->rpcid, $port))
				{
					$data .= tab(1).'<warning ip="'.$ip.'" data="You already reported '.$ip.':'.$port.' as type '.$type.'" />'.PHP_EOL;
					return $data;
				}
			}
			else if (newFilter($ip, $type, $this->rpcid))
			{
				$data .= tab(1).'<warning ip="'.$ip.'" data="You already reported '.$ip.' as type '.$type.'" />'.PHP_EOL;
				return $data;
			}
			
			// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="newfilter: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			if ($asn = _getasn($ip))
			{
				$fields[] = 'asn';
				$values[] = $asn;
			}
			
			// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="_getasn: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			if ($country = _getcountry($ip))
			{
				$fields[] = 'country_code';
				$values[] = db_escape($country);
			}
			
			// if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="_getcountry: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			if (!$this->staging)
			{
				$query = "INSERT INTO blacklist (".implode(",", $fields).") VALUES ('".implode("','", $values)."')";
				$res = get_db_rows($query);
				$id = db_insert_id($res);
				if ($id)
				{
					_activity_log_add(0, 1, "IP <strong>".$ip."</strong> added as type <strong>".$type."</strong> by RPC2 call.");
					$data .= tab(1).'<success ip="'.$ip.'" id="'.$id.'" data="Added '.$ip.'" />'.PHP_EOL;
				}
				else
					$data .= tab(1).'<warning ip="'.$ip.'" data="Unable to add '.$ip.' for unknown reason. Contact maintainer." />'.PHP_EOL;
			}
			else
				$data .= tab(1).'<success ip="'.$ip.'" data="Added '.$ip.' (simulated)" />'.PHP_EOL;
				
			if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="add: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
				
			return $data;
		}

		function LookupRecords($tag, $data) {
			$data .= tab(1).'<warning data="this method has been removed. Please replace by lookup with attribute own added" />'.PHP_EOL;
			return $data;
		}

		function LookupAction($tag, $data)
		{
			if ($this->debugme) $this->debugtag = microtime(true);
			if (isset($tag['attributes']['ID']))
			{
				if (is_numeric($tag['attributes']['ID']))
				{
					$id = intval($tag['attributes']['ID']);
					$tuple = get_db_tuple(get_db_rows("SELECT ip,type,comment,id,listed,timestamp FROM blacklist WHERE id='" . $id ."'"));
					$data .= ($tuple ? $this->FormatLLSDObject("result", $tuple) : tab(1).'<warning id="'.$id.'" data="'.$id.' does not exist." />'.PHP_EOL);
				}
				else
					$data .= tab(1).'<warning id="'.$id.'" data="'.$id.' is an invalid id." />'.PHP_EOL;
					
				// if ($this->debugme) $data .= tab(1).'<debug id="'.$id.'" data="idlookup: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
				
				return $data;
			}
			
			// if ($this->debugme) $data .= tab(1).'<debug data="lookup_attr_id: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			
			$comp_op = array();
			if (isset($tag['attributes']['IP']))
			{
				$ip = $tag['attributes']['IP'];

				if (!is_valid_ip($ip))
				{
					list($ip2, $prefix) = explode('/', $ip, 2);
					if (!$prefix)
					{
						$data .= tab(1).'<warning ip="'.$ip.'" data="'.$ip.' is not a valid IPv4/IPv6 address or cidr." />'.PHP_EOL;
						return $data;
					}
					else if (!is_numeric($prefix))
					{
						$data .= tab(1).'<warning ip="'.$ip.'" data="Prefix has to be numeric." />'.PHP_EOL;
						return $data;
					}
					else
						$comp_op[] = "ip::inet << '".$ip."'::cidr";
				}
				else
					$comp_op[] = "ip::inet = '".$ip."'::inet";
			}
			else
			{
				$data .= tab(1).'<warning data="Missing IP or ID parameter." />'.PHP_EOL;
				return $data;
			}
			
			// if ($this->debugme) $data .= tab(1).'<debug data="lookup_attr_ip: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			
			if (isset($tag['attributes']['LISTED']) && is_numeric($tag['attributes']['LISTED']))
			{
				switch ($tag['attributes']['LISTED'])
				{
					case 0: $comp_op[] = "listed=0";
						break;
					case 1: $comp_op[] = "listed=1";
						break;
				}
			}
			
			// if ($this->debugme) $data .= tab(1).'<debug data="lookup_attr_listed: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			
			if (isset($tag['attributes']['OWN']))
			{
				$comp_op[] = "uid_add='".$this->rpcid."'";
			}
			
			// if ($this->debugme) $data .= tab(1).'<debug data="lookup_attr_own: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			if (isset($tag['attributes']['TYPE']) && is_numeric($tag['attributes']['TYPE']))
			{
				$type = intval($tag['attributes']['TYPE']);
				if (!is_valid_type($type))
				{
					$data .= tab(1).'<warning data="'.$type.' is not a valid type. Please see http://dronebl.org/classes" />'.PHP_EOL;
					return $data;
				}
				$comp_op[] = "type=".$type;
			}
			
			// if ($this->debugme) $data .= tab(1).'<debug data="lookup_attr_type: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			if (isset($tag['attributes']['START']) && is_numeric($tag['attributes']['START']))
				$comp_op[] = "timestamp >= ".$tag['attributes']['START'];
				
			// if ($this->debugme) $data .= tab(1).'<debug data="lookup_attr_start: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
				
			if (isset($tag['attributes']['STOP']) && is_numeric($tag['attributes']['STOP']))
				$comp_op[] = "timestamp <= ".$tag['attributes']['STOP'];
				
			// if ($this->debugme) $data .= tab(1).'<debug data="lookup_attr_stop: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			$limit = 1000;
			if (isset($tag['attributes']['LIMIT']) && intval($tag['attributes']['LIMIT'])>0)
				$limit = (intval($tag['attributes']['LIMIT'])>1000?1000:intval($tag['attributes']['LIMIT']));
				
			// if ($this->debugme) $data .= tab(1).'<debug data="lookup_attr_limit: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;

			$res = get_db_rows("SELECT ip,type,comment,id,listed,timestamp FROM blacklist WHERE ".implode(' AND ', $comp_op)." ORDER BY id DESC LIMIT ".$limit);
			while($tuple = get_db_tuple($res))
				$data .= $this->FormatLLSDObject("result", $tuple);
			if ($this->debugme) $data .= tab(1).'<debug ip="'.$ip.'" data="lookup: '.lapseTimer($this->debugtag).'." />'.PHP_EOL;
			return $data;
		}

		function Run($page, $matches)
		{
			$requestText = file_get_contents("php://input");
			$data = '';

			header('Content-Type: text/xml; charset="utf=8"');
			$parser = xml_parser_create();
			xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
			xml_parse_into_struct($parser, $requestText, $values, $tags);
			xml_parser_free($parser);

			foreach ($values as $tag) {
				if ($tag['type'] == 'close')
					continue;

				switch($tag['tag'])
				{
					case "REQUEST":
						$this->debugme = isset($tag['attributes']['DEBUG']);
						if ($this->debugme) $this->debugstart = microtime(true);
						
						if (!isset($tag['attributes']['KEY']))
							$this->FatalError(500, "No RPCKey given.", "You did not specify an RPCKey.");

						$key = db_escape($tag['attributes']['KEY']);
						$tuple = get_db_tuple(get_db_rows("SELECT * FROM rpckey WHERE rpckey='".db_escape($key)."'"));

						if (!$tuple)
							$this->FatalError(403, "Invalid RPCKey given.", "The RPCKey $key was not found in our database.");
						
						// if ($this->debugme) $data .= tab(1).'<debug data="key_lookup: '.lapseTimer($this->debugstart).'." />'.PHP_EOL;

						$this->staging = isset($tag['attributes']['STAGING']);
							
						$this->rpcid = $tuple['id'];
						$_SESSION['uid'] = $tuple['id'];
						$_SESSION['flags'] = $tuple['flags'];
						
						get_db_rows("UPDATE rpckey SET last_used=now()::abstime::int4 WHERE id='".$tuple['id']."'");
						
						if (_hasflag(FLAG_ASADMIN))
						{
							$rows = get_db_rows("SELECT * FROM asadmins WHERE keyid=".$tuple['id'].";");
							$_SESSION['asnum'] = array();
							while ($tuple = get_db_tuple($rows))
								$_SESSION['asnum'][] = $tuple['asnum'];
							// if ($this->debugme) $data .= tab(1).'<debug data="as_loaded: '.lapseTimer($this->debugstart).'." />'.PHP_EOL;
						};
						break;
					default:
						if (empty($this->rpcid))
							$this->FatalError(403, "Invalid RPCKey given.", "You did not specify an rpckey.");

						if (isset($this->llsdapi_actions[$tag['tag']]))
						{
							$functor = $this->llsdapi_actions[$tag['tag']];
							if ($functor != '')
								$data = $this->$functor($tag, $data);
						}
						else
							$data .= tab(1).'<warning data="The tag \''.$tag['tag'].'\' is not supported." />'.PHP_EOL;
				}
			}
			
			if ($this->debugme) $data .= tab(1).'<debug data="request_finish: '.lapseTimer($this->debugstart).'." />'.PHP_EOL;

			$this->SuccessMessage($data);
		}
	};

	new RPCVersion2Component;
?>
