#!/usr/bin/php
<?php
/**
 * scanner
 *
 * no in-script configs, use command line arguments
 * to meet all preconditions (squeeze)
 *   - apt-get install php5-cli socat coreutils
 *   - or udpxy (slow!)
 */
define('RELEASE','6');

// l udpxy: -u 127.0.0.1:8080 -vc >aontv.m3u
// p udpxy: -u 10.0.0.160:4810 -vc -f xspf >aontv.xspf

$args = getParams(array(
	// flags
	'help'			=>	array('-h','--help',null, false),
	'verbose'		=>	array('-v','--verbose',null, false),
	// args
	'mcast'			=>	array('-m','--mcast','%^(239\.[0-9]+\.[0-9]+\.[0-9]+)$%', '239.2.16.0'),
	'format'		=>	array('-f','--format','%^(m3u|csv|xspf|null)$%', 'm3u'),
	'lookup'		=>	array('-l','--lookup','%^[1-9][0-9]*$%', 4096),
	'port'			=>	array('-p','--port','%^([0-9\-]+)$%', 8208),
	'out'			=>	array('-o','--out','%^([^&\|\s\r\n\b;\'"><]+)$%', false),
	'timeout'		=>	array('-t','--timeout','%^[1-9][0-9]*$%', 1),
	'sample'		=>	array('-s','--sample','%^[1-9][0-9]*$%', 4096),
	'udpxy'			=>	array('-u','--udpxy','%^(((?:[0-9]{1,3}\.){3}[0-9]{1,3})\:([0-9]{1,5}))$%', false)
));

/**
 * check preconditions
 */
if($_SERVER['argc'] == 1 || $args['help']) {
	displayHelp();
}
$args['lookup'] = ($args['lookup'] < $args['sample']) ? $args['sample'] : $args['lookup'];
$args['samplesource'] = $args['udpxy'] ? 'udpxy' : 'socat';
$errbin = array();
if (version_compare(PHP_VERSION, '5.2.6') < 1) {
    $errbin[] = 'need at least PHP 5.2.6, you have '.PHP_VERSION;
}
if($args['samplesource'] == 'socat') {
	if(!checkBinary('socat')) {
		$errbin[] = "'socat' not found, please install socat or use udpxy method";

	}
	if(!checkBinary('timeout')) {
		$errbin[] = "'timeout' not found, needs newer GNU coreutils version or timeout itself";
	} else {
		// GNU coreutils binary - or SATAN library timeout?
		exec('timeout >/dev/null 2>&1',$out,$ret);
		$timeouts = array(
			1	=>	array('type' => 'SATAN',	'mask' => 'timeout -{signal} {seconds}'),
			125	=>	array('type' => 'GNU',		'mask' => 'timeout -s {signal} {seconds}'));
		//TODO: change default to GNU in 2011/2012
		$args['ttype'] = isset($timeouts[$ret]) ? $timeouts[$ret] : $timeouts[1];
		unset($timeouts,$out,$ret);
	}
}
if($args['out'] && !$outfilehandle = @fopen($args['out'],'a')) {
	$errbin[] = "could not open your --out=<file> for appending";
}
if(count($errbin) > 0) {
	displayHelp($errbin);
}

/**
 * do it
 */
outputFormat($args['format'],'init');
$start = time();
$stations = 0;
stderr("starting... \n");
$args['port'] = explode('-',$args['port']);
preg_match('%(239\.[0-9]+\.[0-9]+)\.%',$args['mcast'],$m);
$mcast = $m[1];

for($i = 1; $i < 255; $i++) {
	$ip = "$mcast.$i";
	foreach($args['port'] as $port) {
		stderr(sprintf("udp://@%-18s",$ip.":".$port));
		if($content = $args['samplesource'] == 'udpxy' ? getSampleUdpxy($ip,$port,$args) : getSampleSocat($ip,$port,$args)) {
			$stations++;
			$proto = $content['rtp'] ? 'rtp' : 'udp';
			$sdt = analyzeSDT($content['sdt']);
				if(count($sdt['token']) > 1) {
				outputFormat($args['format'],'item',trim($sdt['token'][1]['content']), "$proto://@$ip:".$port);
				stderr(sprintf(' %-40s',trim($sdt['token'][1]['content'])));
			} else {
				outputFormat($args['format'],'item',' - empty service description table - ', "$proto://@$ip:".$port);
				stderr(sprintf(' %-40s',' - empty SDT - '));
			}
//		} else {
//			stderr(sprintf("%80s",' '));
		}
		stderr("\r\n");
	}
}
outputFormat($args['format'],'close');
if($args['out']) {
	fclose($outfilehandle);
}
stderr("found $stations stations in ".(time() - $start)." seconds.".sprintf("%80s",' ')."\n");
exit(0);

/**
 * helper functions
 */

/**
 * check if binary exists and is executable (32/64)
 *
 * very lazy
 *
 * @param	$name	string exploit me
 * @return	bool	exists && works
 */
function checkBinary($name) {
	exec("which $name", &$null, &$ret);
	return $ret == 0;
}

