Move site title to the top bar
[girocco/susan.git] / cgi / Git / RepoCGI.pm
blobb059792c83e155a0fbce1c2183b36cbbdb1c78c2
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 valid_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);
23 ### RepoCGI object
25 sub new {
26 my $class = shift;
27 my ($heading) = @_;
28 my $repo = {};
30 $repo->{cgi} = CGI->new;
32 print $repo->{cgi}->header(-type=>'text/html', -charset => 'utf-8');
34 print <<EOT;
35 <?xml version="1.0" encoding="utf-8"?>
36 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
37 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
39 <head>
40 <title>repo.or.cz :: $heading</title>
41 <link rel="stylesheet" type="text/css" href="/gitweb.css"/>
42 <link rel="shortcut icon" href="/git-favicon.png" type="image/png"/>
43 </head>
45 <body>
47 <div class="page_header">
48 <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>
49 <a href="/">repo.or.cz</a> / administration / $heading
50 </div>
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";
249 my $P = lock_file($self->_property_path($propmap{$name}));
250 $value ne '' and print $P "$value\n";
251 close $P;
252 unlock_file($self->_property_path($propmap{$name}));
255 sub _properties_load {
256 my $self = shift;
257 foreach my $prop (keys %propmap) {
258 $self->{$prop} = $self->_property_fget($prop);
262 sub _properties_save {
263 my $self = shift;
264 foreach my $prop (keys %propmap) {
265 $self->_property_fput($prop, $self->{$prop});
269 sub _nofetch_path {
270 my $self = shift;
271 $self->_property_path('.nofetch');
274 sub _nofetch {
275 my $self = shift;
276 my ($nofetch) = @_;
277 my $np = $self->_nofetch_path;
278 if ($nofetch) {
279 open X, '>'.$np or die "nofetch failed: $!";
280 close X;
281 } else {
282 unlink $np or die "yesfetch failed: $!";
286 sub _group_add {
287 my $self = shift;
288 my ($xtra) = @_;
289 $xtra .= join(',', @{$self->{users}});
290 filedb_atomic_append(jailed_file('/etc/group'),
291 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
294 sub _group_update {
295 my $self = shift;
296 my $xtra = join(',', @{$self->{users}});
297 filedb_atomic_edit(jailed_file('/etc/group'),
298 sub {
299 $_ = $_[0];
300 chomp;
301 if ($self->{name} eq (split /:/)[0]) {
302 # preserve readonly flag
303 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
304 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
305 } else {
306 return "$_\n";
312 sub _group_remove {
313 my $self = shift;
314 filedb_atomic_edit(jailed_file('/etc/group'),
315 sub {
316 $self->{name} ne (split /:/)[0] and return $_;
321 sub _hook_path {
322 my $self = shift;
323 my ($name) = @_;
324 $self->{path}.'/hooks/'.$name;
327 sub _hook_install {
328 my $self = shift;
329 my ($name) = @_;
330 open SRC, "/home/repo/repomgr/$name-hook" or die "cannot open hook $name: $!";
331 open DST, '>'.$self->_hook_path($name) or die "cannot open hook $name for writing: $!";
332 while (<SRC>) { print DST $_; }
333 close DST;
334 close SRC;
335 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
338 sub _hooks_install {
339 my $self = shift;
340 foreach my $hook ('update') {
341 $self->_hook_install($hook);
345 # private constructor, do not use
346 sub _new {
347 my $class = shift;
348 my ($name, $path) = @_;
349 valid_name($name) or die "refusing to create project with invalid name ($name)!";
350 my $proj = { name => $name, path => $path };
352 bless $proj, $class;
355 # public constructor #0
356 # creates a virtual project not connected to disk image
357 # you can conjure() it later to disk
358 sub ghost {
359 my $class = shift;
360 my ($name, $mirror) = @_;
361 my $self = $class->_new($name, $mirror ? "/home/repo/repodata/to-clone/$name" : "/srv/git/$name.git");
362 $self->{users} = [];
363 $self->{mirror} = $mirror;
364 $self;
367 # public constructor #1
368 sub load {
369 my $class = shift;
370 my ($name) = @_;
372 open F, jailed_file("/etc/group") or die "project load failed: $!";
373 while (<F>) {
374 chomp;
375 @_ = split /:+/;
376 next unless (shift eq $name);
378 my $self = $class->_new($name, "/srv/git/$name.git");
379 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
381 my $ulist;
382 ($self->{crypt}, $self->{gid}, $ulist) = @_;
383 $ulist ||= '';
384 $self->{users} = [split /,/, $ulist];
385 $self->{mirror} = ! -e $self->_nofetch_path;
387 $self->_properties_load;
388 return $self;
390 close F;
391 undef;
394 # $proj may not be in sane state if this returns false!
395 sub cgi_fill {
396 my $self = shift;
397 my ($repo) = @_;
398 my $cgi = $repo->cgi;
400 my $pwd = $cgi->param('pwd');
401 if ($pwd ne '' or not $self->{crypt}) {
402 $self->{crypt} = scrypt($pwd);
405 $self->{email} = $repo->wparam('email');
406 valid_email($self->{email})
407 or $repo->err("Your email sure looks weird...?");
409 $self->{url} = $repo->wparam('url');
410 if ($self->{url}) {
411 valid_repo_url($self->{url})
412 or $repo->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
415 $self->{desc} = $repo->wparam('desc');
416 length($self->{desc}) <= 1024
417 or $repo->err("<b>Short</b> description length > 1kb!");
419 $self->{README} = $repo->wparam('README');
420 length($self->{README}) <= 8192
421 or $repo->err("README length > 8kb!");
423 $self->{hp} = $repo->wparam('hp');
424 if ($self->{hp}) {
425 valid_web_url($self->{hp})
426 or $repo->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
429 # FIXME: Permit only existing users
430 $self->{users} = [grep { valid_name($_) } $cgi->param('user')];
432 not $repo->err_check;
435 sub form_defaults {
436 my $self = shift;
438 name => $self->{name},
439 email => $self->{email},
440 url => $self->{url},
441 desc => html_esc($self->{desc}),
442 README => html_esc($self->{README}),
443 hp => $self->{hp},
444 users => $self->{users},
448 sub premirror {
449 my $self = shift;
451 mkdir $self->{path} or die "mkdir failed: $!";
452 chmod 0775, $self->{path} or die "chmod failed: $!";
453 $self->_properties_save;
454 $self->_group_add(':');
457 sub conjure {
458 my $self = shift;
460 system('cg-admin-setuprepo', '-g', 'repo', $self->{path}) == 0
461 or die "cg-admin-setuprepo failed: $?";
462 $self->_nofetch(1);
463 $self->_properties_save;
464 $self->_group_add;
465 $self->_hooks_install;
468 sub update {
469 my $self = shift;
471 $self->_properties_save;
472 $self->_group_update;
475 # You can explicitly do this just on a ghost() repository too.
476 sub delete {
477 my $self = shift;
479 if (-d $self->{path}) {
480 system('rm', '-r', $self->{path}) == 0
481 or die "rm -r failed: $?";
483 $self->_group_remove;
486 # static method
487 sub does_exist {
488 my ($name) = @_;
489 valid_name($name) or die "tried to query for project with invalid name $name!";
490 (available($name)
491 or -d "/home/repo/repodata/cloning/$name"
492 or -d "/home/repo/repodata/to-clone/$name");
494 sub available {
495 my ($name) = @_;
496 valid_name($name) or die "tried to query for project with invalid name $name!";
497 (-d "/srv/git/$name.git");
501 ### User object
503 package Git::RepoCGI::User;
505 BEGIN { use Git::RepoCGI; }
507 sub _passwd_add {
508 my $self = shift;
509 filedb_atomic_append(jailed_file('/etc/passwd'),
510 join(':', $self->{name}, 'x', '\i', 65534, $self->{email}, '/', '/bin/git-shell'));
513 sub _sshkey_path {
514 my $self = shift;
515 '/etc/sshkeys/'.$self->{name};
518 sub _sshkey_save {
519 my $self = shift;
520 open F, ">".jailed_file($self->_sshkey_path) or die "sshkey failed: $!";
521 print F $self->{keys}."\n";
522 close F;
523 chmod 0664, jailed_file($self->_sshkey_path);
526 # private constructor, do not use
527 sub _new {
528 my $class = shift;
529 my ($name) = @_;
530 valid_name($name) or die "refusing to create user with invalid name ($name)!";
531 my $proj = { name => $name };
533 bless $proj, $class;
536 # public constructor #0
537 # creates a virtual user not connected to disk record
538 # you can conjure() it later to disk
539 sub ghost {
540 my $class = shift;
541 my ($name) = @_;
542 my $self = $class->_new($name);
543 $self;
546 # $user may not be in sane state if this returns false!
547 sub cgi_fill {
548 my $self = shift;
549 my ($repo) = @_;
550 my $cgi = $repo->cgi;
552 $self->{name} = $repo->wparam('name');
553 valid_name($self->{name})
554 or $repo->err("Name contains invalid characters.");
556 $self->{email} = $repo->wparam('email');
557 valid_email($self->{email})
558 or $repo->err("Your email sure looks weird...?");
560 $self->{keys} = $cgi->param('keys');
561 length($self->{keys}) <= 4096
562 or $repo->err("The list of keys is more than 4kb. Do you really need that much?");
564 not $repo->err_check;
567 sub conjure {
568 my $self = shift;
570 $self->_passwd_add;
571 $self->_sshkey_save;
574 # static method
575 sub does_exist {
576 my ($name) = @_;
577 valid_name($name) or die "tried to query for user with invalid name $name!";
578 (-e jailed_file("/etc/sshkeys/$name"));
580 sub available {
581 does_exist(@_);