#!/usr/bin/perl
#
# A git daemon with an added userv security boundary.
#
# This was written by Tony Finch <dot@dotat.at> and subsequently
# heavily modified by Ian Jackson <ijackson@chiark.greenend.org.uk>
# http://creativecommons.org/publicdomain/zero/1.0/

use strict;
use warnings;

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

BEGIN {
    if ($ARGV[0] =~ s/^-L//) {
	my $logfile= shift @ARGV;
	open STDERR, ">> $logfile" or die $!;
    }
}

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

printf STDERR "%s [$$] %s %s\n",
    strftime("%Y-%m-%d %H:%M:%S %Z", localtime), $server, $client;

openlog 'userv-git-daemon', 'pid', 'daemon';
sub fail { syslog 'err', "$client @_"; exit }

$SIG{ALRM} = sub { fail "timeout" };
alarm 30;

sub xread {
    my $length = shift;
    my $buffer = "";
    while ($length > length $buffer) {
        my $ret = sysread STDIN, $buffer, $length, length $buffer;
        fail "Expected $length bytes, got ".length $buffer
                            if defined $ret and $ret == 0;
        fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
    }
    return $buffer;
}
my $hex_len = xread 4;
fail "Bad hex in packet length" unless $hex_len =~ m|^[0-9a-fA-F]{4}$|;
my $line = xread -4 + hex $hex_len;
unless (($service,$specpath,$spechost) = $line =~
        m|^(git-[a-z-]+) /*([!-~]+)\0host=([!-~]+)\0$|) {
    $line =~ s|[^ -~]+| |g;
    fail "Could not parse \"$line\""
}

# -*- perl -*-

# uses:
#     $specpath    whole path from caller, minus any leading /s
#     $spechost    host from caller
#
# sets:
#
#  always:
#     $uri
#
#  if match found for this host and path:
#     $serve_user   username, or undef if no match (then other serve_* invalid)
#     $serve_dir    directory as specified in config
#     $serve_repo   subpath under $serve_dir _including_ leading /
#
#  for use by user's service program
#     $repo_regexp
#     $require_exportok

sub remain_path ($) {
    # return value matches {( / [^/]+ )+}x
    my ($vsubpath) = @_;
    syslog 'debug', sprintf "DEBUG remain_path %s $specpath",
                              (defined $vsubpath ? $vsubpath : '<undef>');
    return "/$specpath" if !defined $vsubpath;
    return "" if $vsubpath eq $specpath;
    return substr($specpath,length($vsubpath))
	if substr($specpath,0,length($vsubpath)+1) eq "$vsubpath/";
    return undef;
}

fail "no config ??" unless @ARGV;
fail "no specpath ??" unless length $specpath;

our $uri = "git://$spechost/$specpath";

our $repo_regexp= '^(\\w[-+._0-9A-Za-z]*/?\.git)$';  # stupid emacs ';
our $check_export= 0;

our ($serve_user, $serve_dir, $serve_repo);

sub fexists ($) {
    my ($f) = @_;
    if (stat $f) {
	-f _ or fail "bad config $_ - not a file";
	return 1;
    } else {
	$!==&ENOENT or fail "bad config $_ - could not stat: $!";
	return 0;
    }
}

@ARGV = grep { fexists($_) } @ARGV;

while (<>) {

    s/^\s*//;
    s/\s+$//;
    next unless m/\S/;
    next if m/^\#/;

    if (m{^ single-user \s+ (\S+?) (/\S*)? \s+ (\S+) (?: \s+ (\S+) )? $ }x) {
	my ($h,$v,$u,$d) = ($1,$2,$3,$4);
	next unless $h eq $spechost;
	$serve_repo= remain_path($v);
	next unless defined $serve_repo;
	$serve_user= $u;
	$serve_dir= $d;
        syslog 'debug', "DEBUG $ARGV:$. match".
            " $serve_user $serve_dir $serve_repo";
    } elsif (m{^ multi-user \s+ (\S+?) (/\S*)? \s+ (\S+) $ }x) {
	my ($h,$v,$d) = ($1,$2,$3);
	next unless $1 eq $spechost;
	$serve_repo= remain_path($v);
	next unless defined $serve_repo;
        syslog 'debug', "DEBUG $ARGV:$. perhaps $serve_repo";
	next unless $serve_repo =~ s{ ^/\~( [a-z][-+_0-9a-z]* )/ }{/}xi;
	$serve_user= $1;
	$serve_dir= $d;
        syslog 'debug', "DEBUG $ARGV:$. match".
            " $serve_user $serve_dir $serve_repo";
    } elsif (m{^ repo-regexp \s+ (\S.*) $ }x) {
	$repo_regexp= $1;
    } elsif (m{^ (no-)?require-git-daemon-export-ok $ }x) {
	$check_export= !defined $1;
    } else {
	fail "config syntax error at $ARGV:$.";
    }
}

# end


fail "No global mapping for $uri" unless defined $serve_user;

my ($hn,$ha,$at,$naddrs,@addrs) = gethostbyname $spechost;
fail "hostname/address mismatch ($spechost $server_addr)" unless grep {
    $server_addr eq inet_ntoa $_
    } @addrs;

our @opts;

push @opts, "-D$_=${$::{$_}}"
    for qw(service specpath spechost
	   client client_addr client_port
	   server server_addr server_port);

fail "no user $serve_user" unless getpwnam($serve_user);

syslog 'notice', "$client $service $uri $serve_user";

my @cmd = ('userv', '-t300', @opts, $serve_user, $service);
no warnings; # suppress errors to stderr
exec @cmd or fail "exec userv: $!";

# end