/**
 * output to stderror
 *
 * @param	$string	message line
 */
function stderr($string) {
	global $args;
	if($args['verbose']) {
		file_put_contents('php://stderr',$string);
	}
}

/**
 * output to stdout
 *
 * @param	$string	message line
 */
function stdout($string) {
	global $args, $outfilehandle;
	if($args['out']) {
		fputs($outfilehandle,$string);
	} else {
		echo($string);
	}
}

/**
 * print start,entry,end of format
 *
 * @param	$format	string	(see array)
 * @param	$mode	string	init|item|close
 * @param	$name	string	station name
 * @param	$mcast	string	multicast address
 */
function outputFormat($format,$mode,$name = false,$mcast = false) {
	$fmt = array(
		'init'	=>	array(
			'm3u'	=>	"#EXTM3U\n",
			'xspf'	=>	'<?xml version="1.0" encoding="UTF-8"?>'."\n".
						'<playlist version="1" xmlns="http://xspf.org/ns/0/">'."\n".
						'  <title>aonTV Playlist '.date('Y-m-d H:i')."</title>\n"),
		'item'	=>	array(
			'm3u'	=>	'#EXTINF:0,'.$name."\n$mcast\n",
			'csv'	=>	str_replace(',','',$name).",$mcast\n",
			'xspf'	=>	"  <track><location>$mcast</location><title>$name</title></track>\n"),
		'close'	=>	array(
			'm3u'	=>	"\n#EXT-X-ENDLIST\n",
			'xspf'	=>	"</playlist>\n"));
	if(isset($fmt[$mode][$format])) {
		stdout($fmt[$mode][$format]);
	}
	return false;
}

/**
 * use socat for igmp and mcast dump
 *
 * php's network headers do not support igmp
 * - exec breakout needed anyway
 *
 * @param	$mcast	string	multicast address
 * @param	$args	array	arguments(1): --port
 * @return	mixed	success||array(mcast raw data)
 */
function getSampleSocat($mcast,$mport,$args) {
	$timeout = str_replace(array('{signal}','{seconds}'),array(9,$args['timeout']), $args['ttype']['mask']);

	//arm socat cannot fork properly - only one packet returned
	$cmd="$timeout socat -T=1 UDP4-RECVFROM:$mport,ip-add-membership=$mcast:0.0.0.0,fork -";
//	stderr($cmd);
	$proc=proc_open($cmd,
		array(array('pipe','r'),array('pipe','w'),array('pipe','a')), 
		$sock, getcwd(), array());
	if (!is_resource($proc)) {
		stderr("no resource");
		return false;
	}
	$return = readTSPacket($sock[1],$args);
	fclose($sock[0]);	// close stdin
	fclose($sock[1]);	// close stout
	fclose($sock[2]);	// close stderr - fixes socat SIGINT broken pipe 
	proc_terminate($proc,15);
	`pkill socat`;
	proc_close($proc);
//	stderr($return['sample']);
	return strlen($return['sample']) > 0 ? $return : false;
}

/**
 * getSampleUdpxy
 *
 * use udpxy for igmp and mcast dump
 *
 * @param	$mcast	string	multicast address
 * @param	$port	int		multicast port
 * @return	mixed	success||array(mcast raw data)
 */
function getSampleUdpxy($mcast,$mport,$args) {
	list($host,$port) = explode(':',$args['udpxy']);
	if(!$sock = fsockopen($host,$port)) {
		return false;
	}
	fputs($sock,"GET /udp/$mcast:$mport/ HTTP/1.0\r\n\r\n");
	stream_set_timeout($sock,1);
	stream_set_blocking($sock,true); 
	$header = fgets($sock);	// drop header
	while(strlen(trim($header)) > 0) {
		$header = fgets($sock);
	}
	$return = readTSPacket($sock,$args);
	fclose($sock);
	return strlen($return['sample']) > 0 ? $return : false;
}

/**
 * readTSPacket
 *
 * read data from a transport stream socket
 *
 * @param	$sock	socket	open file handle
 * @return	string	raw data
 */
function readTSPacket($sock,$args) {
	$cnt = 1;
	$return = array(
		'reached'	=>	false,
		'sample'	=>	null,
		'rtp'		=>	null,
		'sdt'		=>	null);
	for($i = 1; $i < $args['lookup']; $i++) {
		// skip rtp headers...
		$j = fread($sock,1);
		if(is_null($return['rtp'])) {
			$return['rtp'] = !($j == 'G');
		}
		while($j != 'G' && !feof($sock)) {
			$j = fread($sock,1);
		}
		$block = 'G'.fread($sock, 187);
		if($block != 'G') {
			if($cnt++ < $args['sample']) {
				$return['sample'] .= $block;
			}
			$pid = @getPid($block);
			if(bin2hex($pid) == '0011') {
				$return['sdt'] = $block;
				if($cnt++ > $args['sample']) {
					$return['reached'] = true;
					break;
				}
			}
		}
	}
	return $return;
}

