Add SSH key changing interface.
[girocco/ztw.git] / cgi / Git / RepoCGI.pm
blob4f77cd515eeb3f7d8fe03bda5c04fad4c27505a8
1 package Git::RepoCGI;
3 use strict;
4 use warnings;
6 ### Administrativa
8 BEGIN {
9 our $VERSION = '0.1';
10 our @ISA = qw(Exporter);
11 our @EXPORT = qw(scrypt html_esc jailed_file
12 lock_file unlock_file
13 filedb_atomic_append filedb_atomic_edit
14 proj_get_forkee_name proj_get_forkee_path
15 valid_proj_name valid_user_name valid_email valid_repo_url valid_web_url);
17 use CGI qw(:standard :escapeHTML -nosticky);
18 use CGI::Util qw(unescape);
19 use CGI::Carp qw(fatalsToBrowser);
20 use Digest::SHA1 qw(sha1_hex);
22 $ENV{PATH} = '/home/pasky/bin:'.$ENV{PATH};
26 ### RepoCGI object
28 sub new {
29 my $class = shift;
30 my ($heading) = @_;
31 my $repo = {};
33 $repo->{cgi} = CGI->new;
35 print $repo->{cgi}->header(-type=>'text/html', -charset => 'utf-8');
37 print <<EOT;
38 <?xml version="1.0" encoding="utf-8"?>
39 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
40 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
42 <head>
43 <title>repo.or.cz :: $heading</title>
44 <link rel="stylesheet" type="text/css" href="/gitweb.css"/>
45 <link rel="shortcut icon" href="/git-favicon.png" type="image/png"/>
46 </head>
48 <body>
50 <div class="page_header">
51 <a href="http://git.or.cz/" title="Git homepage"><img src="/git-logo.png" width="72" height="27" alt="git" style="float:right; border-width:0px;"/></a>
52 <a href="/">repo.or.cz</a> / administration / $heading
53 </div>
55 EOT
57 bless $repo, $class;
60 sub DESTROY {
61 my $self = shift;
62 my $cgi = $self->cgi;
63 my $cginame = $cgi->url(-absolute => 1);
64 $cginame =~ s#^/m/##;
65 if ($cginame =~ /^[a-zA-Z0-9_.\/-]+\.cgi$/) {
66 print <<EOT;
67 <div align="right">
68 <a href="http://repo.or.cz/w/repo.git?a=blob;f=cgi/$cginame">(view source)</a>
69 </div>
70 EOT
72 print <<EOT;
73 </body>
74 </html>
75 EOT
78 sub cgi {
79 my $self = shift;
80 $self->{cgi};
83 sub err {
84 my $self = shift;
85 print "<p style=\"color: red\">@_</p>\n";
86 $self->{err}++;
89 sub err_check {
90 my $self = shift;
91 my $err = $self->{err};
92 $err and print "<p style=\"font-weight: bold\">Operation aborted due to $err errors.</p>\n";
93 $err;
96 sub wparam {
97 my $self = shift;
98 my ($param) = @_;
99 my $val = $self->{cgi}->param($param);
100 $val =~ s/^\s*(.*?)\s*$/$1/;
101 $val;
105 ### Random utility functions
107 sub scrypt {
108 my ($pwd) = @_;
109 crypt($pwd, join ('', ('.', '/', 2..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
112 sub html_esc {
113 my ($str) = @_;
114 $str =~ s/&/&amp;/g;
115 $str =~ s/</&lt;/g; $str =~ s/>/&gt;/g;
116 $str =~ s/"/&quot;/g;
117 $str;
120 sub jailed_file {
121 my ($filename) = @_;
122 "/home/repo/j/$filename";
125 sub lock_file {
126 my ($path) = @_;
128 $path .= '.lock';
130 use Errno qw(EEXIST);
131 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
132 use IO::Handle;
133 my $handle = new IO::Handle;
135 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
136 my $cnt = 0;
137 while (not sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
138 ($! == EEXIST) or die "$path open failed: $!";
139 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
140 sleep(1);
143 # XXX: filedb-specific
144 chmod 0664, $path or die "$path g+w failed: $!";
146 $handle;
149 sub unlock_file {
150 my ($path) = @_;
152 rename "$path.lock", $path or die "$path unlock failed: $!";
155 sub filedb_atomic_append {
156 my ($file, $line) = @_;
157 my $id = 65536;
159 open my $src, $file or die "$file open for reading failed: $!";
160 my $dst = lock_file($file);
162 while (<$src>) {
163 my $aid = (split /:/)[2];
164 $id = $aid + 1 if ($aid >= $id);
166 print $dst $_ or die "$file(l) write failed: $!";
169 $line =~ s/\\i/$id/g;
170 print $dst "$line\n" or die "$file(l) write failed: $!";
172 close $dst or die "$file(l) close failed: $!";
173 close $src;
175 unlock_file($file);
177 $id;
180 sub filedb_atomic_edit {
181 my ($file, $fn) = @_;
183 open my $src, $file or die "$file open for reading failed: $!";
184 my $dst = lock_file($file);
186 while (<$src>) {
187 print $dst $fn->($_) or die "$file(l) write failed: $!";
190 close $dst or die "$file(l) close failed: $!";
191 close $src;
193 unlock_file($file);
196 sub proj_get_forkee_name {
197 $_ = $_[0];
198 (m#^(.*)/.*?$#)[0];
200 sub proj_get_forkee_path {
201 my $forkee = '/srv/git/'.proj_get_forkee_name($_[0]).'.git';
202 -d $forkee ? $forkee : '';
204 sub valid_proj_name {
205 $_ = $_[0];
206 (not m#/# or -d proj_get_forkee_path($_)) # will also catch ^/
207 and (not m#\./#)
208 and (not m#/$#)
209 and m#^[a-zA-Z0-9+./_-]+$#;
211 sub valid_user_name {
212 $_ = $_[0];
213 /^[a-zA-Z0-9+._-]+$/;
215 sub valid_email {
216 $_ = $_[0];
217 /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9-.]+$/;
219 sub valid_web_url {
220 $_ = $_[0];
221 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?(#[a-zA-Z0-9._-]+)?$/;
223 sub valid_repo_url {
224 $_ = $_[0];
225 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/ or
226 /^git:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/;
230 ### Project object
232 package Git::RepoCGI::Project;
234 BEGIN { use Git::RepoCGI; }
236 sub _mkdir_forkees {
237 my $self = shift;
238 my @pelems = split('/', $self->{name});
239 pop @pelems; # do not create dir for the project itself
240 my $path = $self->{base_path};
241 foreach my $pelem (@pelems) {
242 $path .= "/$pelem";
243 (-d "$path") or mkdir $path or die "mkdir $path: $!";
244 chmod 0775, $path; # ok if fails (dir may already exist and be owned by someone else)
248 our %propmap = (
249 url => 'base_url',
250 email => 'owner',
251 desc => 'description',
252 README => 'README.html',
253 hp => 'homepage',
256 sub _property_path {
257 my $self = shift;
258 my ($name) = @_;
259 $self->{path}.'/'.$name;
262 sub _property_fget {
263 my $self = shift;
264 my ($name) = @_;
265 $propmap{$name} or die "unknown property: $name";
266 open P, $self->_property_path($propmap{$name}) or return undef;
267 my @value = <P>;
268 close P;
269 my $value = join('', @value); chomp $value;
270 $value;
273 sub _property_fput {
274 my $self = shift;
275 my ($name, $value) = @_;
276 $propmap{$name} or die "unknown property: $name";
278 my $P = lock_file($self->_property_path($propmap{$name}));
279 $value ne '' and print $P "$value\n";
280 close $P;
281 unlock_file($self->_property_path($propmap{$name}));
284 sub _properties_load {
285 my $self = shift;
286 foreach my $prop (keys %propmap) {
287 $self->{$prop} = $self->_property_fget($prop);
291 sub _properties_save {
292 my $self = shift;
293 foreach my $prop (keys %propmap) {
294 $self->_property_fput($prop, $self->{$prop});
298 sub _nofetch_path {
299 my $self = shift;
300 $self->_property_path('.nofetch');
303 sub _nofetch {
304 my $self = shift;
305 my ($nofetch) = @_;
306 my $np = $self->_nofetch_path;
307 if ($nofetch) {
308 open X, '>'.$np or die "nofetch failed: $!";
309 close X;
310 } else {
311 unlink $np or die "yesfetch failed: $!";
315 sub _alternates_setup {
316 my $self = shift;
317 return unless $self->{name} =~ m#/#;
318 my $forkee_name = proj_get_forkee_name($self->{name});
319 my $forkee_path = proj_get_forkee_path($self->{name});
320 return unless -d $forkee_path;
321 mkdir $self->{path}.'/refs'; chmod 0775, $self->{path}.'/refs';
322 mkdir $self->{path}.'/objects'; chmod 0775, $self->{path}.'/objects';
323 mkdir $self->{path}.'/objects/info'; chmod 0775, $self->{path}.'/objects/info';
325 # We set up both alternates and http_alternates since we cannot use
326 # relative path in alternates - that doesn't work recursively.
328 my $filename = $self->{path}.'/objects/info/alternates';
329 open X, '>'.$filename or die "alternates failed: $!";
330 print X "$forkee_path/objects\n";
331 close X;
332 chmod 0664, $filename or warn "cannot chmod $filename: $!";
334 $filename = $self->{path}.'/objects/info/http-alternates';
335 open X, '>'.$filename or die "http-alternates failed: $!";
336 my $upfork = $forkee_name;
337 do { print X "/r/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork);
338 close X;
339 chmod 0664, $filename or warn "cannot chmod $filename: $!";
341 symlink "$forkee_path/refs", $self->{path}.'/refs/forkee';
344 sub _group_add {
345 my $self = shift;
346 my ($xtra) = @_;
347 $xtra .= join(',', @{$self->{users}});
348 filedb_atomic_append(jailed_file('/etc/group'),
349 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
352 sub _group_update {
353 my $self = shift;
354 my $xtra = join(',', @{$self->{users}});
355 filedb_atomic_edit(jailed_file('/etc/group'),
356 sub {
357 $_ = $_[0];
358 chomp;
359 if ($self->{name} eq (split /:/)[0]) {
360 # preserve readonly flag
361 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
362 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
363 } else {
364 return "$_\n";
370 sub _group_remove {
371 my $self = shift;
372 filedb_atomic_edit(jailed_file('/etc/group'),
373 sub {
374 $self->{name} ne (split /:/)[0] and return $_;
379 sub _hook_path {
380 my $self = shift;
381 my ($name) = @_;
382 $self->{path}.'/hooks/'.$name;
385 sub _hook_install {
386 my $self = shift;
387 my ($name) = @_;
388 open SRC, "/home/repo/repomgr/$name-hook" or die "cannot open hook $name: $!";
389 open DST, '>'.$self->_hook_path($name) or die "cannot open hook $name for writing: $!";
390 while (<SRC>) { print DST $_; }
391 close DST;
392 close SRC;
393 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
396 sub _hooks_install {
397 my $self = shift;
398 foreach my $hook ('update') {
399 $self->_hook_install($hook);
403 # private constructor, do not use
404 sub _new {
405 my $class = shift;
406 my ($name, $base_path, $path) = @_;
407 valid_proj_name($name) or die "refusing to create project with invalid name ($name)!";
408 $path ||= "$base_path/$name.git";
409 my $proj = { name => $name, base_path => $base_path, path => $path };
411 bless $proj, $class;
414 # public constructor #0
415 # creates a virtual project not connected to disk image
416 # you can conjure() it later to disk
417 sub ghost {
418 my $class = shift;
419 my ($name, $mirror) = @_;
420 my $self = $class->_new($name, $mirror ? "/home/repo/repodata/to-clone" : "/srv/git",
421 $mirror ? "/home/repo/repodata/to-clone/$name" : "/srv/git/$name.git");
422 $self->{users} = [];
423 $self->{mirror} = $mirror;
424 $self;
427 # public constructor #1
428 sub load {
429 my $class = shift;
430 my ($name) = @_;
432 open F, jailed_file("/etc/group") or die "project load failed: $!";
433 while (<F>) {
434 chomp;
435 @_ = split /:+/;
436 next unless (shift eq $name);
438 my $self = $class->_new($name, "/srv/git");
439 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
441 my $ulist;
442 ($self->{crypt}, $self->{gid}, $ulist) = @_;
443 $ulist ||= '';
444 $self->{users} = [split /,/, $ulist];
445 $self->{mirror} = ! -e $self->_nofetch_path;
446 $self->{ccrypt} = $self->{crypt};
448 $self->_properties_load;
449 return $self;
451 close F;
452 undef;
455 # $proj may not be in sane state if this returns false!
456 sub cgi_fill {
457 my $self = shift;
458 my ($repo) = @_;
459 my $cgi = $repo->cgi;
461 my $pwd = $cgi->param('pwd');
462 if ($pwd ne '' or not $self->{crypt}) {
463 $self->{crypt} = scrypt($pwd);
466 if ($cgi->param('pwd2') and $pwd ne $cgi->param('pwd2')) {
467 $repo->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
470 $self->{cpwd} = $cgi->param('cpwd');
472 $self->{email} = $repo->wparam('email');
473 valid_email($self->{email})
474 or $repo->err("Your email sure looks weird...?");
476 $self->{url} = $repo->wparam('url');
477 if ($self->{url}) {
478 valid_repo_url($self->{url})
479 or $repo->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
482 $self->{desc} = $repo->wparam('desc');
483 length($self->{desc}) <= 1024
484 or $repo->err("<b>Short</b> description length > 1kb!");
486 $self->{README} = $repo->wparam('README');
487 length($self->{README}) <= 8192
488 or $repo->err("README length > 8kb!");
490 $self->{hp} = $repo->wparam('hp');
491 if ($self->{hp}) {
492 valid_web_url($self->{hp})
493 or $repo->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
496 # FIXME: Permit only existing users
497 $self->{users} = [grep { valid_user_name($_) } $cgi->param('user')];
499 not $repo->err_check;
502 sub form_defaults {
503 my $self = shift;
505 name => $self->{name},
506 email => $self->{email},
507 url => $self->{url},
508 desc => html_esc($self->{desc}),
509 README => html_esc($self->{README}),
510 hp => $self->{hp},
511 users => $self->{users},
515 sub authenticate {
516 my $self = shift;
517 my ($repo) = @_;
519 $self->{ccrypt} or die "Can't authenticate against a project with no password";
520 $self->{cpwd} or $repo->err("No password entered.");
521 unless ($self->{ccrypt} eq crypt($self->{cpwd}, $self->{ccrypt})) {
522 $repo->err("Your admin password does not match!");
523 return 0;
525 return 1;
528 sub premirror {
529 my $self = shift;
531 $self->_mkdir_forkees;
532 mkdir $self->{path} or die "mkdir failed: $!";
533 chmod 0775, $self->{path} or die "chmod failed: $!";
534 $self->_properties_save;
535 $self->_alternates_setup;
536 $self->_group_add(':');
539 sub conjure {
540 my $self = shift;
542 $self->_mkdir_forkees;
543 system('cg-admin-setuprepo', '-g', 'repo', $self->{path}) == 0
544 or die "cg-admin-setuprepo failed: $?";
545 system('git', '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false');
546 $self->_nofetch(1);
547 $self->_properties_save;
548 $self->_alternates_setup;
549 $self->_group_add;
550 $self->_hooks_install;
553 sub update {
554 my $self = shift;
556 $self->_properties_save;
557 $self->_group_update;
560 sub update_password {
561 my $self = shift;
562 my ($pwd) = @_;
564 $self->{crypt} = scrypt($pwd);
565 $self->_group_update;
568 # You can explicitly do this just on a ghost() repository too.
569 sub delete {
570 my $self = shift;
572 if (-d $self->{path}) {
573 system('rm', '-r', $self->{path}) == 0
574 or die "rm -r failed: $?";
576 $self->_group_remove;
579 # static method
580 sub does_exist {
581 my ($name) = @_;
582 valid_proj_name($name) or die "tried to query for project with invalid name $name!";
583 (available($name)
584 or -d "/home/repo/repodata/cloning/$name"
585 or -d "/home/repo/repodata/to-clone/$name");
587 sub available {
588 my ($name) = @_;
589 valid_proj_name($name) or die "tried to query for project with invalid name $name!";
590 (-d "/srv/git/$name.git");
594 ### User object
596 package Git::RepoCGI::User;
598 BEGIN { use Git::RepoCGI; }
600 sub _passwd_add {
601 my $self = shift;
602 filedb_atomic_append(jailed_file('/etc/passwd'),
603 join(':', $self->{name}, 'x', '\i', 65534, $self->{email}, '/', '/bin/git-shell'));
606 sub _sshkey_path {
607 my $self = shift;
608 '/etc/sshkeys/'.$self->{name};
611 sub _sshkey_load {
612 my $self = shift;
613 open F, "<".jailed_file($self->_sshkey_path) or die "sshkey load failed: $!";
614 my @keys;
615 my $auth;
616 while (<F>) {
617 chomp;
618 if (/^ssh-(?:dss|rsa) /) {
619 push @keys, $_;
620 } elsif (/^# REPOAUTH ([0-9a-f]+) (\d+)/) {
621 my $expire = $2;
622 $auth = $1 unless (time >= $expire);
625 close F;
626 my $keys = join('', @keys); chomp $keys;
627 ($keys, $auth);
630 sub _sshkey_save {
631 my $self = shift;
632 open F, ">".jailed_file($self->_sshkey_path) or die "sshkey failed: $!";
633 if (defined($self->{auth}) && $self->{auth}) {
634 my $expire = time + 24 * 3600;
635 print F "# REPOAUTH $self->{auth} $expire\n";
637 print F $self->{keys}."\n";
638 close F;
639 chmod 0664, jailed_file($self->_sshkey_path);
642 # private constructor, do not use
643 sub _new {
644 my $class = shift;
645 my ($name) = @_;
646 valid_user_name($name) or die "refusing to create user with invalid name ($name)!";
647 my $proj = { name => $name };
649 bless $proj, $class;
652 # public constructor #0
653 # creates a virtual user not connected to disk record
654 # you can conjure() it later to disk
655 sub ghost {
656 my $class = shift;
657 my ($name) = @_;
658 my $self = $class->_new($name);
659 $self;
662 # public constructor #1
663 sub load {
664 my $class = shift;
665 my ($name) = @_;
667 open F, jailed_file("/etc/passwd") or die "user load failed: $!";
668 while (<F>) {
669 chomp;
670 @_ = split /:+/;
671 next unless (shift eq $name);
673 my $self = $class->_new($name);
675 (undef, $self->{uid}, undef, $self->{email}) = @_;
676 ($self->{keys}, $self->{auth}) = $self->_sshkey_load;
678 return $self;
680 close F;
681 undef;
684 # $user may not be in sane state if this returns false!
685 sub cgi_fill {
686 my $self = shift;
687 my ($repo) = @_;
688 my $cgi = $repo->cgi;
690 $self->{name} = $repo->wparam('name');
691 valid_user_name($self->{name})
692 or $repo->err("Name contains invalid characters.");
694 $self->{email} = $repo->wparam('email');
695 valid_email($self->{email})
696 or $repo->err("Your email sure looks weird...?");
698 $self->keys_fill($repo);
701 sub keys_fill {
702 my $self = shift;
703 my ($repo) = @_;
704 my $cgi = $repo->cgi;
706 $self->{keys} = $cgi->param('keys');
707 length($self->{keys}) <= 4096
708 or $repo->err("The list of keys is more than 4kb. Do you really need that much?");
710 not $repo->err_check;
713 sub keys_save {
714 my $self = shift;
716 $self->_sshkey_save;
719 sub gen_auth {
720 my $self = shift;
722 $self->{auth} = Digest::SHA1::sha1_hex(time . $$ . rand() . $self->{keys});
723 $self->_sshkey_save;
724 $self->{auth};
727 sub del_auth {
728 my $self = shift;
730 delete $self->{auth};
733 sub conjure {
734 my $self = shift;
736 $self->_passwd_add;
737 $self->_sshkey_save;
740 # static method
741 sub does_exist {
742 my ($name) = @_;
743 valid_user_name($name) or die "tried to query for user with invalid name $name!";
744 (-e jailed_file("/etc/sshkeys/$name"));
746 sub available {
747 does_exist(@_);