git-daemon: allow virtual hosts to forbit tilde parts in URLs
[userv-utils] / git-daemon / git-daemon.pl
CommitLineData
d2707bea
TF
1#!/usr/bin/perl
2#
fbde0914 3# A git daemon with an added userv security boundary.
d2707bea
TF
4#
5# This reads the first packet-line of the protocol, checks the syntax
fbde0914
TF
6# of the pathname and hostname, then uses userv to invoke the
7# git-upload-pack as the target user with safe arguments.
d2707bea
TF
8#
9# This was written by Tony Finch <dot@dotat.at>
10# You may do anything with it, at your own risk.
11# http://creativecommons.org/publicdomain/zero/1.0/
12
13use strict;
14use warnings;
15
16use POSIX;
fbde0914
TF
17use Socket;
18use Sys::Syslog;
d2707bea 19
b8db4eb5
TF
20use vars qw{ $TILDE $REPO $HOSTNAME
21 %vhost_default_user %vhost_tilde_is_user %vhost_tilde_forbidden };
fbde0914
TF
22
23use lib '/etc/userv';
24require 'git-daemon-vhosts.pl';
25
26my $peer = getpeername STDIN;
27my ($port,$addr);
28if (defined $peer) {
29 ($port,$addr) = sockaddr_in $peer;
30 $addr = inet_ntoa $addr;
31 $peer = "[$addr]:$port";
32} else {
33 $peer = "[?.?.?.?]:?";
34 undef $!;
35}
36
37openlog 'userv-git-daemon', 'pid', 'daemon';
38
39sub fail {
40 syslog 'err', "$peer @_";
41 exit;
42}
d2707bea
TF
43
44sub xread {
45 my $length = shift;
46 my $buffer = "";
f14a8627 47 local $SIG{ALRM} = sub { fail "timeout" };
fbde0914 48 alarm 30;
d2707bea 49 while ($length > length $buffer) {
abb80356
TF
50 my $ret = sysread STDIN, $buffer, $length, length $buffer;
51 fail "short read: expected $length bytes, got " . length $buffer
52 if defined $ret and $ret == 0;
53 fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
54 $ret = 0 if not defined $ret;
d2707bea 55 }
fbde0914 56 alarm 0;
d2707bea
TF
57 return $buffer;
58}
59
60my $len_hex = xread 4;
fbde0914 61fail "non-hexadecimal packet length" unless $len_hex =~ m{^[0-9a-zA-Z]{4}$};
f14a8627 62my $line = xread hex $len_hex;
fbde0914
TF
63unless ($line =~ m{^git-upload-pack (?:~($TILDE)/)?($REPO[.]git)\0host=($HOSTNAME)\0$}) {
64 $line =~ s/[^ -~]+/ /g;
65 fail "could not parse \"$line\""
66}
67my ($tilde,$repo,$host) = ($1,$2,$3);
68my $url = $tilde ? "git://$host/~$tilde/$repo" : "git://$host/$repo";
69
b8db4eb5
TF
70fail "tilde forbidden for $url" if defined $tilde and $vhost_tilde_forbidden{$host};
71my $user = $vhost_tilde_is_user{$host} ? $tilde : $vhost_default_user{$host};
72fail "no user configured for $url" unless defined $user;
fbde0914
TF
73syslog 'info', "$peer $user $url";
74
11b88dbb 75my @opts = ("-DHOST=$host", "-DREPO=$repo");
fbde0914 76push @opts, "-DTILDE=$tilde" if defined $tilde;
11b88dbb
TF
77push @opts, "-DCLIENT=$addr" if defined $addr;
78no warnings; # suppress errors to stderr
fbde0914
TF
79exec 'userv', @opts, $user, 'git-upload-pack'
80 or fail "exec userv: $!";
81
82# end