#!/usr/bin/perl
#
# A git daemon with an added userv security boundary.
#
# This was written by Tony Finch <dot@dotat.at>
# You may do anything with it, at your own risk.
# http://creativecommons.org/publicdomain/zero/1.0/

use strict;
use warnings;

use POSIX;
use Socket;
use Sys::Syslog;

sub ntoa {
    my $sockaddr = shift;
    return ('[?.?.?.?]:?') unless defined $sockaddr;
    my ($port,$addr) = sockaddr_in $sockaddr;
    $addr = inet_ntoa $addr;
    return ("[$addr]:$port",$addr,$port);
}
{
    package cf;
    our ($client,$client_addr,$client_port) = ::ntoa(getpeername(STDIN));
    our ($server,$server_addr,$server_port) = ::ntoa(getsockname(STDIN));
}

openlog 'userv-git-daemon', 'pid', 'daemon';

sub fail {
    syslog 'err', "$cf::client @_";
    exit;
}

sub xread {
    my $length = shift;
    my $buffer = "";
    local $SIG{ALRM} = sub { fail "timeout" };
    alarm 30;
    while ($length > length $buffer) {
        my $ret = sysread STDIN, $buffer, $length, length $buffer;
        fail "short read: expected $length bytes, got " . length $buffer
                            if defined $ret and $ret == 0;
        fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
    }
    alarm 0;
    return $buffer;
}

my $len_hex = xread 4;
fail "non-hex packet length" unless $len_hex =~ m{^[0-9a-fA-F]{4}$};
my $line = xread hex $len_hex;
if ($line =~ m{^(git-[a-z-]+) ([!-~]+)\0host=([!-~]+)\0$}) {
    package cf;
    our ($service,$path,$host) = ($1,$2,$3);
    $path =~ s|^/*||;
    our $uri = $_ = "git://$host/$path";
} else {
    $line =~ s|[^ -~]+| |g;
    fail "could not parse \"$line\""
}

for my $cf (@ARGV) {
    package cf;
    our ($user,$dir,$repo);
    do $cf;
}
fail "no user configured for $cf::uri" unless defined $cf::user;
syslog 'info', "$cf::client $cf::service $cf::uri";

my @opts = map "-D$_=${$cf::{$_}}", grep defined ${$cf::{$_}}, sort keys %cf::;
my @cmd = ('userv', @opts, $cf::user, $cf::service);
no warnings; # suppress errors to stderr
exec @cmd or fail "exec @cmd: $!";

# end
