11# !/usr/bin/perl
22use warnings;
3- use strict;
3+ use 5.014; # strict, HTTP::Tiny, JSON::PP
44# should run on vanilla Perl, use core modules only
55use Sys::Hostname ' hostname' ;
66use Digest::SHA ' hmac_sha256_base64' ;
7+ use JSON::PP ();
8+ use HTTP::Tiny ();
79
8- my $SECRET = ' password ' ; # for signature, so server can verify authenticity
9- my $BASEURL = ' https://example.com/hellorpi/ ' ; # end with slash!
10+ my $SECRET = ' secret ' ; # FIXME: CHANGE THIS - for signature, so server can verify authenticity
11+ my $URL = ' https://example.com/hellorpi' ;
1012
1113# IPv4 only at the moment:
12- my @ips = grep { / \A\d +(?:\.\d +){3}\z / } split ' ' , ` /usr/bin/hostname -I` ;
13- die " hostname -I failed with \$ ?=$? \n " if $? ;
14+ my @ips = sort grep { / \A\d +(?:\.\d +){3}\z / } split ' ' , ` /usr/bin/hostname -I` ;
15+ die " ` hostname -I` failed with \$ ?=$? \n " if $? ;
1416exit unless @ips ;
1517
1618my $host = hostname;
1719die " unexpected hostname '$host '\n " unless $host =~/ \A [A-Za-z0-9\.\-\_ ]+\z / ;
1820
19- my $url = join ' /' , $host , @ips ;
21+ my $sig = hmac_sha256_base64(join (" \0 " , $host , @ips ), $SECRET );
22+ $sig .= ' =' while length ($sig ) % 4; # pad
2023
21- my $sig = hmac_sha256_base64($url , $SECRET );
22- $sig =~ tr # +/# -_# ; # like Python's base64.urlsafe_b64encode
23- # $sig =~ s/=+$//g; # not actually needed, docs say there won't be padding
24+ my $resp = HTTP::Tiny-> new-> request(' POST' , $URL , { content =>
25+ JSON::PP-> new-> ascii-> canonical-> pretty-> encode(
26+ { host => $host , ips => \@ips , sig => $sig }) });
27+ die " POST $URL => $resp ->{status} $resp ->{reason}\n " unless $resp -> {success };
2428
25- my @cmd = (' curl' ,' --silent' ,' --max-time' ,' 5' ,
26- ' --fail' ,' --fail-early' ,' --show-error' ,
27- ' --header' ,' Content-Type: application/octet-stream' ,
28- ' --data-raw' ,$sig ," $BASEURL$url " ,' --output' ,' /dev/null' );
29- system (@cmd ) and die " @cmd \n FAILED with \$ ?=$? , \$ !=$! \n " ;
29+ # spell: ignore hmac
0 commit comments