Git::RepoCGI: Fix a warning
[girocco.git] / cgi / Git / RepoCGI.pm
blob2945c2c7c2108326f47219356d57acbac8798373
1 package Git::RepoCGI;
3 use strict;
4 use warnings;
7 ### Administrativa
9 BEGIN {
10 our $VERSION = '0.1';
11 our @ISA = qw(Exporter);
12 our @EXPORT = qw(scrypt html_esc jailed_file
13 lock_file unlock_file
14 filedb_atomic_append filedb_atomic_edit
15 proj_get_forkee_name proj_get_forkee_path
16 valid_proj_name valid_user_name valid_email valid_repo_url valid_web_url);
18 use CGI qw(:standard :escapeHTML -nosticky);
19 use CGI::Util qw(unescape);
20 use CGI::Carp qw(fatalsToBrowser);
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=\"text-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>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 my $value;
266 $propmap{$name} or die "unknown property: $name";
267 open P, $self->_property_path($propmap{$name}) or return undef;
268 chomp($value = <P>);
269 close P;
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 $self->{email} = $repo->wparam('email');
467 valid_email($self->{email})
468 or $repo->err("Your email sure looks weird...?");
470 $self->{url} = $repo->wparam('url');
471 if ($self->{url}) {
472 valid_repo_url($self->{url})
473 or $repo->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
476 $self->{desc} = $repo->wparam('desc');
477 length($self->{desc}) <= 1024
478 or $repo->err("<b>Short</b> description length > 1kb!");
480 $self->{README} = $repo->wparam('README');
481 length($self->{README}) <= 8192
482 or $repo->err("README length > 8kb!");
484 $self->{hp} = $repo->wparam('hp');
485 if ($self->{hp}) {
486 valid_web_url($self->{hp})
487 or $repo->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
490 # FIXME: Permit only existing users
491 $self->{users} = [grep { valid_user_name($_) } $cgi->param('user')];
493 not $repo->err_check;
496 sub form_defaults {
497 my $self = shift;
499 name => $self->{name},
500 email => $self->{email},
501 url => $self->{url},
502 desc => html_esc($self->{desc}),
503 README => html_esc($self->{README}),
504 hp => $self->{hp},
505 users => $self->{users},
509 sub authenticate {
510 my $self = shift;
511 my ($repo) = @_;
513 $self->{ccrypt} or die "Can't authenticate against a project with no password";
514 $self->{cpwd} or $repo->err("No password entered.");
515 unless ($self->{ccrypt} eq crypt($self->{cpwd}, $self->{ccrypt})) {
516 $repo->err("Your admin password does not match!");
517 return 0;
519 return 1;
522 sub premirror {
523 my $self = shift;
525 $self->_mkdir_forkees;
526 mkdir $self->{path} or die "mkdir failed: $!";
527 chmod 0775, $self->{path} or die "chmod failed: $!";
528 $self->_properties_save;
529 $self->_alternates_setup;
530 $self->_group_add(':');
533 sub conjure {
534 my $self = shift;
536 $self->_mkdir_forkees;
537 system('cg-admin-setuprepo', '-g', 'repo', $self->{path}) == 0
538 or die "cg-admin-setuprepo failed: $?";
539 system('git', '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false');
540 $self->_nofetch(1);
541 $self->_properties_save;
542 $self->_alternates_setup;
543 $self->_group_add;
544 $self->_hooks_install;
547 sub update {
548 my $self = shift;
550 $self->_properties_save;
551 $self->_group_update;
554 # You can explicitly do this just on a ghost() repository too.
555 sub delete {
556 my $self = shift;
558 if (-d $self->{path}) {
559 system('rm', '-r', $self->{path}) == 0
560 or die "rm -r failed: $?";
562 $self->_group_remove;
565 # static method
566 sub does_exist {
567 my ($name) = @_;
568 valid_proj_name($name) or die "tried to query for project with invalid name $name!";
569 (available($name)
570 or -d "/home/repo/repodata/cloning/$name"
571 or -d "/home/repo/repodata/to-clone/$name");
573 sub available {
574 my ($name) = @_;
575 valid_proj_name($name) or die "tried to query for project with invalid name $name!";
576 (-d "/srv/git/$name.git");
580 ### User object
582 package Git::RepoCGI::User;
584 BEGIN { use Git::RepoCGI; }
586 sub _passwd_add {
587 my $self = shift;
588 filedb_atomic_append(jailed_file('/etc/passwd'),
589 join(':', $self->{name}, 'x', '\i', 65534, $self->{email}, '/', '/bin/git-shell'));
592 sub _sshkey_path {
593 my $self = shift;
594 '/etc/sshkeys/'.$self->{name};
597 sub _sshkey_save {
598 my $self = shift;
599 open F, ">".jailed_file($self->_sshkey_path) or die "sshkey failed: $!";
600 print F $self->{keys}."\n";
601 close F;
602 chmod 0664, jailed_file($self->_sshkey_path);
605 # private constructor, do not use
606 sub _new {
607 my $class = shift;
608 my ($name) = @_;
609 valid_user_name($name) or die "refusing to create user with invalid name ($name)!";
610 my $proj = { name => $name };
612 bless $proj, $class;
615 # public constructor #0
616 # creates a virtual user not connected to disk record
617 # you can conjure() it later to disk
618 sub ghost {
619 my $class = shift;
620 my ($name) = @_;
621 my $self = $class->_new($name);
622 $self;
625 # $user may not be in sane state if this returns false!
626 sub cgi_fill {
627 my $self = shift;
628 my ($repo) = @_;
629 my $cgi = $repo->cgi;
631 $self->{name} = $repo->wparam('name');
632 valid_user_name($self->{name})
633 or $repo->err("Name contains invalid characters.");
635 $self->{email} = $repo->wparam('email');
636 valid_email($self->{email})
637 or $repo->err("Your email sure looks weird...?");
639 $self->{keys} = $cgi->param('keys');
640 length($self->{keys}) <= 4096
641 or $repo->err("The list of keys is more than 4kb. Do you really need that much?");
643 not $repo->err_check;
646 sub conjure {
647 my $self = shift;
649 $self->_passwd_add;
650 $self->_sshkey_save;
653 # static method
654 sub does_exist {
655 my ($name) = @_;
656 valid_user_name($name) or die "tried to query for user with invalid name $name!";
657 (-e jailed_file("/etc/sshkeys/$name"));
659 sub available {
660 does_exist(@_);