diff options
| author | Kristian Lyngstol <kly@kly.no> | 2016-02-21 15:17:23 +0000 | 
|---|---|---|
| committer | Kristian Lyngstol <kly@kly.no> | 2016-02-21 15:17:23 +0000 | 
| commit | a412ae0c8c75b70786cf60c10c21d0b5c080dfb4 (patch) | |
| tree | 6c64eab1ac2c207c49b6ef7c4bc38e6e897c809a /include/nms/web.pm | |
| parent | cdc33b1f0989e82d270d281090ffa2d516282f62 (diff) | |
nms: Start splitting up port-state.pl
Diffstat (limited to 'include/nms/web.pm')
| -rwxr-xr-x | include/nms/web.pm | 83 | 
1 files changed, 83 insertions, 0 deletions
diff --git a/include/nms/web.pm b/include/nms/web.pm new file mode 100755 index 0000000..b768104 --- /dev/null +++ b/include/nms/web.pm @@ -0,0 +1,83 @@ +#! /usr/bin/perl +use strict; +use warnings; +use CGI qw(fatalsToBrowser); +use DBI; +use Data::Dumper; +use JSON; +use nms; +package nms::web; + +use base 'Exporter'; +our @EXPORT = qw(finalize_output json cgi dbh); +our $cgi; +our %json = (); +our $dbh; +our $now; +our $when; +our $ifname; +our %cc = (); + +# Print cache-control from %cc +sub printcc { +	my $line = ""; +	my $first = ""; +	foreach my $tmp (keys(%cc)) { +		$line .= $first . $tmp . "=" . $cc{$tmp}; +		$first = ", "; +	} +	print 'Cache-Control: ' . $line . "\n"; +} + +# returns a valid $when statement +# Also sets cache-control headers if time is overridden +sub setwhen { +	my $when; +	$now = "now()"; +	if (defined($cgi->param('now'))) { +		$now = "'" . $cgi->param('now') . "'::timestamp "; +		$cc{'max-age'} = "3600"; +	} +	$when = " time > " . $now . " - '5m'::interval and time < " . $now . " "; +	return $when; +} + +# Sets the ifname. If we are logged in, it's simply set to "ifname", otherwise +# it's hashed for anonymization. +sub  obfuscateifname { +	my $ifname = "ifname"; +	if (defined($cgi->param('public'))) { +		$ifname = "regexp_replace(ifname, 'ge-0/0/(([0-3][0-9])|(4[0-3])|([0-9]))\$',concat('ge-participant',sha1_hmac(ifname::bytea,'".$nms::config::nms_hash."'::bytea))) as ifname"; +	} +	return $ifname; +} + +sub finalize_output { +	my $query; +	$query = $dbh->prepare ('select ' . $now . ' as time;'); +	$query->execute(); + +	$json{'time'} = $query->fetchrow_hashref()->{'time'}; +	$json{'username'} = $cgi->remote_user(); +	printcc; + +	print $cgi->header(-type=>'text/json; charset=utf-8'); +	print JSON::XS::encode_json(\%json); +	print "\n"; +} + +BEGIN { +	$cgi = CGI->new; + +	$cc{'stale-while-revalidate'} = "3600"; +	$cc{'max-age'} = "5"; + +	$dbh = nms::db_connect(); +	# FIXME: Shouldn't be magic. +	# Only used for setting time in result from DB time. +	# FIXME: Clarification, this _has_ to be set before setwhen is run, +	# since it secretly overrides it. +	$when = setwhen(); +	$ifname = obfuscateifname(); +} +1;  | 
