#!/usr/bin/perl

=head1 NAME

sdbset - generate HTTP requests for B<sdb>

=head1 SYNOPSIS

B<sdbset> /I<url> I<name>/I<id> I<value> I<key>

=head1 DESCRIPTION

B<sdbset> generates a HTTP POST request which is used to put values
into an B<sdb> database. The output should be fed into a TCP
connection to the server.

The request contains a timestamp and MD5 checksum. To construct the
checksum a key is needed. B<sdb> accepts only requests with correct
checksum and current (less than 1 minute off) timestamp.

=head1 OPTIONS

The following parameters have to be specified in order:

=over 4

=item I<url>

The URL (path-part for direct connection, complete URL for proxy
connection) of the B<sdb> CGI script.

=item I<name>/I<id>

The client name and resource ID to set, separated by a slash.

=item I<value>

The new value.

=item I<key>

The key (password) for the client name.

=back

All parameters can be any string, but common usage limits them to
(probably non-blank) printable characters.

=head1 EXAMPLES

To set value "me" for client "hosta" to "10.11.12.13:1415" using password "hello_world":

  sdbset /cgi-bin/sdb hosta/me 10.11.12.13:1415 hello_world |\
         socket www.example.com 80

To do the same using an HTTP proxy:

  sdbset http://www.example.com/cgi-bin/sdb hosta/me \
         10.11.12.13:1415 hello_world |\
         socket proxy.example.com 3128

=head1 SEE ALSO

L<sdb>.

=head1 AUTHOR

Olaf Titz (olaf@bigred.inka.de). Public domain.

=cut

use MD5;

$t=sprintf("%d", $^T);
$val=$ARGV[2];
$val=~s/[^A-Za-z0-9]/sprintf("%%%02X", ord($&))/ge;
$q=sprintf("set=%s&t=%s&cs=%s", $val, $t,
	   &csum($ARGV[1], $ARGV[2], $t, $ARGV[3]));

printf "POST %s/%s HTTP/1.0\n", $ARGV[0], $ARGV[1];
printf "Content-Length: %d\n", length($q);
print "Content-type: application/x-www-form-urlencoded\n";
print "\n$q\n";
exit;

# checksum over: id, val, time, key
sub csum
{
    local($i,$v,$t,$k)=@_;
    my $m=new MD5;
    $m->add("$i$v$t$k");
    return $m->hexdigest();
}
