view common.php @ 14:372f4e195986 draft default tip

Added article blacklist function, switch to binary-safe latin1 character set for database
author Ivo Smits <Ivo@UCIS.nl>
date Thu, 17 Jul 2014 23:24:17 +0200
parents cccd73f72bf6
children
line wrap: on
line source

<?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.*/

$pnewss_hooks = array('article_stored' => array(), 'article_filter' => array());

require_once './pdo.php';
require_once './config.php';

function nntp_readline($socket) {
	$line = fgets($socket);
	if ($line === FALSE || $line === NULL) return $line;
	$line = rtrim($line, "\r\n");
	writelog('R: '.$line);
	return $line;
}
function nntp_writeline_data($socket, $line) {
	if (strlen($line) && $line[0] == '.') $line = '.'.$line;
	nntp_writeline($socket, $line);
}
function nntp_writeline($socket, $line) {
	writelog('W: '.$line);
	$line .= "\r\n";
	while (strlen($line)) {
		$written = fwrite($socket, $line);
		if ($written === FALSE || $written <= 0) throw new Exception('Write operation failed');
		$line = substr($line, $written);
	}
}
function nntp_readlines($socket) {
	$line = nntp_readline($socket);
	$lines = array();
	while ($line != '.' && $line !== FALSE && $line !== FALSE) {
		if (strlen($line) && $line[0] == '.') $line = substr($line, 1);
		$lines[] = $line;
		$line = nntp_readline($socket);
	}
	if ($line != '.') throw new Exception('Unexpected end of message');
	return $lines;
}

function pnewss_call_hooks($hooks, $args) {
	foreach ($hooks as $hook) call_user_func_array($hook, $args);
}
function pnewss_call_filter_hooks($hooks, $args) {
	foreach ($hooks as $hook) if (!call_user_func_array($hook, $args)) return FALSE;
	return TRUE;
}

function nntp_article_wanted($messageid) {
	global $db, $pnewss_hooks;
	if ($db->evalRow('SELECT `id` FROM `messages` WHERE `messageid` = ?', $messageid) !== FALSE) return FALSE;
	if ($db->evalRow('SELECT * FROM `blacklist` WHERE `messageid` = ?', $messageid) !== FALSE) return FALSE;
	if (!pnewss_call_filter_hooks($pnewss_hooks['article_filter'], array(array('messageid' => $messageid)))) return FALSE;
	return TRUE;
}

function nntp_article_store($lines, $header = array()) {
	global $db, $pnewss_hooks;
	$headers = array();
	if (!count($header)) {
		while (count($lines)) {
			$line = array_shift($lines);
			if (!strlen($line)) break;
			$header[] = $line;
		}
	}
	$headername = NULL;
	foreach ($header as $headerid => $line) {
		if (!strlen($line)) throw new Exception('Empty header line');
		if (strpos($line, "\r") !== FALSE || strpos($line, "\n") !== FALSE || strpos($line, "\0")) throw new Exception('Invalid newline or NUL character in header line');
		if (strlen($line) && strlen($headername) && ($line[0] == ' ' || $line[0] == "\t") && isset($headers[$headername])) {
			$headers[$headername] .= ' '.trim($line, " \t");
			unset($header[$headerid]);
			continue;
		}
		$parts = explode(': ', $line, 2);
		$headername = strtoupper($parts[0]);
		switch ($headername) {
			case 'PATH': case 'FROM': case 'NEWSGROUPS': case 'SUBJECT': case 'DATE': case 'MESSAGE-ID': case 'SENDER':
				if (isset($headers[$headername])) throw new Exception('Duplicate header: '.$headername);
				$headers[$headername] = $parts[1];
				unset($header[$headerid]);
				break;
			case 'ORGANIZATION': case 'LINES':
			case 'MIME-VERSION': case 'CONTENT-TYPE': case 'CONTENT-TRANSFER-ENCODING': case 'USER-AGENT':
			case 'REFERENCES': case 'REPLY-TO': case 'FOLLOWUP-TO': case 'IN-REPLY-TO':
			case 'EXPIRES': case 'CONTROL': case 'DISTRIBUTION': case 'KEYWORDS': case 'SUMMARY':
				break;
			case 'NNTP-POSTING-HOST': case 'X-TRACE': case 'XREF': case 'X-COMPLAINTS-TO':
			case 'NNTP-POSTING-DATE':
				unset($header[$headerid]);
				$line = NULL;
				break;
			default:
				if ($headername[0] == 'X' && $headername[1] == '-') break;
				writelog("Received unknown header $headername");
		}
	}
	foreach ($lines as $line) {
		if (strpos($line, "\r") !== FALSE || strpos($line, "\n") !== FALSE || strpos($line, "\0")) throw new Exception('Invalid newline or NUL character in body line');
	}
	if (!isset($headers['NEWSGROUPS'])) throw new Exception('Missing required Newsgroups header');
	$newsgroups = array();
	foreach (explode(',', $headers['NEWSGROUPS']) as $groupname) {
		$group = $db->evalRowAssoc('SELECT * FROM `groups` WHERE `name` = ?', $groupname);
		if ($group === FALSE) continue;
		$newsgroups[] = $group['id'];
	}
	if (!count($newsgroups)) throw new Exception('No known newsgroups listed');
	if (!isset($headers['MESSAGE-ID'])) $headers['MESSAGE-ID'] = '<'.md5(time().rand()).'@pNewss.Core.UCIS.nl>';
	if (!isset($headers['DATE'])) $headers['DATE'] = gmdate('r');
	$messageid = $headers['MESSAGE-ID'];
	if (strlen($messageid) < 3 || strlen($messageid) > 250 || $messageid[0] != '<' || strpos($messageid, '>') !== strlen($messageid) - 1) throw new Exception('Bad Message-ID');
	$messageid = substr($messageid, 1, -1);
	$article = $db->evalRowAssoc('SELECT * FROM `messages` WHERE `messageid` = ?', $messageid);
	if ($article !== FALSE) throw new Exception('Duplicate');
	if ($db->evalRow('SELECT * FROM `blacklist` WHERE `messageid` = ?', $messageid) !== FALSE) throw new Exception('Blacklisted Message-ID');
	$headers['PATH'] = 'pNewss.Core.UCIS.nl'.(isset($headers['PATH'])?'!'.$headers['PATH']:'');
	foreach (array('Path', 'From', 'Newsgroups', 'Subject', 'Date', 'Message-ID', 'Sender') as $headername) {
		if (isset($headers[strtoupper($headername)])) $header[] = $headername.': '.$headers[strtoupper($headername)];
	}
	if (!pnewss_call_filter_hooks($pnewss_hooks['article_filter'], array(array('messageid' => $messageid, 'headers' => $headers, 'body' => $lines)))) throw new Exception('Filtered');
	$headertext = implode("\r\n", $header);
	$bodytext = implode("\r\n", $lines);
	if (strlen($messageid) > 255 || strlen($headertext) > 65535 || strlen($bodytext) > 16777215) throw new Exception('Message too big');
	$id = $db->insert('INSERT INTO `messages` (`messageid`, `header`, `body`) VALUES (?, ?, ?)', array($messageid, $headertext, $bodytext));
	foreach ($newsgroups as $groupid) $db->insert('INSERT INTO `groupmessages` (`group`, `message`) VALUES (?, ?)', array($groupid, $id));
	pnewss_call_hooks($pnewss_hooks['article_stored'], array(array('messageid' => $messageid, 'headers' => $headers, 'body' => $lines, 'dbid' => $id)));
	return $messageid;
}