git-daemon: tidy up a bit
[userv-utils] / git-daemon / git-daemon.pl
... / ...
CommitLineData
1#!/usr/bin/perl
2#
3# A git daemon with an added userv security boundary.
4#
5# This was written by Tony Finch <dot@dotat.at>
6# You may do anything with it, at your own risk.
7# http://creativecommons.org/publicdomain/zero/1.0/
8
9use strict;
10use warnings;
11
12use POSIX;
13use Socket;
14use Sys::Syslog;
15
16sub ntoa {
17 my $sockaddr = shift;
18 return ('(local)') unless defined $sockaddr;
19 my ($port,$addr) = sockaddr_in $sockaddr;
20 $addr = inet_ntoa $addr;
21 return ("[$addr]:$port",$addr,$port);
22}
23our ($client,$client_addr,$client_port) = ntoa getpeername STDIN;
24our ($server,$server_addr,$server_port) = ntoa getsockname STDIN;
25our ($service,$path,$host,$user);
26
27openlog 'userv-git-daemon', 'pid', 'daemon';
28sub fail { syslog 'err', "$client @_"; exit }
29
30$SIG{ALRM} = sub { fail "timeout" };
31alarm 30;
32
33sub xread {
34 my $length = shift; $_ = "";
35 while ($length > length) {
36 my $ret = sysread STDIN, $_, $length, length;
37 fail "Expected $length bytes, got ".length
38 if defined $ret and $ret == 0;
39 fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
40 }
41}
42xread 4;
43fail "Bad hex in packet length" unless m|^[0-9a-fA-F]{4}$|;
44xread hex;
45unless (($service,$path,$host) =
46 m|^(git-[a-z-]+) /*([!-~]+)\0host=([!-~]+)\0$|) {
47 s|[^ -~]+| |g;
48 fail "Could not parse \"$_\""
49}
50our $uri = $_ = "git://$host/$path";
51for my $cf (@ARGV) { do $cf }
52
53fail "No user for $uri" unless defined $user;
54syslog 'notice', "$client $service $uri";
55
56my @opts = map "-D$_=${$::{$_}}",
57 grep defined ${$::{$_}} && /^[a-z_]+$/, keys %::;
58
59my @cmd = ('userv', @opts, $user, $service);
60no warnings; # suppress errors to stderr
61exec @cmd or fail "exec userv: $!";
62
63# end