Export lock_file, unlock_file
[girocco.git] / cgi / Git / RepoCGI.pm
blobed505e745dba5b4946008c51713500ef2c71b639
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
50 </div>
52 <h1>$heading</h1>
53 EOT
55 bless $repo, $class;
58 sub DESTROY {
59 my $self = shift;
60 my $cgi = $self->cgi;
61 my $cginame = $cgi->url(-absolute => 1);
62 $cginame =~ s#^/m/##;
63 if ($cginame =~ /^[a-zA-Z0-9_.\/-]+\.cgi$/) {
64 print <<EOT;
65 <div align="right">
66 <a href="http://repo.or.cz/w/repo.git?a=blob;f=cgi/$cginame">(view source)</a>
67 </div>
68 EOT
70 print <<EOT;
71 </body>
72 </html>
73 EOT
76 sub cgi {
77 my $self = shift;
78 $self->{cgi};
81 sub err {
82 my $self = shift;
83 print "<p style=\"text-color: red\">@_</p>\n";
84 $self->{err}++;
87 sub err_check {
88 my $self = shift;
89 my $err = $self->{err};
90 $err and print "<p>Operation aborted due to $err errors.</p>\n";
91 $err;
94 sub wparam {
95 my $self = shift;
96 my ($param) = @_;
97 my $val = $self->{cgi}->param($param);
98 $val =~ s/^\s*(.*?)\s*$/$1/;
99 $val;
103 ### Random utility functions
105 sub scrypt {
106 my ($pwd) = @_;
107 crypt($pwd, join ('', ('.', '/', 2..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
110 sub html_esc {
111 my ($str) = @_;
112 $str =~ s/&/&amp;/g;
113 $str =~ s/</&lt;/g; $str =~ s/>/&gt;/g;
114 $str =~ s/"/&quot;/g;
115 $str;
118 sub jailed_file {
119 my ($filename) = @_;
120 "/home/repo/j/$filename";
123 sub lock_file {
124 my ($path) = @_;
126 $path .= '.lock';
128 use Errno qw(EEXIST);
129 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
130 use IO::Handle;
131 my $handle = new IO::Handle;
133 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
134 my $cnt = 0;
135 while (not sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
136 ($! == EEXIST) or die "$path open failed: $!";
137 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
138 sleep(1);
141 # XXX: filedb-specific
142 chmod 0664, $path or die "$path g+w failed: $!";
144 $handle;
147 sub unlock_file {
148 my ($path) = @_;
150 rename "$path.lock", $path or die "$path unlock failed: $!";
153 sub filedb_atomic_append {
154 my ($file, $line) = @_;
155 my $id = 65536;
157 open my $src, $file or die "$file open for reading failed: $!";
158 my $dst = lock_file($file);
160 while (<$src>) {
161 my $aid = (split /:/)[2];
162 $id = $aid + 1 if ($aid >= $id);
164 print $dst $_ or die "$file(l) write failed: $!";
167 $line =~ s/\\i/$id/g;
168 print $dst "$line\n" or die "$file(l) write failed: $!";
170 close $dst or die "$file(l) close failed: $!";
171 close $src;
173 unlock_file($file);
175 $id;
178 sub filedb_atomic_edit {
179 my ($file, $fn) = @_;
181 open my $src, $file or die "$file open for reading failed: $!";
182 my $dst = lock_file($file);
184 while (<$src>) {
185 print $dst $fn->($_) or die "$file(l) write failed: $!";
188 close $dst or die "$file(l) close failed: $!";
189 close $src;
191 unlock_file($file);
194 # BOTH user AND project name!
195 sub valid_name {
196 $_ = $_[0];
197 /^[a-zA-Z0-9_+-]+$/;
199 sub valid_email {
200 $_ = $_[0];
201 /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9-.]+$/;
203 sub valid_web_url {
204 $_ = $_[0];
205 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?(#[a-zA-Z0-9._-]+)?$/;
207 sub valid_repo_url {
208 $_ = $_[0];
209 /^http:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/ or
210 /^git:\/\/[a-zA-Z0-9-.]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/;
214 ### Project object
216 package Git::RepoCGI::Project;
218 BEGIN { use Git::RepoCGI; }
220 our %propmap = (
221 url => 'base_url',
222 email => 'owner',
223 desc => 'description',
224 README => 'README',
225 hp => 'homepage',
228 sub _property_path {
229 my $self = shift;
230 my ($name) = @_;
231 $self->{path}.'/'.$name;
234 sub _property_fget {
235 my $self = shift;
236 my ($name) = @_;
237 my $value;
238 $propmap{$name} or die "unknown property: $name";
239 open P, $self->_property_path($propmap{$name}) or return undef;
240 chomp($value = <P>);
241 close P;
242 $value;
245 sub _property_fput {
246 my $self = shift;
247 my ($name, $value) = @_;
248 $propmap{$name} or die "unknown property: $name";
250 my $P = lock_file($propmap{$name});
251 $value ne '' and print $P "$value\n";
252 close $P;
253 unlock_file($propmap{$name});
256 sub _properties_load {
257 my $self = shift;
258 foreach my $prop (keys %propmap) {
259 $self->{$prop} = $self->_property_fget($prop);
263 sub _properties_save {
264 my $self = shift;
265 foreach my $prop (keys %propmap) {
266 $self->_property_fput($prop, $self->{$prop});
270 sub _nofetch_path {
271 my $self = shift;
272 $self->_property_path('.nofetch');
275 sub _nofetch {
276 my $self = shift;
277 my ($nofetch) = @_;
278 my $np = $self->_nofetch_path;
279 if ($nofetch) {
280 open X, '>'.$np or die "nofetch failed: $!";
281 close X;
282 } else {
283 unlink $np or die "yesfetch failed: $!";
287 sub _group_add {
288 my $self = shift;
289 my ($xtra) = @_;
290 $xtra .= join(',', @{$self->{users}});
291 filedb_atomic_append(jailed_file('/etc/group'),
292 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
295 sub _group_update {
296 my $self = shift;
297 my $xtra = join(',', @{$self->{users}});
298 filedb_atomic_edit(jailed_file('/etc/group'),
299 sub {
300 $_ = $_[0];
301 chomp;
302 if ($self->{name} eq (split /:/)[0]) {
303 # preserve readonly flag
304 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
305 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
306 } else {
307 return "$_\n";
313 sub _group_remove {
314 my $self = shift;
315 filedb_atomic_edit(jailed_file('/etc/group'),
316 sub {
317 $self->{name} ne (split /:/)[0] and return $_;
322 sub _hook_path {
323 my $self = shift;
324 my ($name) = @_;
325 $self->{path}.'/hooks/'.$name;
328 sub _hook_install {
329 my $self = shift;
330 my ($name) = @_;
331 open SRC, "/home/repo/repomgr/$name-hook" or die "cannot open hook $name: $!";
332 open DST, '>'.$self->_hook_path($name) or die "cannot open hook $name for writing: $!";
333 while (<SRC>) { print DST $_; }
334 close DST;
335 close SRC;
336 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
339 sub _hooks_install {
340 my $self = shift;
341 foreach my $hook ('update') {
342 $self->_hook_install($hook);
346 # private constructor, do not use
347 sub _new {
348 my $class = shift;
349 my ($name, $path) = @_;
350 valid_name($name) or die "refusing to create project with invalid name ($name)!";
351 my $proj = { name => $name, path => $path };
353 bless $proj, $class;
356 # public constructor #0
357 # creates a virtual project not connected to disk image
358 # you can conjure() it later to disk
359 sub ghost {
360 my $class = shift;
361 my ($name, $mirror) = @_;
362 my $self = $class->_new($name, $mirror ? "/home/repo/repodata/to-clone/$name" : "/srv/git/$name.git");
363 $self->{users} = [];
364 $self->{mirror} = $mirror;
365 $self;
368 # public constructor #1
369 sub load {
370 my $class = shift;
371 my ($name) = @_;
373 open F, jailed_file("/etc/group") or die "project load failed: $!";
374 while (<F>) {
375 chomp;
376 @_ = split /:+/;
377 next unless (shift eq $name);
379 my $self = $class->_new($name, "/srv/git/$name.git");
380 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
382 my $ulist;
383 ($self->{crypt}, $self->{gid}, $ulist) = @_;
384 $ulist ||= '';
385 $self->{users} = [split /,/, $ulist];
386 $self->{mirror} = ! -e $self->_nofetch_path;
388 $self->_properties_load;
389 return $self;
391 close F;
392 undef;
395 # $proj may not be in sane state if this returns false!
396 sub cgi_fill {
397 my $self = shift;
398 my ($repo) = @_;
399 my $cgi = $repo->cgi;
401 my $pwd = $cgi->param('pwd');
402 if ($pwd ne '' or not $self->{crypt}) {
403 $self->{crypt} = scrypt($pwd);
406 $self->{email} = $repo->wparam('email');
407 valid_email($self->{email})
408 or $repo->err("Your email sure looks weird...?");
410 $self->{url} = $repo->wparam('url');
411 if ($self->{url}) {
412 valid_repo_url($self->{url})
413 or $repo->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
416 $self->{desc} = $repo->wparam('desc');
417 length($self->{desc}) <= 1024
418 or $repo->err("<b>Short</b> description length > 1kb!");
420 $self->{README} = $repo->wparam('README');
421 length($self->{README}) <= 8192
422 or $repo->err("README length > 8kb!");
424 $self->{hp} = $repo->wparam('hp');
425 if ($self->{hp}) {
426 valid_web_url($self->{hp})
427 or $repo->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
430 # FIXME: Permit only existing users
431 $self->{users} = [grep { valid_name($_) } $cgi->param('user')];
433 not $repo->err_check;
436 sub form_defaults {
437 my $self = shift;
439 name => $self->{name},
440 email => $self->{email},
441 url => $self->{url},
442 desc => html_esc($self->{desc}),
443 README => html_esc($self->{README}),
444 hp => $self->{hp},
445 users => $self->{users},
449 sub premirror {
450 my $self = shift;
452 mkdir $self->{path} or die "mkdir failed: $!";
453 chmod 0775, $self->{path} or die "chmod failed: $!";
454 $self->_properties_save;
455 $self->_group_add(':');
458 sub conjure {
459 my $self = shift;
461 system('cg-admin-setuprepo', '-g', 'repo', $self->{path}) == 0
462 or die "cg-admin-setuprepo failed: $?";
463 $self->_nofetch(1);
464 $self->_properties_save;
465 $self->_group_add;
466 $self->_hooks_install;
469 sub update {
470 my $self = shift;
472 $self->_properties_save;
473 $self->_group_update;
476 # You can explicitly do this just on a ghost() repository too.
477 sub delete {
478 my $self = shift;
480 if (-d $self->{path}) {
481 system('rm', '-r', $self->{path}) == 0
482 or die "rm -r failed: $?";
484 $self->_group_remove;
487 # static method
488 sub does_exist {
489 my ($name) = @_;
490 valid_name($name) or die "tried to query for project with invalid name $name!";
491 (available($name)
492 or -d "/home/repo/repodata/cloning/$name"
493 or -d "/home/repo/repodata/to-clone/$name");
495 sub available {
496 my ($name) = @_;
497 valid_name($name) or die "tried to query for project with invalid name $name!";
498 (-d "/srv/git/$name.git");
502 ### User object
504 package Git::RepoCGI::User;
506 BEGIN { use Git::RepoCGI; }
508 sub _passwd_add {
509 my $self = shift;
510 filedb_atomic_append(jailed_file('/etc/passwd'),
511 join(':', $self->{name}, 'x', '\i', 65534, $self->{email}, '/', '/bin/git-shell'));
514 sub _sshkey_path {
515 my $self = shift;
516 '/etc/sshkeys/'.$self->{name};
519 sub _sshkey_save {
520 my $self = shift;
521 open F, ">".jailed_file($self->_sshkey_path) or die "sshkey failed: $!";
522 print F $self->{keys}."\n";
523 close F;
524 chmod 0664, jailed_file($self->_sshkey_path);
527 # private constructor, do not use
528 sub _new {
529 my $class = shift;
530 my ($name) = @_;
531 valid_name($name) or die "refusing to create user with invalid name ($name)!";
532 my $proj = { name => $name };
534 bless $proj, $class;
537 # public constructor #0
538 # creates a virtual user not connected to disk record
539 # you can conjure() it later to disk
540 sub ghost {
541 my $class = shift;
542 my ($name) = @_;
543 my $self = $class->_new($name);
544 $self;
547 # $user may not be in sane state if this returns false!
548 sub cgi_fill {
549 my $self = shift;
550 my ($repo) = @_;
551 my $cgi = $repo->cgi;
553 $self->{name} = $repo->wparam('name');
554 valid_name($self->{name})
555 or $repo->err("Name contains invalid characters.");
557 $self->{email} = $repo->wparam('email');
558 valid_email($self->{email})
559 or $repo->err("Your email sure looks weird...?");
561 $self->{keys} = $cgi->param('keys');
562 length($self->{keys}) <= 4096
563 or $repo->err("The list of keys is more than 4kb. Do you really need that much?");
565 not $repo->err_check;
568 sub conjure {
569 my $self = shift;
571 $self->_passwd_add;
572 $self->_sshkey_save;
575 # static method
576 sub does_exist {
577 my ($name) = @_;
578 valid_name($name) or die "tried to query for user with invalid name $name!";
579 (-e jailed_file("/etc/sshkeys/$name"));
581 sub available {
582 does_exist(@_);