#!/usr/bin/perl
#
# A git daemon with an added userv security boundary.
#
# This reads the first packet-line of the protocol, checks the syntax
# of the pathname and hostname, then uses userv to invoke the
# git-upload-pack as the target user with safe arguments.
#
# 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;

use lib '/etc/userv';

sub ntoa {
    my $sockaddr = shift;
    if (defined $sockaddr) {
        my ($port,$addr) = sockaddr_in $sockaddr;
        $addr = inet_ntoa $addr;
        return ($addr,$port,"[$addr]:$port");
    } else {
        return (undef,undef,"[?.?.?.?]:?");
    }
}

my ($client_addr,$client_port,$client) = ntoa getpeername STDIN;
my ($server_addr,$server_port,$server) = ntoa getsockname STDIN;

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

sub fail {
    syslog 'err', "$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;
        $ret = 0        if not defined $ret;
    }
    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;
unless ($line =~ m{^git-upload-pack ([!-~]+)\0host=([!-~]+)\0$}) {
    $line =~ s/[^ -~]+/ /g;
    fail "could not parse \"$line\""
}
my ($path,$host) = ($1,$2);
$path =~ s|^/||;
$_ = my $uri = "git://$host/$path";

my ($user,$repo) = do "git-daemon-urlmap.pl";
fail "no user configured for $uri" unless defined $user;
syslog 'info', "$client userv $user git-upload-pack $uri";

my %vars = (
    REQUEST_HOST => $host,
    REQUEST_PATH => $path,
    REQUEST_URI => $uri,
    CLIENT_ADDR => $client_addr,
    CLIENT_PORT => $client_port,
    SERVER_ADDR => $server_addr,
    SERVER_PORT => $server_port,
);
my @opts = map "-D$_=$vars{$_}", grep defined $vars{$_}, sort keys %vars;

no warnings; # suppress errors to stderr
exec 'userv', @opts, $user, 'git-upload-pack'
    or fail "exec userv @opts $user git-upload-pack: $!";

# end
