Project.pm: create and maintain additional project info
[girocco.git] / Girocco / Project.pm
blob412d4c121528533cb63c749cd597dd3b81639ced
1 package Girocco::Project;
3 use strict;
4 use warnings;
6 BEGIN {
7 use Girocco::CGI;
8 use Girocco::User;
9 use Girocco::Util;
10 use Girocco::HashUtil;
11 use Girocco::ProjPerm;
12 use Girocco::Config;
13 use base ('Girocco::ProjPerm::'.$Girocco::Config::permission_control); # mwahaha
16 BEGIN {
17 eval {
18 require Digest::SHA;
19 Digest::SHA->import(
20 qw(sha1_hex)
21 );1} ||
22 eval {
23 require Digest::SHA1;
24 Digest::SHA1->import(
25 qw(sha1_hex)
26 );1} ||
27 eval {
28 require Digest::SHA::PurePerl;
29 Digest::SHA::PurePerl->import(
30 qw(sha1_hex)
31 );1} ||
32 die "One of Digest::SHA or Digest::SHA1 or Digest::SHA::PurePerl "
33 . "must be available\n";
36 our $metadata_fields = {
37 homepage => ['Homepage URL', 'hp', 'text'],
38 shortdesc => ['Short description', 'desc', 'text'],
39 README => ['README (HTML, lt 8kb)', 'README', 'textarea'],
40 notifymail => ['Commit notify - mail to', 'notifymail', 'text'],
41 notifyjson => ['Commit notify - <a href="http://help.github.com/post-receive-hooks/">POST JSON</a> at', 'notifyjson', 'text'],
42 notifycia => ['Commit notify - <a href="http://cia.vc/doc/">CIA project</a> name', 'notifycia', 'text'],
45 sub _mkdir_forkees {
46 my $self = shift;
47 my @pelems = split('/', $self->{name});
48 pop @pelems; # do not create dir for the project itself
49 my $path = $self->{base_path};
50 foreach my $pelem (@pelems) {
51 $path .= "/$pelem";
52 (-d "$path") or mkdir $path or die "mkdir $path: $!";
53 chmod 02775, $path; # ok if fails (dir may already exist and be owned by someone else)
57 # With a leading ':' get from config replacing ':' with 'gitweb.'
58 # With a leading '%' get from config after removing '%'
59 # Otherwise it's a file name to be loaded
60 # %propmapro entries are loaded but never written
62 our %propmap = (
63 url => ':baseurl',
64 email => ':owner',
65 desc => 'description',
66 README => 'README.html',
67 hp => ':homepage',
68 notifymail => '%hooks.mailinglist',
69 notifytag => '%hooks.announcelist',
70 notifyjson => '%hooks.jsonurl',
71 notifycia => '%hooks.cianame',
74 our %propmapro = (
75 lastchange => ':lastchange',
76 lastactivity => 'info/lastactivity',
77 creationtime => '%girocco.creationtime',
78 origurl => ':baseurl',
81 # Projects with any of these names will be disallowed to avoid possible
82 # collisions with cgi script paths or chroot paths
83 our %reservedprojectnames = (
84 b => 1, # /b/ -> bundle.cgi
85 c => 1, # /c/ -> cgit
86 h => 1, # /h/ -> html.cgi
87 r => 1, # /r/ -> git http
88 w => 1, # /w/ -> gitweb
89 srv => 1, # /srv/git/ -> chroot ssh git repositories
92 sub _update_index {
93 my $self = shift;
94 system("$Girocco::Config::basedir/gitweb/genindex.sh", $self->{name});
97 sub _property_path {
98 my $self = shift;
99 my ($name) = @_;
100 $self->{path}.'/'.$name;
103 sub _property_fget {
104 my $self = shift;
105 my ($name) = @_;
106 my $pname = $propmap{$name};
107 $pname = $propmapro{$name} unless $pname;
108 $pname or die "unknown property: $name";
109 if ($pname =~ s/^://) {
110 my $val = get_git("--git-dir=$self->{path}", 'config', "gitweb.$pname");
111 defined($val) or $val = '';
112 chomp $val;
113 return $val;
114 } elsif ($pname =~ s/^%//) {
115 my $val = get_git("--git-dir=$self->{path}", 'config', $pname);
116 defined($val) or $val = '';
117 chomp $val;
118 return $val;
121 open my $p, '<', $self->_property_path($pname) or return undef;
122 my @value = <$p>;
123 close $p;
124 my $value = join('', @value); chomp $value;
125 $value;
128 sub _property_fput {
129 my $self = shift;
130 my ($name, $value) = @_;
131 my $pname = $propmap{$name};
132 $pname or die "unknown property: $name";
133 $value ||= '';
134 if ($pname =~ s/^://) {
135 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
136 return;
137 } elsif ($pname =~ s/^%//) {
138 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
139 return;
142 my $P = lock_file($self->_property_path($pname));
143 $value ne '' and print $P "$value\n";
144 close $P;
145 unlock_file($self->_property_path($pname));
148 sub _properties_load {
149 my $self = shift;
150 foreach my $prop (keys %propmap) {
151 $self->{$prop} = $self->_property_fget($prop);
153 foreach my $prop (keys %propmapro) {
154 $self->{$prop} = $self->_property_fget($prop);
156 my $val = get_git("--git-dir=$self->{path}", 'config', '--bool', 'gitweb.statusupdates');
157 defined($val) or $val = '';
158 chomp $val;
159 $val = ($val eq 'false') ? 0 : 1;
160 $self->{statusupdates} = $val;
161 delete $self->{auth};
162 $val = get_git("--git-dir=$self->{path}", 'config', 'gitweb.repoauth');
163 defined($val) or $val = '';
164 chomp $val;
165 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
166 my $expire = $3;
167 if (time < $expire) {
168 $self->{authtype} = $1;
169 $self->{auth} = $2;
174 sub _properties_save {
175 my $self = shift;
176 my $fd;
177 foreach my $prop (keys %propmap) {
178 $self->_property_fput($prop, $self->{$prop});
180 $self->{statusupdates} = 1
181 unless defined($self->{statusupdates}) && $self->{statusupdates} =~ /^\d+$/;
182 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool',
183 "gitweb.statusupdates", $self->{statusupdates});
184 if (defined($self->{origurl}) && defined($self->{url}) &&
185 $self->{origurl} ne $self->{url} && -e $self->_property_path(".banged")) {
186 if (open($fd, '>', $self->_property_path(".bangagain"))) {
187 close $fd;
188 chmod(0664, $self->_property_path(".bangagain"));
191 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
194 sub _nofetch_path {
195 my $self = shift;
196 $self->_property_path('.nofetch');
199 sub _nofetch {
200 my $self = shift;
201 my ($nofetch) = @_;
202 my $nf = $self->_nofetch_path;
203 if ($nofetch) {
204 open my $x, '>', $nf or die "nofetch failed: $!";
205 close $x;
206 } else {
207 unlink $nf or die "yesfetch failed: $!";
211 sub _clonelog_path {
212 my $self = shift;
213 $self->_property_path('.clonelog');
216 sub _clonefail_path {
217 my $self = shift;
218 $self->_property_path('.clone_failed');
221 sub _clonep_path {
222 my $self = shift;
223 $self->_property_path('.clone_in_progress');
226 sub _clonep {
227 my $self = shift;
228 my ($nofetch) = @_;
229 my $np = $self->_clonep_path;
230 if ($nofetch) {
231 open my $x, '>', $np or die "clonep failed: $!";
232 close $x;
233 } else {
234 unlink $np or die "clonef failed: $!";
237 sub _alternates_setup {
238 my $self = shift;
239 return unless $self->{name} =~ m#/#;
240 my $forkee_name = get_forkee_name($self->{name});
241 my $forkee_path = get_forkee_path($self->{name});
242 return unless -d $forkee_path;
243 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
244 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
245 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
247 # We set up both alternates and http_alternates since we cannot use
248 # relative path in alternates - that doesn't work recursively.
250 my $filename = $self->{path}.'/objects/info/alternates';
251 open my $x, '>', $filename or die "alternates failed: $!";
252 print $x "$forkee_path/objects\n";
253 close $x;
254 chmod 0664, $filename or warn "cannot chmod $filename: $!";
256 if ($Girocco::Config::httppullurl) {
257 $filename = $self->{path}.'/objects/info/http-alternates';
258 open my $x, '>', $filename or die "http-alternates failed: $!";
259 my $upfork = $forkee_name;
260 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
261 close $x;
262 chmod 0664, $filename or warn "cannot chmod $filename: $!";
265 # copy refs from parent project
266 open(SAVEOUT, ">&STDOUT") || die "couldn't dup STDOUT: $!";
267 my $result = open(STDOUT, '>', "$self->{path}/packed-refs");
268 my $resultstr = $!;
269 if (!$result) {
270 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
271 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
272 die "could not write fork's packed-refs file: $resultstr";
274 system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
275 $result = close(STDOUT);
276 $resultstr = $!;
277 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
278 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
279 $result or die "could not close fork's packed-refs file: $resultstr";
281 # initialize HEAD
282 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
283 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
284 chomp $HEAD;
285 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
286 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
289 sub _ctags_setup {
290 my $self = shift;
291 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
292 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
295 sub _group_add {
296 my $self = shift;
297 my ($xtra) = @_;
298 $xtra .= join(',', @{$self->{users}});
299 filedb_atomic_append(jailed_file('/etc/group'),
300 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
303 sub _group_update {
304 my $self = shift;
305 my $xtra = join(',', @{$self->{users}});
306 filedb_atomic_edit(jailed_file('/etc/group'),
307 sub {
308 $_ = $_[0];
309 chomp;
310 if ($self->{name} eq (split /:/)[0]) {
311 # preserve readonly flag
312 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
313 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
314 } else {
315 return "$_\n";
321 sub _group_remove {
322 my $self = shift;
323 filedb_atomic_edit(jailed_file('/etc/group'),
324 sub {
325 $self->{name} ne (split /:/)[0] and return $_;
330 sub _hook_path {
331 my $self = shift;
332 my ($name) = @_;
333 $self->{path}.'/hooks/'.$name;
336 sub _hook_install {
337 my $self = shift;
338 my ($name) = @_;
339 my $hooksdir = $self->{path}.'/hooks';
340 -d $hooksdir or mkdir $hooksdir or
341 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
342 open my $src, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
343 open my $dst, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
344 while (<$src>) { print $dst $_; }
345 close $dst;
346 close $src;
347 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
350 sub _hooks_install {
351 my $self = shift;
352 foreach my $hook ('pre-receive', 'post-receive', 'update', 'post-update') {
353 $self->_hook_install($hook);
357 # private constructor, do not use
358 sub _new {
359 my $class = shift;
360 my ($name, $base_path, $path) = @_;
361 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
362 $path ||= "$base_path/$name.git";
363 my $proj = { name => $name, base_path => $base_path, path => $path };
365 bless $proj, $class;
368 # public constructor #0
369 # creates a virtual project not connected to disk image
370 # you can conjure() it later to disk
371 sub ghost {
372 my $class = shift;
373 my ($name, $mirror) = @_;
374 my $self = $class->_new($name, $Girocco::Config::reporoot);
375 $self->{users} = [];
376 $self->{mirror} = $mirror;
377 $self->{email} = $self->{orig_email} = '';
378 $self;
381 # public constructor #1
382 sub load {
383 my $class = shift;
384 my $name = shift || '';
386 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
387 my $r = qr/^\Q$name\E:/;
388 foreach (grep /$r/, <$fd>) {
389 chomp;
391 my $self = $class->_new($name, $Girocco::Config::reporoot);
392 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
394 my $ulist;
395 (undef, $self->{crypt}, $self->{gid}, $ulist) = split /:/;
396 $ulist ||= '';
397 $self->{users} = [split /,/, $ulist];
398 $self->{HEAD} = $self->get_HEAD;
399 $self->{orig_HEAD} = $self->{HEAD};
400 $self->{orig_users} = [@{$self->{users}}];
401 $self->{mirror} = ! -e $self->_nofetch_path;
402 $self->{clone_in_progress} = -e $self->_clonep_path;
403 $self->{clone_logged} = -e $self->_clonelog_path;
404 $self->{clone_failed} = -e $self->_clonefail_path;
405 $self->{ccrypt} = $self->{crypt};
407 $self->_properties_load;
408 $self->{orig_email} = $self->{email};
409 $self->{loaded} = 1; # indicates self was loaded from etc/group file
410 close $fd;
411 return $self;
413 close $fd;
414 undef;
417 # $proj may not be in sane state if this returns false!
418 sub cgi_fill {
419 my $self = shift;
420 my ($gcgi) = @_;
421 my $cgi = $gcgi->cgi;
423 my ($pwd, $pwd2) = ($cgi->param('pwd'), $cgi->param('pwd2'));
424 # in case passwords are disabled
425 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
426 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
427 $gcgi->err("Empty passwords are not permitted.");
429 if ($pwd ne '' or not $self->{crypt}) {
430 $self->{crypt} = scrypt_sha1($pwd);
432 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
433 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
436 $self->{cpwd} = $cgi->param('cpwd');
438 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
439 my $newtype = $forkee ? 'fork' : 'project';
440 length($project) <= 64
441 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
443 if ($Girocco::Config::project_owners eq 'email') {
444 $self->{email} = $gcgi->wparam('email');
445 valid_email($self->{email})
446 or $gcgi->err("Your email sure looks weird...?");
447 length($self->{email}) <= 96
448 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
451 $self->{url} = $gcgi->wparam('url');
452 if ($self->{url}) {
453 valid_repo_url($self->{url})
454 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
455 if ($Girocco::Config::restrict_mirror_hosts) {
456 my $mh = extract_url_hostname($self->{url});
457 is_dns_hostname($mh)
458 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
459 !is_our_hostname($mh)
460 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
464 $self->{desc} = $gcgi->wparam('desc');
465 length($self->{desc}) <= 1024
466 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
468 $self->{README} = $gcgi->wparam('README');
469 length($self->{README}) <= 8192
470 or $gcgi->err("README length &gt; 8kb!");
472 $self->{hp} = $gcgi->wparam('hp');
473 if ($self->{hp}) {
474 valid_web_url($self->{hp})
475 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
478 my %users = ();
479 my @users = ();
480 foreach my $user ($cgi->param('user')) {
481 if (!exists($users{$user})) {
482 $users{$user} = 1;
483 push(@users, $user) if Girocco::User::valid_name($user) && Girocco::User::does_exist($user)
486 $self->{users} = \@users;
488 $self->{HEAD} = $cgi->param('HEAD') if $cgi->param('HEAD');
490 # schedule deletion of tags (will be committed by update() after auth)
491 $self->{tags_to_delete} = [$cgi->param('tags')];
493 $self->{notifymail} = $gcgi->wparam('notifymail');
494 if ($self->{notifymail}) {
495 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
496 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
499 $self->{notifyjson} = $gcgi->wparam('notifyjson');
500 if ($self->{notifyjson}) {
501 valid_web_url($self->{notifyjson})
502 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
505 $self->{notifycia} = $gcgi->wparam('notifycia');
506 if ($self->{notifycia}) {
507 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
508 or $gcgi->err("Overly suspicious CIA notify project name. If it is actually valid, contact me.");
511 if ($cgi->param('setstatusupdates')) {
512 my $val = $gcgi->wparam('statusupdates') || '0';
513 $self->{statusupdates} = $val ? 1 : 0;
516 not $gcgi->err_check;
519 sub form_defaults {
520 my $self = shift;
522 name => $self->{name},
523 email => $self->{email},
524 url => $self->{url},
525 desc => html_esc($self->{desc}),
526 README => html_esc($self->{README}),
527 hp => $self->{hp},
528 users => $self->{users},
529 notifymail => html_esc($self->{notifymail}),
530 notifyjson => html_esc($self->{notifyjson}),
531 notifycia => html_esc($self->{notifycia}),
535 # return true if $enc_passwd is a match for $plain_passwd
536 my $_check_passwd_match = sub {
537 my $enc_passwd = shift;
538 my $plain_passwd = shift;
539 defined($enc_passwd) or $enc_passwd = '';
540 defined($plain_passwd) or $plain_passwd = '';
541 # $enc_passwd may be crypt or crypt_sha1
542 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
543 # It's using sha1-crypt
544 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
545 } else {
546 # It's using crypt
547 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
551 sub authenticate {
552 my $self = shift;
553 my ($gcgi) = @_;
555 $self->{ccrypt} or die "Can't authenticate against a project with no password";
556 defined($self->{cpwd}) or $self->{cpwd} = '';
557 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
558 $gcgi->err("Your admin password does not match!");
559 return 0;
561 return 1;
564 # return true if the password from the file is empty or consists of all the same
565 # character. However, if the project was NOT loaded from the group file
566 # (!self->{loaded}) then the password is never locked.
567 # This function does NOT check $Girocco::Config::project_passwords, the caller
568 # is responsible for doing so if desired. Same for $self->{email}.
569 sub is_password_locked {
570 my $self = shift;
572 $self->{loaded} or return 0;
573 my $testcrypt = $self->{ccrypt}; # The value from the group file
574 defined($testcrypt) or $testcrypt = '';
575 $testcrypt ne '' or return 1; # No password at all
576 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
577 return 0; # Not locked
580 sub _setup {
581 use POSIX qw(strftime);
582 my $self = shift;
583 my ($pushers) = @_;
584 my $fd;
586 $self->_mkdir_forkees;
588 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
589 if ($Girocco::Config::owning_group) {
590 my $gid = scalar(getgrnam($Girocco::Config::owning_group));
591 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
592 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
593 } else {
594 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
596 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
597 or die "git init $self->{path} failed: $?";
598 -d $self->{path}."/info" or mkdir $self->{path}."/info"
599 or die "info directory does not exist and unable to create it: $!";
600 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
601 or die "disabling receive.denyNonFastforwards failed: $?";
602 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
603 or die "disabling gc.auto failed: $?";
604 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
605 or die "disabling receive.autogc failed: $?";
606 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
607 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
608 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
609 or die "setting girocco.creationtime failed: $?";
610 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateserverinfo', 'true') == 0
611 or die "enabling receive.updateserverinfo failed: $?";
612 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writebitmaps', 'true') == 0
613 or die "enabling repack.writebitmaps failed: $?";
614 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
615 or die "htmlcache directory does not exist and unable to create it: $!";
616 if (open $fd, '>', $self->{path}."/info/lastactivity") {
617 close $fd;
618 chmod 0664, $self->{path}."/info/lastactivity";
621 # /info must have right permissions,
622 # and git init didn't do it for some reason.
623 # config must have correct permissions.
624 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
625 if ($Girocco::Config::owning_group) {
626 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
627 chmod(02775, $self->{path}."/htmlcache") or die "chmod 02775 $self->{path}/htmlcache failed: $!";
628 chmod(0664, $self->{path}."/config") or die "chmod 0664 $self->{path}/config failed: $!";
629 } else {
630 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
631 chmod(02777, $self->{path}."/htmlcache") or die "chmod 02777 $self->{path}/htmlcache failed: $!";
632 chmod(0666, $self->{path}."/config") or die "chmod 0666 $self->{path}/config failed: $!";
635 $self->_properties_save;
636 $self->_alternates_setup;
637 $self->_ctags_setup;
638 $self->_group_remove;
639 $self->_group_add($pushers);
640 $self->_hooks_install;
641 #$self->perm_initialize;
642 $self->_update_index;
645 sub premirror {
646 my $self = shift;
648 $self->_setup(':');
649 $self->_clonep(1);
650 $self->perm_initialize;
653 sub conjure {
654 my $self = shift;
656 $self->_setup;
657 $self->_nofetch(1);
658 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
659 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
660 or die "create-personal-mob-area $self->{name} failed";
662 $self->perm_initialize;
665 sub clone {
666 my $self = shift;
668 unlink ($self->_clonefail_path()); # Ignore EEXIST error
669 unlink ($self->_clonelog_path()); # Ignore EEXIST error
671 use IO::Socket;
672 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
673 $sock->print("clone ".$self->{name}."\n");
674 # Just ignore reply, we are going to succeed anyway and the I/O
675 # would apparently get quite hairy.
676 $sock->flush();
677 sleep 2; # *cough*
678 $sock->close();
681 sub update {
682 my $self = shift;
684 $self->_properties_save;
685 $self->_group_update;
687 if (exists($self->{tags_to_delete})) {
688 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
691 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
693 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
694 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
695 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
696 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
698 $self->_update_index if $self->{email} ne $self->{orig_email};
699 $self->{orig_email} = $self->{email};
704 sub update_password {
705 my $self = shift;
706 my ($pwd) = @_;
708 $self->{crypt} = scrypt_sha1($pwd);
709 $self->_group_update;
712 # You can explicitly do this just on a ghost() repository too.
713 sub delete {
714 my $self = shift;
716 if (-d $self->{path}) {
717 system('rm', '-rf', $self->{path}) == 0
718 or die "rm -rf $self->{path} failed: $?";
720 # attempt to clean up any empty fork directories by removing them
721 my @pelems = split('/', $self->{name});
722 while (@pelems > 1) {
723 pop @pelems;
724 # okay to fail
725 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
727 $self->_group_remove;
728 $self->_update_index;
731 sub _contains_files {
732 my $dir = shift;
733 (-d $dir) or return 0;
734 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
735 while (my $entry = readdir($dh)) {
736 next if $entry eq '' || $entry eq '.' || $entry eq '..';
737 closedir($dh), return 1
738 if -f "$dir/$entry" ||
739 -d "$dir/$entry" && _contains_files("$dir/$entry");
741 closedir($dh);
742 return 0;
745 sub has_forks {
746 my $self = shift;
748 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
751 sub is_empty {
752 # A project is considered empty if the git repository does not
753 # have any refs. This means packed-refs does not exist or is
754 # empty or only has lines starting with '#' AND there are no
755 # files in the refs subdirectory hierarchy (no matter how deep).
757 my $self = shift;
759 (-d $self->{path}) or return 0;
760 if (-e $self->{path}.'/packed-refs') {
761 open(my $pr, '<', $self->{path}.'/packed-refs')
762 or die "open $self->{path}./packed-refs failed: $!";
763 my $foundref = 0;
764 while (my $ref = <$pr>) {
765 next if $ref =~ /^#/;
766 $foundref = 1;
767 last;
769 close($pr);
770 return 0 if $foundref;
772 (-d $self->{path}.'/refs') or return 1;
773 return !_contains_files($self->{path}.'/refs');
776 sub delete_ctag {
777 my $self = shift;
778 my ($ctag) = @_;
780 # sanity check, disallow filenames starting with . .. or /
781 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
784 sub get_ctag_names {
785 my $self = shift;
786 my @ctags = ();
787 opendir(my $dh, $self->{path}.'/ctags')
788 or return @ctags;
789 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
790 closedir($dh);
791 return @ctags;
794 sub get_heads {
795 my $self = shift;
796 my $fh;
797 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
798 defined($heads) or $heads = '';
799 chomp $heads;
800 my @res = ();
801 foreach (split(/\n/, $heads)) {
802 chomp;
803 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
804 push @res, $1;
806 @res;
809 sub get_HEAD {
810 my $self = shift;
811 my $HEAD = get_git("--git-dir=$self->{path}", 'symbolic-ref', 'HEAD');
812 defined($HEAD) or $HEAD = '';
813 chomp $HEAD;
814 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
815 return $1;
818 sub set_HEAD {
819 my $self = shift;
820 my $newHEAD = shift;
821 # Cursory checks only -- if you want to break your HEAD, be my guest
822 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
823 die "grossly invalid new HEAD: $newHEAD";
825 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
826 die "could not set HEAD" if ($? >> 8);
827 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
828 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
831 sub gen_auth {
832 my $self = shift;
833 my ($type) = @_;
834 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
836 $self->{authtype} = $type;
838 no warnings;
839 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
841 my $expire = time + 24 * 3600;
842 my $propval = "# ${type}AUTH $self->{auth} $expire";
843 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
844 $self->{auth};
847 sub del_auth {
848 my $self = shift;
850 delete $self->{auth};
851 delete $self->{authtype};
852 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
855 sub remove_user {
856 my $self = shift;
857 my ($username) = @_;
859 my $before_count = @{$self->{users}};
860 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
861 return @{$self->{users}} != $before_count;
864 ### static methods
866 sub get_forkee_name {
867 local $_ = $_[0];
868 (m#^(.*)/.*?$#)[0]; #
871 sub get_forkee_path {
872 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
873 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
874 -d $forkee ? $forkee : '';
877 # Ultimately the full project/fork name could end up being part of a Git ref name
878 # when a project's forks are combined into one giant repository for efficiency.
879 # That means that the project/fork name must satisfy the Git ref name requirements:
881 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
882 # 2. The character with an ASCII value of 0x7F is not allowed
883 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
884 # 4. The character '/' is a separator and is not allowed within a name
885 # 5. The name may not start with '.' or end with '.'
886 # 6. The name may not end with '.lock'
887 # 7. The name may not contain the '..' sequence
888 # 8. The name may not contain the '@{' sequence
889 # 9. If multiple components are used (separated by '/'), no empty '' components
891 # We also prohibit a trailing '.git' on any path component and futher restrict
892 # the allowed characters to alphanumeric and [+._-] where names must start with
893 # an alphanumeric.
895 sub _valid_name_characters {
896 local $_ = $_[0];
897 (not m#^[/+._-]#)
898 and (not m#//#)
899 and (not m#\.\.#)
900 and (not m#/[+._-]#)
901 and (not m#\./#)
902 and (not m#\.$#)
903 and (not m#\.git/#i)
904 and (not m#\.git$#i)
905 and (not m#\.lock/#i)
906 and (not m#\.lock$#i)
907 and (not m#/$#)
908 and m#^[a-zA-Z0-9/+._-]+$#;
911 sub valid_name {
912 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
913 local $_ = $_[0];
914 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
915 and @{[m#/#g]} <= 5 # maximum fork depth is 5
916 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
919 # It's possible that some forks have been kept but the forkee is gone.
920 # In this case the standard valid_name check is too strict.
921 sub does_exist {
922 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
923 my ($name, $nodie) = @_;
924 my $okay = (
925 _valid_name_characters($name)
926 and ((not $name =~ m#/#)
927 or -d get_forkee_path($name)
928 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
929 (!$okay && $nodie) and return undef;
930 !$okay and die "tried to query for project with invalid name $name!";
931 (-d $Girocco::Config::reporoot."/$name.git");
934 sub get_full_list {
935 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
936 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
937 close $fd;
938 @projects;