$proj->delete() implemented
[girocco.git] / cgi / Git / RepoCGI.pm
blob7714121eb5e16fb3f9a7c3b1c96982a4e02a8e2b
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 filedb_atomic_append filedb_atomic_edit
14 valid_name valid_email valid_repo_url valid_web_url);
16 use CGI qw(:standard :escapeHTML -nosticky);
17 use CGI::Util qw(unescape);
18 use CGI::Carp qw(fatalsToBrowser);
22 ### RepoCGI object
24 sub new {
25 my $class = shift;
26 my ($heading) = @_;
27 my $repo = {};
29 $repo->{cgi} = CGI->new;
31 print $repo->{cgi}->header(-type=>'text/html', -charset => 'utf-8');
33 print <<EOT;
34 <?xml version="1.0" encoding="utf-8"?>
35 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
36 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
38 <head>
39 <title>repo.or.cz :: $heading</title>
40 <link rel="stylesheet" type="text/css" href="/gitweb.css"/>
41 <link rel="shortcut icon" href="/git-favicon.png" type="image/png"/>
42 </head>
44 <body>
46 <div class="page_header">
47 <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>
48 <a href="/">repo.or.cz</a>
49 <div class="search">
50 Administration Interface
51 </div>
52 </div>
54 <h1>$heading</h1>
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/gitweb.cgi/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 # BOTH user AND project name!
197 sub valid_name {
198 $_ = $_[0];
199 /^[a-zA-Z0-9_+-]+$/;
201 sub valid_email {
202 $_ = $_[0];
203 /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9-.]+$/;
205 sub valid_web_url {
206 $_ = $_[0];
207 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?(#[a-zA-Z0-9._-]+)?$/;
209 sub valid_repo_url {
210 $_ = $_[0];
211 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/ or
212 /^git:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/;
216 ### Project object
218 package Git::RepoCGI::Project;
220 BEGIN { use Git::RepoCGI; }
222 our %propmap = (
223 url => 'base_url',
224 email => 'owner',
225 desc => 'description',
226 README => 'README',
227 hp => 'homepage',
230 sub _property_path {
231 my $self = shift;
232 my ($name) = @_;
233 $self->{path}.'/'.$name;
236 sub _property_fget {
237 my $self = shift;
238 my ($name) = @_;
239 my $value;
240 $propmap{$name} or die "unknown property: $name";
241 open P, $self->_property_path($propmap{$name}) or return undef;
242 chomp($value = <P>);
243 close P;
244 $value;
247 sub _property_fput {
248 my $self = shift;
249 my ($name, $value) = @_;
250 $propmap{$name} or die "unknown property: $name";
251 open P, '>'.$self->_property_path($propmap{$name}) or die "$name put failed: $!";
252 $value ne '' and print P "$value\n";
253 close P;
254 chmod 0664, $self->_property_path($propmap{$name}) or die "$name chmod failed: $!";
257 sub _properties_load {
258 my $self = shift;
259 foreach my $prop (keys %propmap) {
260 $self->{$prop} = $self->_property_fget($prop);
264 sub _properties_save {
265 my $self = shift;
266 foreach my $prop (keys %propmap) {
267 $self->_property_fput($prop, $self->{$prop});
271 sub _nofetch_path {
272 my $self = shift;
273 $self->_property_path('.nofetch');
276 sub _nofetch {
277 my $self = shift;
278 my ($nofetch) = @_;
279 my $np = $self->_nofetch_path;
280 if ($nofetch) {
281 open X, '>'.$np or die "nofetch failed: $!";
282 close X;
283 } else {
284 unlink $np or die "yesfetch failed: $!";
288 sub _group_add {
289 my $self = shift;
290 my ($xtra) = @_;
291 $xtra .= join(',', @{$self->{users}});
292 filedb_atomic_append(jailed_file('/etc/group'),
293 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
296 sub _group_update {
297 my $self = shift;
298 my $xtra = join(',', @{$self->{users}});
299 filedb_atomic_edit(jailed_file('/etc/group'),
300 sub {
301 $_ = $_[0];
302 chomp;
303 if ($self->{name} eq (split /:/)[0]) {
304 # preserve readonly flag
305 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
306 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
307 } else {
308 return "$_\n";
314 sub _group_remove {
315 my $self = shift;
316 filedb_atomic_edit(jailed_file('/etc/group'),
317 sub {
318 $self->{name} ne (split /:/)[0]) and return $_;
323 sub _hook_path {
324 my $self = shift;
325 my ($name) = @_;
326 $self->{path}.'/hooks/'.$name;
329 sub _hook_install {
330 my $self = shift;
331 my ($name) = @_;
332 open SRC, "/home/repo/repomgr/$name-hook" or die "cannot open hook $name: $!";
333 open DST, '>'.$self->_hook_path($name) or die "cannot open hook $name for writing: $!";
334 while (<SRC>) { print DST $_; }
335 close DST;
336 close SRC;
337 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
340 sub _hooks_install {
341 my $self = shift;
342 foreach my $hook ('update') {
343 $self->_hook_install($hook);
347 # private constructor, do not use
348 sub _new {
349 my $class = shift;
350 my ($name, $path) = @_;
351 valid_name($name) or die "refusing to create project with invalid name ($name)!";
352 my $proj = { name => $name, path => $path };
354 bless $proj, $class;
357 # public constructor #0
358 # creates a virtual project not connected to disk image
359 # you can conjure() it later to disk
360 sub ghost {
361 my $class = shift;
362 my ($name, $mirror) = @_;
363 my $self = $class->_new($name, $mirror ? "/home/repo/repodata/to-clone/$name" : "/srv/git/$name.git");
364 $self->{users} = [];
365 $self->{mirror} = $mirror;
366 $self;
369 # public constructor #1
370 sub load {
371 my $class = shift;
372 my ($name, $warehouse) = @_;
373 $warehouse ||= '/srv/git';
375 open F, jailed_file("/etc/group") or die "project load failed: $!";
376 while (<F>) {
377 chomp;
378 @_ = split /:+/;
379 next unless (shift eq $name);
381 my $self = $class->_new($name, "$warehouse/$name".($warehouse eq '/srv/git' ? '.git' : ''));
382 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
384 my $ulist;
385 ($self->{crypt}, $self->{gid}, $ulist) = @_;
386 $ulist ||= '';
387 $self->{users} = [split /,/, $ulist];
388 $self->{mirror} = ! -e $self->_nofetch_path;
390 $self->_properties_load;
391 return $self;
393 close F;
394 undef;
397 # $proj may not be in sane state if this returns false!
398 sub cgi_fill {
399 my $self = shift;
400 my ($repo) = @_;
401 my $cgi = $repo->cgi;
403 my $pwd = $cgi->param('pwd');
404 if ($pwd ne '' or not $self->{crypt}) {
405 $self->{crypt} = scrypt($pwd);
408 $self->{email} = $repo->wparam('email');
409 valid_email($self->{email})
410 or $repo->err("Your email sure looks weird...?");
412 $self->{url} = $repo->wparam('url');
413 if ($self->{url}) {
414 valid_repo_url($self->{url})
415 or $repo->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
418 $self->{desc} = $repo->wparam('desc');
419 length($self->{desc}) <= 1024
420 or $repo->err("<b>Short</b> description length > 1kb!");
422 $self->{README} = $repo->wparam('README');
423 length($self->{README}) <= 8192
424 or $repo->err("README length > 8kb!");
426 $self->{hp} = $repo->wparam('hp');
427 if ($self->{hp}) {
428 valid_web_url($self->{hp})
429 or $repo->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
432 # FIXME: Permit only existing users
433 $self->{users} = [grep { valid_name($_) } $cgi->param('user')];
435 not $repo->err_check;
438 sub form_defaults {
439 my $self = shift;
441 name => $self->{name},
442 email => $self->{email},
443 url => $self->{url},
444 desc => html_esc($self->{desc}),
445 README => html_esc($self->{README}),
446 hp => $self->{hp},
447 users => $self->{users},
451 sub premirror {
452 my $self = shift;
454 mkdir $self->{path} or die "mkdir failed: $!";
455 chmod 0775, $self->{path} or die "chmod failed: $!";
456 $self->_properties_save;
457 $self->_group_add(':');
460 sub conjure {
461 my $self = shift;
463 system('cg-admin-setuprepo', '-g', 'repo', $self->{path}) == 0
464 or die "cg-admin-setuprepo failed: $?";
465 $self->_nofetch(1);
466 $self->_properties_save;
467 $self->_group_add;
468 $self->_hooks_install;
471 sub update {
472 my $self = shift;
474 $self->_properties_save;
475 $self->_group_update;
478 sub delete {
479 my $self = shift;
481 system('rm', '-r', $self->{path});
482 $self->_group_remove;
485 # static method
486 sub does_exist {
487 my ($name) = @_;
488 valid_name($name) or die "tried to query for project with invalid name $name!";
489 (available($name)
490 or -d "/home/repo/repodata/cloning/$name"
491 or -d "/home/repo/repodata/to-clone/$name");
493 sub available {
494 my ($name) = @_;
495 valid_name($name) or die "tried to query for project with invalid name $name!";
496 (-d "/srv/git/$name.git");
500 ### User object
502 package Git::RepoCGI::User;
504 BEGIN { use Git::RepoCGI; }
506 sub _passwd_add {
507 my $self = shift;
508 filedb_atomic_append(jailed_file('/etc/passwd'),
509 join(':', $self->{name}, 'x', '\i', 65536, $self->{email}, '/', '/bin/git-shell'));
512 sub _sshkey_path {
513 my $self = shift;
514 '/etc/sshkeys/'.$self->{name};
517 sub _sshkey_save {
518 my $self = shift;
519 open F, ">".jailed_file($self->_sshkey_path) or die "sshkey failed: $!";
520 print F $self->{keys}."\n";
521 close F;
522 chmod 0664, jailed_file($self->_sshkey_path);
525 # private constructor, do not use
526 sub _new {
527 my $class = shift;
528 my ($name) = @_;
529 valid_name($name) or die "refusing to create user with invalid name ($name)!";
530 my $proj = { name => $name };
532 bless $proj, $class;
535 # public constructor #0
536 # creates a virtual user not connected to disk record
537 # you can conjure() it later to disk
538 sub ghost {
539 my $class = shift;
540 my ($name) = @_;
541 my $self = $class->_new($name);
542 $self;
545 # $user may not be in sane state if this returns false!
546 sub cgi_fill {
547 my $self = shift;
548 my ($repo) = @_;
549 my $cgi = $repo->cgi;
551 $self->{name} = $repo->wparam('name');
552 valid_name($self->{name})
553 or $repo->err("Name contains invalid characters.");
555 $self->{email} = $repo->wparam('email');
556 valid_email($self->{email})
557 or $repo->err("Your email sure looks weird...?");
559 $self->{keys} = $cgi->param('keys');
560 length($self->{keys}) <= 4096
561 or $repo->err("The list of keys is more than 4kb. Do you really need that much?");
563 not $repo->err_check;
566 sub conjure {
567 my $self = shift;
569 $self->_passwd_add;
570 $self->_sshkey_save;
573 # static method
574 sub does_exist {
575 my ($name) = @_;
576 valid_name($name) or die "tried to query for user with invalid name $name!";
577 (-e jailed_file("/etc/sshkeys/$name"));
579 sub available {
580 does_exist(@_);