s/gitweb.cgi/w/
[girocco/ztw.git] / cgi / Git / RepoCGI.pm
blobf692da9bdc085718006d298d73f01366ccefa0d5
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> / administration
49 </div>
51 <h1>$heading</h1>
52 EOT
54 bless $repo, $class;
57 sub DESTROY {
58 my $self = shift;
59 my $cgi = $self->cgi;
60 my $cginame = $cgi->url(-absolute => 1);
61 $cginame =~ s#^/m/##;
62 if ($cginame =~ /^[a-zA-Z0-9_.\/-]+\.cgi$/) {
63 print <<EOT;
64 <div align="right">
65 <a href="http://repo.or.cz/w/repo.git?a=blob;f=cgi/$cginame">(view source)</a>
66 </div>
67 EOT
69 print <<EOT;
70 </body>
71 </html>
72 EOT
75 sub cgi {
76 my $self = shift;
77 $self->{cgi};
80 sub err {
81 my $self = shift;
82 print "<p style=\"text-color: red\">@_</p>\n";
83 $self->{err}++;
86 sub err_check {
87 my $self = shift;
88 my $err = $self->{err};
89 $err and print "<p>Operation aborted due to $err errors.</p>\n";
90 $err;
93 sub wparam {
94 my $self = shift;
95 my ($param) = @_;
96 my $val = $self->{cgi}->param($param);
97 $val =~ s/^\s*(.*?)\s*$/$1/;
98 $val;
102 ### Random utility functions
104 sub scrypt {
105 my ($pwd) = @_;
106 crypt($pwd, join ('', ('.', '/', 2..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
109 sub html_esc {
110 my ($str) = @_;
111 $str =~ s/&/&amp;/g;
112 $str =~ s/</&lt;/g; $str =~ s/>/&gt;/g;
113 $str =~ s/"/&quot;/g;
114 $str;
117 sub jailed_file {
118 my ($filename) = @_;
119 "/home/repo/j/$filename";
122 sub lock_file {
123 my ($path) = @_;
125 $path .= '.lock';
127 use Errno qw(EEXIST);
128 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
129 use IO::Handle;
130 my $handle = new IO::Handle;
132 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
133 my $cnt = 0;
134 while (not sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
135 ($! == EEXIST) or die "$path open failed: $!";
136 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
137 sleep(1);
140 # XXX: filedb-specific
141 chmod 0664, $path or die "$path g+w failed: $!";
143 $handle;
146 sub unlock_file {
147 my ($path) = @_;
149 rename "$path.lock", $path or die "$path unlock failed: $!";
152 sub filedb_atomic_append {
153 my ($file, $line) = @_;
154 my $id = 65536;
156 open my $src, $file or die "$file open for reading failed: $!";
157 my $dst = lock_file($file);
159 while (<$src>) {
160 my $aid = (split /:/)[2];
161 $id = $aid + 1 if ($aid >= $id);
163 print $dst $_ or die "$file(l) write failed: $!";
166 $line =~ s/\\i/$id/g;
167 print $dst "$line\n" or die "$file(l) write failed: $!";
169 close $dst or die "$file(l) close failed: $!";
170 close $src;
172 unlock_file($file);
174 $id;
177 sub filedb_atomic_edit {
178 my ($file, $fn) = @_;
180 open my $src, $file or die "$file open for reading failed: $!";
181 my $dst = lock_file($file);
183 while (<$src>) {
184 print $dst $fn->($_) or die "$file(l) write failed: $!";
187 close $dst or die "$file(l) close failed: $!";
188 close $src;
190 unlock_file($file);
193 # BOTH user AND project name!
194 sub valid_name {
195 $_ = $_[0];
196 /^[a-zA-Z0-9_+-]+$/;
198 sub valid_email {
199 $_ = $_[0];
200 /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9-.]+$/;
202 sub valid_web_url {
203 $_ = $_[0];
204 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?(#[a-zA-Z0-9._-]+)?$/;
206 sub valid_repo_url {
207 $_ = $_[0];
208 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/ or
209 /^git:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/;
213 ### Project object
215 package Git::RepoCGI::Project;
217 BEGIN { use Git::RepoCGI; }
219 our %propmap = (
220 url => 'base_url',
221 email => 'owner',
222 desc => 'description',
223 README => 'README',
224 hp => 'homepage',
227 sub _property_path {
228 my $self = shift;
229 my ($name) = @_;
230 $self->{path}.'/'.$name;
233 sub _property_fget {
234 my $self = shift;
235 my ($name) = @_;
236 my $value;
237 $propmap{$name} or die "unknown property: $name";
238 open P, $self->_property_path($propmap{$name}) or return undef;
239 chomp($value = <P>);
240 close P;
241 $value;
244 sub _property_fput {
245 my $self = shift;
246 my ($name, $value) = @_;
247 $propmap{$name} or die "unknown property: $name";
248 open P, '>'.$self->_property_path($propmap{$name}) or die "$name put failed: $!";
249 $value ne '' and print P "$value\n";
250 close P;
251 chmod 0664, $self->_property_path($propmap{$name}) or die "$name chmod failed: $!";
254 sub _properties_load {
255 my $self = shift;
256 foreach my $prop (keys %propmap) {
257 $self->{$prop} = $self->_property_fget($prop);
261 sub _properties_save {
262 my $self = shift;
263 foreach my $prop (keys %propmap) {
264 $self->_property_fput($prop, $self->{$prop});
268 sub _nofetch_path {
269 my $self = shift;
270 $self->_property_path('.nofetch');
273 sub _nofetch {
274 my $self = shift;
275 my ($nofetch) = @_;
276 my $np = $self->_nofetch_path;
277 if ($nofetch) {
278 open X, '>'.$np or die "nofetch failed: $!";
279 close X;
280 } else {
281 unlink $np or die "yesfetch failed: $!";
285 sub _group_add {
286 my $self = shift;
287 my ($xtra) = @_;
288 $xtra .= join(',', @{$self->{users}});
289 filedb_atomic_append(jailed_file('/etc/group'),
290 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
293 sub _group_update {
294 my $self = shift;
295 my $xtra = join(',', @{$self->{users}});
296 filedb_atomic_edit(jailed_file('/etc/group'),
297 sub {
298 $_ = $_[0];
299 chomp;
300 if ($self->{name} eq (split /:/)[0]) {
301 # preserve readonly flag
302 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
303 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
304 } else {
305 return "$_\n";
311 sub _group_remove {
312 my $self = shift;
313 filedb_atomic_edit(jailed_file('/etc/group'),
314 sub {
315 $self->{name} ne (split /:/)[0] and return $_;
320 sub _hook_path {
321 my $self = shift;
322 my ($name) = @_;
323 $self->{path}.'/hooks/'.$name;
326 sub _hook_install {
327 my $self = shift;
328 my ($name) = @_;
329 open SRC, "/home/repo/repomgr/$name-hook" or die "cannot open hook $name: $!";
330 open DST, '>'.$self->_hook_path($name) or die "cannot open hook $name for writing: $!";
331 while (<SRC>) { print DST $_; }
332 close DST;
333 close SRC;
334 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
337 sub _hooks_install {
338 my $self = shift;
339 foreach my $hook ('update') {
340 $self->_hook_install($hook);
344 # private constructor, do not use
345 sub _new {
346 my $class = shift;
347 my ($name, $path) = @_;
348 valid_name($name) or die "refusing to create project with invalid name ($name)!";
349 my $proj = { name => $name, path => $path };
351 bless $proj, $class;
354 # public constructor #0
355 # creates a virtual project not connected to disk image
356 # you can conjure() it later to disk
357 sub ghost {
358 my $class = shift;
359 my ($name, $mirror) = @_;
360 my $self = $class->_new($name, $mirror ? "/home/repo/repodata/to-clone/$name" : "/srv/git/$name.git");
361 $self->{users} = [];
362 $self->{mirror} = $mirror;
363 $self;
366 # public constructor #1
367 sub load {
368 my $class = shift;
369 my ($name) = @_;
371 open F, jailed_file("/etc/group") or die "project load failed: $!";
372 while (<F>) {
373 chomp;
374 @_ = split /:+/;
375 next unless (shift eq $name);
377 my $self = $class->_new($name, "/srv/git/$name.git");
378 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
380 my $ulist;
381 ($self->{crypt}, $self->{gid}, $ulist) = @_;
382 $ulist ||= '';
383 $self->{users} = [split /,/, $ulist];
384 $self->{mirror} = ! -e $self->_nofetch_path;
386 $self->_properties_load;
387 return $self;
389 close F;
390 undef;
393 # $proj may not be in sane state if this returns false!
394 sub cgi_fill {
395 my $self = shift;
396 my ($repo) = @_;
397 my $cgi = $repo->cgi;
399 my $pwd = $cgi->param('pwd');
400 if ($pwd ne '' or not $self->{crypt}) {
401 $self->{crypt} = scrypt($pwd);
404 $self->{email} = $repo->wparam('email');
405 valid_email($self->{email})
406 or $repo->err("Your email sure looks weird...?");
408 $self->{url} = $repo->wparam('url');
409 if ($self->{url}) {
410 valid_repo_url($self->{url})
411 or $repo->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
414 $self->{desc} = $repo->wparam('desc');
415 length($self->{desc}) <= 1024
416 or $repo->err("<b>Short</b> description length > 1kb!");
418 $self->{README} = $repo->wparam('README');
419 length($self->{README}) <= 8192
420 or $repo->err("README length > 8kb!");
422 $self->{hp} = $repo->wparam('hp');
423 if ($self->{hp}) {
424 valid_web_url($self->{hp})
425 or $repo->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
428 # FIXME: Permit only existing users
429 $self->{users} = [grep { valid_name($_) } $cgi->param('user')];
431 not $repo->err_check;
434 sub form_defaults {
435 my $self = shift;
437 name => $self->{name},
438 email => $self->{email},
439 url => $self->{url},
440 desc => html_esc($self->{desc}),
441 README => html_esc($self->{README}),
442 hp => $self->{hp},
443 users => $self->{users},
447 sub premirror {
448 my $self = shift;
450 mkdir $self->{path} or die "mkdir failed: $!";
451 chmod 0775, $self->{path} or die "chmod failed: $!";
452 $self->_properties_save;
453 $self->_group_add(':');
456 sub conjure {
457 my $self = shift;
459 system('cg-admin-setuprepo', '-g', 'repo', $self->{path}) == 0
460 or die "cg-admin-setuprepo failed: $?";
461 $self->_nofetch(1);
462 $self->_properties_save;
463 $self->_group_add;
464 $self->_hooks_install;
467 sub update {
468 my $self = shift;
470 $self->_properties_save;
471 $self->_group_update;
474 # You can explicitly do this just on a ghost() repository too.
475 sub delete {
476 my $self = shift;
478 if (-d $self->{path}) {
479 system('rm', '-r', $self->{path}) == 0
480 or die "rm -r failed: $?";
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(@_);