Merge with /srv/git/repo.git
[girocco.git] / cgi / Git / RepoCGI.pm
blobe72ab851e4823512c99700ef655cedbc22f5b792
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;
119 sub jailed_file {
120 my ($filename) = @_;
121 "/home/repo/j/$filename";
124 sub lock_file {
125 my ($path) = @_;
127 $path .= '.lock';
129 use Errno qw(EEXIST);
130 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
131 use IO::Handle;
132 my $handle = new IO::Handle;
134 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
135 my $cnt = 0;
136 while (not sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
137 ($! == EEXIST) or die "$path open failed: $!";
138 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
139 sleep(1);
142 # XXX: filedb-specific
143 chmod 0664, $path or die "$path g+w failed: $!";
145 $handle;
148 sub unlock_file {
149 my ($path) = @_;
151 rename "$path.lock", $path or die "$path unlock failed: $!";
154 sub filedb_atomic_append {
155 my ($file, $line) = @_;
156 my $id = 65536;
158 open my $src, $file or die "$file open for reading failed: $!";
159 my $dst = lock_file($file);
161 while (<$src>) {
162 my $aid = (split /:/)[2];
163 $id = $aid + 1 if ($aid >= $id);
165 print $dst $_ or die "$file(l) write failed: $!";
168 $line =~ s/\\i/$id/g;
169 print $dst "$line\n" or die "$file(l) write failed: $!";
171 close $dst or die "$file(l) close failed: $!";
172 close $src;
174 unlock_file($file);
176 $id;
179 sub filedb_atomic_edit {
180 my ($file, $fn) = @_;
182 open my $src, $file or die "$file open for reading failed: $!";
183 my $dst = lock_file($file);
185 while (<$src>) {
186 print $dst $fn->($_) or die "$file(l) write failed: $!";
189 close $dst or die "$file(l) close failed: $!";
190 close $src;
192 unlock_file($file);
195 # BOTH user AND project name!
196 sub valid_name {
197 $_ = $_[0];
198 /^[a-zA-Z0-9_+-]+$/;
200 sub valid_email {
201 $_ = $_[0];
202 /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9-.]+$/;
204 sub valid_web_url {
205 $_ = $_[0];
206 /^http:\/\/[a-zA-Z0-9-.]+\/[_\%a-zA-Z0-9.\/~-]+(#[a-zA-Z0-9._-]+)?$/;
208 sub valid_repo_url {
209 $_ = $_[0];
210 /^http:\/\/[a-zA-Z0-9-.]+\/[_\%a-zA-Z0-9.\/~-]+$/ or
211 /^git:\/\/[a-zA-Z0-9-.]+\/[_\%a-zA-Z0-9.\/~-]+$/;
215 ### Project object
217 package Git::RepoCGI::Project;
219 BEGIN { use Git::RepoCGI; }
221 our %propmap = (
222 url => 'base_url',
223 email => 'owner',
224 desc => 'description',
225 hp => 'homepage',
228 sub _property_path {
229 my $self = shift;
230 my ($name) = @_;
231 $self->{path}.'/'.$propmap{$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($name) or die "$name get failed: $!";
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";
249 open P, '>'.$self->_property_path($name) or die "$name put failed: $!";
250 $value ne '' and print P "$value\n";
251 close P;
252 chmod 0664, $self->_property_path($name) or die "$name chmod failed: $!";
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 {
270 my $self = shift;
271 my ($nofetch) = @_;
272 my $np = $self->_property_path('.nofetch');
273 if ($nofetch) {
274 open X, '>'.$np or die "nofetch failed: $!";
275 close X;
276 } else {
277 unlink $np or die "yesfetch failed: $!";
281 sub _group_add {
282 my $self = shift;
283 my ($xtra) = @_;
284 $xtra .= join(',', @{$self->{users}});
285 filedb_atomic_append(jailed_file('/etc/group'),
286 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
289 sub _group_update {
290 my $self = shift;
291 my $xtra = join(',', @{$self->{users}});
292 filedb_atomic_edit(jailed_file('/etc/group'),
293 sub {
294 $_ = $_[0];
295 chomp;
296 if ($self->{name} eq (split /:/)[0]) {
297 # preserve readonly flag
298 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
299 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
300 } else {
301 return "$_\n";
307 # private constructor, do not use
308 sub _new {
309 my $class = shift;
310 my ($name, $path) = @_;
311 valid_name($name) or die "refusing to create project with invalid name ($name)!";
312 my $proj = { name => $name, path => $path };
314 bless $proj, $class;
317 # public constructor #0
318 # creates a virtual project not connected to disk image
319 # you can conjure() it later to disk
320 sub ghost {
321 my $class = shift;
322 my ($name, $mirror) = @_;
323 my $self = $class->_new($name, $mirror ? "/home/repo/repodata/to-clone/$name" : "/srv/git/$name.git");
324 $self->{users} = [];
325 $self->{mirror} = $mirror;
326 $self;
329 # public constructor #1
330 sub load {
331 my $class = shift;
332 my ($name) = @_;
334 open F, jailed_file("/etc/group") or die "project load failed: $!";
335 while (<F>) {
336 chomp;
337 @_ = split /:+/;
338 next unless (shift eq $name);
340 my $self = $class->_new($name, "/srv/git/$name.git");
341 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
343 my $ulist;
344 ($self->{crypt}, $self->{gid}, $ulist) = @_;
345 $self->{users} = [split /,/, $ulist];
347 $self->_properties_load;
348 return $self;
350 close F;
351 undef;
354 # $proj may not be in sane state if this returns false!
355 sub cgi_fill {
356 my $self = shift;
357 my ($repo) = @_;
358 my $cgi = $repo->cgi;
360 my $pwd = $cgi->param('pwd');
361 if ($pwd ne '' or not $self->{crypt}) {
362 $self->{crypt} = scrypt($pwd);
365 $self->{email} = $repo->wparam('email');
366 valid_email($self->{email})
367 or $repo->err("Your email sure looks weird...?");
369 $self->{url} = $repo->wparam('url');
370 if ($self->{url}) {
371 valid_repo_url($self->{url})
372 or $repo->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
375 $self->{desc} = $repo->wparam('desc');
376 length($self->{desc}) <= 1024
377 or $repo->err("<b>Short</b> description length > 1kb!");
379 $self->{hp} = $repo->wparam('hp');
380 if ($self->{hp}) {
381 valid_web_url($self->{hp})
382 or $repo->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
385 # FIXME: Permit only existing users
386 $self->{users} = grep { valid_name($_) } $cgi->param('user');
388 $repo->err_check;
391 sub form_defaults {
392 my $self = shift;
394 name => $self->{name},
395 email => $self->{email},
396 url => $self->{url},
397 desc => html_esc($self->{desc}),
398 hp => $self->{hp},
399 users => $self->{users},
403 sub premirror {
404 my $self = shift;
406 mkdir $self->{path} or die "mkdir failed: $!";
407 $self->_properties_save;
408 $self->_group_add;
411 sub conjure {
412 my $self = shift;
414 system('cg-admin-setuprepo', '-g', 'repo', $self->{path}) == 0
415 or die "cg-admin-setuprepo failed: $?";
416 $self->_nofetch(1);
417 $self->_properties_save;
418 chmod 0775, $self->{path} or die "chmod failed: $!";
419 $self->_group_add(':');
422 sub update {
423 my $self = shift;
425 $self->_properties_save;
426 $self->_group_update;
429 # static method
430 sub does_exist {
431 my ($name) = @_;
432 valid_name($name) or die "tried to query for project with invalid name $name!";
433 (available($name)
434 or -d "/home/repo/repodata/cloning/$name"
435 or -d "/home/repo/repodata/to-clone/$name");
437 sub available {
438 my ($name) = @_;
439 valid_name($name) or die "tried to query for project with invalid name $name!";
440 (-d "/srv/git/$name.git");
444 ### User object
446 package Git::RepoCGI::User;
448 BEGIN { use Git::RepoCGI; }
450 sub _passwd_add {
451 my $self = shift;
452 filedb_atomic_append(jailed_file('/etc/passwd'),
453 join(':', $self->{name}, 'x', '\i', $self->{email}, '/', '/bin/git-shell'));
456 sub _sshkey_path {
457 my $self = shift;
458 '/etc/sshkeys/'.$self->{name};
461 sub _sshkey_save {
462 my $self = shift;
463 open F, ">".jailed_file($self->_sshkey_path) or die "sshkey failed: $!";
464 print F $self->{keys}."\n";
465 close F;
466 chmod 0664, jailed_file($self->_sshkey_path);
469 # private constructor, do not use
470 sub _new {
471 my $class = shift;
472 my ($name) = @_;
473 valid_name($name) or die "refusing to create user with invalid name ($name)!";
474 my $proj = { name => $name };
476 bless $proj, $class;
479 # public constructor #0
480 # creates a virtual user not connected to disk record
481 # you can conjure() it later to disk
482 sub ghost {
483 my $class = shift;
484 my ($name) = @_;
485 my $self = $class->_new($name);
486 $self;
489 # $user may not be in sane state if this returns false!
490 sub cgi_fill {
491 my $self = shift;
492 my ($repo) = @_;
493 my $cgi = $repo->cgi;
495 $self->{name} = $repo->wparam('name');
496 valid_name($self->{name})
497 or $repo->err("Name contains invalid characters.");
499 $self->{email} = $repo->wparam('email');
500 valid_email($self->{email})
501 or $repo->err("Your email sure looks weird...?");
503 $self->{keys} = $cgi->param('keys');
504 length($self->{keys}) <= 4096
505 or $repo->err("The list of keys is more than 4kb. Do you really need that much?");
507 $repo->err_check;
510 sub conjure {
511 my $self = shift;
513 $self->_passwd_add;
514 $self->_sshkey_save;
517 # static method
518 sub does_exist {
519 my ($name) = @_;
520 valid_name($name) or die "tried to query for user with invalid name $name!";
521 (-e jailed_file("/etc/sshkeys/$name"));
523 sub available {
524 does_exist(@_);