summaryrefslogtreecommitdiffstats
path: root/emergencyc.pl
blob: 5d59be12d34106686348be47685bafa0840f8b56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#! /usr/local/bin/perl -w

# The Emergency Client - send commands to the emergency daemon

# David A. Madore <URL: http://www.madore.org/~david/ > - Public Domain

# This is a stupid client which just sends a command verbatim to the
# emergency daemon.  All it takes care of is to put a valid timestamp
# and MAC.

# Options recognized:
#
# -K <key> specifies the key to use; or -k <filename> specifies a key
# file (the client will use the first line as key).
#
# -h <hostname> and -p <number> specifies the host and port to connect
# to.
#
# -t <timestamp> specifies an explicit timestamp to use.
#
# The command follows the options.

use strict;
use warnings;
use Digest::SHA qw(hmac_sha256_hex);
use Socket;
use Socket6;
use Getopt::Std;

use constant {
    DEFAULT_PORT => 911
};

my %opts;

getopts("K:k:h:p:t:", \%opts);

my $key;
if ( defined($opts{K}) ) {
    $key = $opts{K};
} elsif ( defined($opts{k}) ) {
    open my $key_file, "<", $opts{k}
	or die "Cannot open key file $opts{k}: $!";
    $key = <$key_file>;
    chomp $key;
    close $key_file;
}
die "No key specified (use -K or -k option)" unless defined($key);

my $host = $opts{h} // "localhost";
my $port = $opts{p} // DEFAULT_PORT;

my @res = getaddrinfo($host, $port, AF_UNSPEC, SOCK_DGRAM)
    or die "Cannot resolve host $host port $port";
my ($family, $socktype, $proto, $haddr) = @res;

my $socket;
socket $socket, $family, $socktype, $proto or die "Can't create socket: $!";
bind $socket, sockaddr_in6(0, in6addr_any);

sub curtime {
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
    return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ",
		   $year+1900,$mon+1,$mday,$hour,$min,$sec);
}

my $command = $ARGV[0] // "PING";
my $timestamp = $opts{t} // curtime;
my $validate = "$command|$timestamp";
my $mac_check = hmac_sha256_hex($validate, $key);
send $socket, "$command|$timestamp|$mac_check", 0, $haddr;

my $buf;
my $sender;
eval {
    local $SIG{ALRM} = sub { die "alarm\n" };
    alarm 5;
    do {
	$sender = recv($socket, $buf, 16384, 0);
    } while ( defined($sender) && $sender ne $haddr );
};
if ( $@ ) {
    print "timeout\n";
    exit 1;
} elsif ( !defined($sender) ) {
    die "Failed to receive packet: $!";
} else {
    printf "%s", $buf;
}