/**
 * analyzeSDT
 *
 * @see		http://www.dvb.org/technology/standards/a038r5.dvb-si.den300468v1.10.1.pdf
 * @param	$sdt	string	binary packets with pid 0x0011
 * @return	mixed
 */
function analyzeSDT($sdt) {
	$struct = array(
		'sdt'			=>	$sdt,
		'token'			=>	array(),
		'ts_header'		=>	substr($sdt,0,4),
		'sdt_header'	=>	substr($sdt,4,17),
		'scrambled'		=>	(bool) (ord(substr($sdt,20,1)) & 1),	// possibly wrong
		'length'		=>	ord(substr($sdt,22,1))-1);
	$struct['crc32'] = substr($sdt,24+$struct['length'],4);
	$sdt = $struct['payload'] = substr($sdt,24,$struct['length']);
	$run = 0;
	while(strlen($sdt) > 0 && $run++ < 255) {
		$token['length'] = ord($sdt[0]);
		$token['content'] = substr($sdt,1,$token['length']);
		$sdt = substr($sdt,$token['length']+1);
		$struct['token'][] = $token;
	}
	return $struct;
}

/**
 * getPid
 *
 * @param	$block	string	mpeg2ts packet
 * @return	string	12bit PID
 */
function getPid($block) {
	if($block[0] != 'G') {
		stderr("no mpet2ts block");
		return false;
	}
	$pid = $block[1].$block[2];
	$pid = $pid & 31 . $block[2];
	return $pid;
}

/**
 * getParams
 *
 * parse command line parameters
 * flexible, small, works
 * 
 * @param	$paramspec	array	parser instructions
 * 								array(<name> => array($short,$long,$pcre|null,$default))
 * @return	array
 */
function getParams($paramspec) {
	$return = array();
	$argc = $_SERVER['argc'];
	$argv = $_SERVER['argv'];
	for($i = 1; $i < $argc; $i++) {
		if(preg_match('%^-[a-z]{2,}$%i',$argv[$i],$m)) {
			for($j = 1;$j<strlen($argv[$i]); $j++) {
				$argv[] = '-'.substr($argv[$i],$j,1);
				$argc++;
			}
			continue;
		}
		foreach($paramspec as $name=>$ck) {
			if(($argv[$i] == $ck[0] || $argv[$i] == $ck[1])&& 
				(is_null($ck[2]) || ($argc > $i && preg_match($ck[2],$argv[++$i])))) {
				$return[$name] = $argv[$i];
			} 
			if(!is_null($ck[2]) && (preg_match('%^'.$ck[0].'=?'.substr($ck[2],2),$argv[$i],$m) 
				|| preg_match('%^'.$ck[1].'=?'.substr($ck[2],2),$argv[$i],$m))) {
				$return[$name] = $m[1];
			}
		}
	}
	foreach($paramspec as $name=>$ck) {
		$return[$name] = isset($return[$name]) ? 
			($return[$name] == $ck[0] || $return[$name] == $ck[1] ?
			true : $return[$name]) : $ck[3];
	}
	return $return;
}

/**
 * displayHelp
 *
 * display a help message and exit
 *
 * @param	$error	array	optional errors, casted on error
 */
function displayHelp($error = array()) {
	echo("aontv station scanner r".RELEASE."\n");
	$error = is_array($error) ? $error : array($error);
	if(count($error) > 0) {
		echo("stopped: error".(count($error) == 1?null:'s')." occured\n");
		foreach($error as $e) {
			echo("    * $e\n");
		}
		echo("\n");
	} else {
		echo("usage:
    ".$_SERVER['argv'][0]." -chv [arguments] 1>format 2>info
arguments:
    -m  --mcast      multicast /24 network to scan       [239.0.2.0]
    -f  --format     stdout format (m3u|csv|xspf|null)   [m3u]
    -o  --out        file to write                       [stdout]
    -p  --port       multicast port range (8209-8229)    [8208]
    -l  --lookup     search for SDT in X 188 byte blocks [4096]
    -s  --sample     sample size in 188 byte blocks      [4096]
    -t  --timeout    timeout for socat (seconds)         [1]
    -u  --udpxy      use udpxy for samples --SLOW!       [socat]
                     parameter: <ip>:<port>
flags:
    -h  --help       display this help message
    -v  --verbose    verbose output (to stderr)          [no]
examples:
    ".$_SERVER['argv'][0]." --verbose --mcast 239.0.3.0 -p 8209-8229
    ".$_SERVER['argv'][0]." --udpxy 127.0.0.1:4810 >playlist.m3u
    ".$_SERVER['argv'][0]." -f=csv -v -t 2 >scan.csv
    ".$_SERVER['argv'][0]." -v -fcsv -oscan.csv
    ".$_SERVER['argv'][0]." defaults >scan.m3u
    ".$_SERVER['argv'][0]." -p 8209-8229

info:
    - --verbose outputs to stderr (1>your.playlist)
\n");
	}
	exit(count($error) > 0 ? -1 : 125);
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: fdm=marker
 * vim: noet sw=4 ts=4
 */

//EOF

