git-daemon.pl: second iteration based on feedback from Ian.
[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
fbde0914
TF
20use vars qw{ %vhost_default_user %vhost_user_from_tilde
21 $TILDE $REPO $HOSTNAME };
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 = "";
47 my $count = 0;
fbde0914
TF
48 # simply die if the client takes too long
49 alarm 30;
d2707bea 50 while ($length > length $buffer) {
fbde0914
TF
51 my ($data,$ret);
52 do {
53 $ret = sysread STDIN, $data, $length
54 } while not defined $ret and ($! == EINTR or $! == EAGAIN);
55 fail "read: $!" unless defined $ret;
56 fail "short read: expected $length bytes, got $count" if $ret == 0;
57 $buffer .= $data;
58 $count += $ret;
d2707bea 59 }
fbde0914 60 alarm 0;
d2707bea
TF
61 return $buffer;
62}
63
64my $len_hex = xread 4;
fbde0914
TF
65fail "non-hexadecimal packet length" unless $len_hex =~ m{^[0-9a-zA-Z]{4}$};
66my $len = hex $len_hex;
d2707bea
TF
67
68my $line = xread $len;
fbde0914
TF
69unless ($line =~ m{^git-upload-pack (?:~($TILDE)/)?($REPO[.]git)\0host=($HOSTNAME)\0$}) {
70 $line =~ s/[^ -~]+/ /g;
71 fail "could not parse \"$line\""
72}
73my ($tilde,$repo,$host) = ($1,$2,$3);
74my $url = $tilde ? "git://$host/~$tilde/$repo" : "git://$host/$repo";
75
76my $user = $vhost_user_from_tilde{$host} ? $tilde : $vhost_default_user{$host};
77fail "no user configuration for $url" unless defined $user;
78
79syslog 'info', "$peer $user $url";
80
81my @opts = ("-DCLIENT=$addr", "-DHOST=$host", "-DREPO=$repo");
82push @opts, "-DTILDE=$tilde" if defined $tilde;
83
84exec 'userv', @opts, $user, 'git-upload-pack'
85 or fail "exec userv: $!";
86
87# end