#!/usr/bin/php
<?php

$cookiepath = "/etc/tor/control_auth_cookie";
$controlport = 9051;


// Nothing to change down here...

$cmd = $argv['1'];

$cookie = file_get_contents($cookiepath);


if ($cmd == "config") {

	print "graph_title Connections\n";
	print "graph_args -l 0 --base 1000\n";
	print "graph_vlabel connections\n";
	print "graph_category network\n";
	print "graph_info This graph shows the number of Tor OR connections.\n";
	print "graph_period second\n";

	print "new.label new\n";
	print "new.type GAUGE\n";
	print "new.max 50000\n";
	print "new.min 0\n";

        print "launched.label launched\n";
        print "launched.type GAUGE\n";
        print "launched.max 50000\n";
        print "launched.min 0\n";

        print "connected.label connected\n";
        print "connected.type GAUGE\n";
        print "connected.max 50000\n";
        print "connected.min 0\n";

        print "failed.label failed\n";
        print "failed.type GAUGE\n";
        print "failed.max 50000\n";
        print "failed.min 0\n";

        print "closed.label closed\n";
        print "closed.type GAUGE\n";
        print "closed.max 50000\n";
        print "closed.min 0\n";



	exit;

} elseif ($cmd == "autoconf") {

	$socket = fsockopen("tcp://127.0.0.1", $controlport);
	fputs($socket, "AUTHENTICATE \"".$cookie."\"\n");

	$buffer = fgets($socket, 1024);
	if (ereg("250", $buffer)) echo "Yes";
	else echo "No (".trim($buffer).")";

	fclose($socket);
	exit;


}



$socket = fsockopen("tcp://127.0.0.1", $controlport);

fputs($socket, "AUTHENTICATE \"".$cookie."\"\n");

$buffer .= fgets($socket, 4096);

if (!ereg("250", $buffer)) {
	echo "Unable to connect to Tor ControlPort (".$buffer.")";
	fclose($socket);
	exit;
} else {

	$buffer = fputs($socket, "GETINFO orconn-status\n");

        $buffer = fgets($socket, 1024);
        $buffer = fgets($socket, 1024);

	while (strlen($buffer) > 3) {

		$bits = explode(" ", $buffer);

		$connections[trim($bits['1'])]++;

                $buffer = fgets($socket, 1024);


	}

	if (!empty($connections['NEW'])) echo "new.value ".$connections['NEW']."\n";
	else echo "new.value 0\n";

        if (!empty($connections['LAUNCHED'])) echo "launched.value ".$connections['LAUNCHED']."\n";
        else echo "launched.value 0\n";

        if (!empty($connections['CONNECTED'])) echo "connected.value ".$connections['CONNECTED']."\n";
        else echo "connected.value 0\n";

        if (!empty($connections['FAILED'])) echo "failed.value ".$connections['FAILED']."\n";
        else echo "failed.value 0\n";

        if (!empty($connections['CLOSED'])) echo "closed.value ".$connections['CLOSED']."\n";
        else echo "closed.value 0\n";


}

fclose($socket);

?>

