check-perl-modules: clarify informational text
[girocco.git] / Girocco / Project.pm
blobfe60c60bf23b6b535f0cfe2ecf135989bf3c5892
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 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 foreach my $prop (keys %propmap) {
177 $self->_property_fput($prop, $self->{$prop});
179 $self->{statusupdates} = 1
180 unless defined($self->{statusupdates}) && $self->{statusupdates} =~ /^\d+$/;
181 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool',
182 "gitweb.statusupdates", $self->{statusupdates});
183 if (defined($self->{origurl}) && defined($self->{url}) &&
184 $self->{origurl} ne $self->{url} && -e $self->_property_path(".banged")) {
185 if (open(X, '>', $self->_property_path(".bangagain"))) {
186 close X;
187 chmod(0664, $self->_property_path(".bangagain"));
192 sub _nofetch_path {
193 my $self = shift;
194 $self->_property_path('.nofetch');
197 sub _nofetch {
198 my $self = shift;
199 my ($nofetch) = @_;
200 my $nf = $self->_nofetch_path;
201 if ($nofetch) {
202 open X, '>', $nf or die "nofetch failed: $!";
203 close X;
204 } else {
205 unlink $nf or die "yesfetch failed: $!";
209 sub _clonelog_path {
210 my $self = shift;
211 $self->_property_path('.clonelog');
214 sub _clonefail_path {
215 my $self = shift;
216 $self->_property_path('.clone_failed');
219 sub _clonep_path {
220 my $self = shift;
221 $self->_property_path('.clone_in_progress');
224 sub _clonep {
225 my $self = shift;
226 my ($nofetch) = @_;
227 my $np = $self->_clonep_path;
228 if ($nofetch) {
229 open X, '>', $np or die "clonep failed: $!";
230 close X;
231 } else {
232 unlink $np or die "clonef failed: $!";
235 sub _alternates_setup {
236 my $self = shift;
237 return unless $self->{name} =~ m#/#;
238 my $forkee_name = get_forkee_name($self->{name});
239 my $forkee_path = get_forkee_path($self->{name});
240 return unless -d $forkee_path;
241 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
242 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
243 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
245 # We set up both alternates and http_alternates since we cannot use
246 # relative path in alternates - that doesn't work recursively.
248 my $filename = $self->{path}.'/objects/info/alternates';
249 open X, '>', $filename or die "alternates failed: $!";
250 print X "$forkee_path/objects\n";
251 close X;
252 chmod 0664, $filename or warn "cannot chmod $filename: $!";
254 if ($Girocco::Config::httppullurl) {
255 $filename = $self->{path}.'/objects/info/http-alternates';
256 open X, '>', $filename or die "http-alternates failed: $!";
257 my $upfork = $forkee_name;
258 do { print X "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
259 close X;
260 chmod 0664, $filename or warn "cannot chmod $filename: $!";
263 # copy refs from parent project
264 open(SAVEOUT, ">&STDOUT") || die "couldn't dup STDOUT: $!";
265 my $result = open(STDOUT, '>', "$self->{path}/packed-refs");
266 my $resultstr = $!;
267 if (!$result) {
268 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
269 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
270 die "could not write fork's packed-refs file: $resultstr";
272 system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
273 $result = close(STDOUT);
274 $resultstr = $!;
275 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
276 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
277 $result or die "could not close fork's packed-refs file: $resultstr";
279 # initialize HEAD
280 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
281 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
282 chomp $HEAD;
283 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
284 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
287 sub _ctags_setup {
288 my $self = shift;
289 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
290 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
293 sub _group_add {
294 my $self = shift;
295 my ($xtra) = @_;
296 $xtra .= join(',', @{$self->{users}});
297 filedb_atomic_append(jailed_file('/etc/group'),
298 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
301 sub _group_update {
302 my $self = shift;
303 my $xtra = join(',', @{$self->{users}});
304 filedb_atomic_edit(jailed_file('/etc/group'),
305 sub {
306 $_ = $_[0];
307 chomp;
308 if ($self->{name} eq (split /:/)[0]) {
309 # preserve readonly flag
310 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
311 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
312 } else {
313 return "$_\n";
319 sub _group_remove {
320 my $self = shift;
321 filedb_atomic_edit(jailed_file('/etc/group'),
322 sub {
323 $self->{name} ne (split /:/)[0] and return $_;
328 sub _hook_path {
329 my $self = shift;
330 my ($name) = @_;
331 $self->{path}.'/hooks/'.$name;
334 sub _hook_install {
335 my $self = shift;
336 my ($name) = @_;
337 my $hooksdir = $self->{path}.'/hooks';
338 -d $hooksdir or mkdir $hooksdir or
339 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
340 open SRC, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
341 open DST, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
342 while (<SRC>) { print DST $_; }
343 close DST;
344 close SRC;
345 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
348 sub _hooks_install {
349 my $self = shift;
350 foreach my $hook ('pre-receive', 'post-receive', 'update', 'post-update') {
351 $self->_hook_install($hook);
355 # private constructor, do not use
356 sub _new {
357 my $class = shift;
358 my ($name, $base_path, $path) = @_;
359 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
360 $path ||= "$base_path/$name.git";
361 my $proj = { name => $name, base_path => $base_path, path => $path };
363 bless $proj, $class;
366 # public constructor #0
367 # creates a virtual project not connected to disk image
368 # you can conjure() it later to disk
369 sub ghost {
370 my $class = shift;
371 my ($name, $mirror) = @_;
372 my $self = $class->_new($name, $Girocco::Config::reporoot);
373 $self->{users} = [];
374 $self->{mirror} = $mirror;
375 $self->{email} = $self->{orig_email} = '';
376 $self;
379 # public constructor #1
380 sub load {
381 my $class = shift;
382 my $name = shift || '';
384 open F, '<', jailed_file("/etc/group") or die "project load failed: $!";
385 while (<F>) {
386 chomp;
387 @_ = split /:+/;
388 next unless (shift eq $name);
390 my $self = $class->_new($name, $Girocco::Config::reporoot);
391 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
393 my $ulist;
394 ($self->{crypt}, $self->{gid}, $ulist) = @_;
395 $ulist ||= '';
396 $self->{users} = [split /,/, $ulist];
397 $self->{HEAD} = $self->get_HEAD;
398 $self->{orig_HEAD} = $self->{HEAD};
399 $self->{orig_users} = [@{$self->{users}}];
400 $self->{mirror} = ! -e $self->_nofetch_path;
401 $self->{clone_in_progress} = -e $self->_clonep_path;
402 $self->{clone_logged} = -e $self->_clonelog_path;
403 $self->{clone_failed} = -e $self->_clonefail_path;
404 $self->{ccrypt} = $self->{crypt};
406 $self->_properties_load;
407 $self->{orig_email} = $self->{email};
408 $self->{loaded} = 1; # indicates self was loaded from etc/group file
409 return $self;
411 close F;
412 undef;
415 # $proj may not be in sane state if this returns false!
416 sub cgi_fill {
417 my $self = shift;
418 my ($gcgi) = @_;
419 my $cgi = $gcgi->cgi;
421 my ($pwd, $pwd2) = ($cgi->param('pwd'), $cgi->param('pwd2'));
422 # in case passwords are disabled
423 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
424 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
425 $gcgi->err("Empty passwords are not permitted.");
427 if ($pwd ne '' or not $self->{crypt}) {
428 $self->{crypt} = scrypt_sha1($pwd);
430 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
431 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
434 $self->{cpwd} = $cgi->param('cpwd');
436 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
437 my $newtype = $forkee ? 'fork' : 'project';
438 length($project) <= 64
439 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
441 if ($Girocco::Config::project_owners eq 'email') {
442 $self->{email} = $gcgi->wparam('email');
443 valid_email($self->{email})
444 or $gcgi->err("Your email sure looks weird...?");
445 length($self->{email}) <= 96
446 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
449 $self->{url} = $gcgi->wparam('url');
450 if ($self->{url}) {
451 valid_repo_url($self->{url})
452 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
453 if ($Girocco::Config::restrict_mirror_hosts) {
454 my $mh = extract_url_hostname($self->{url});
455 is_dns_hostname($mh)
456 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
457 !is_our_hostname($mh)
458 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
462 $self->{desc} = $gcgi->wparam('desc');
463 length($self->{desc}) <= 1024
464 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
466 $self->{README} = $gcgi->wparam('README');
467 length($self->{README}) <= 8192
468 or $gcgi->err("README length &gt; 8kb!");
470 $self->{hp} = $gcgi->wparam('hp');
471 if ($self->{hp}) {
472 valid_web_url($self->{hp})
473 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
476 my %users = ();
477 my @users = ();
478 foreach my $user ($cgi->param('user')) {
479 if (!exists($users{$user})) {
480 $users{$user} = 1;
481 push(@users, $user) if Girocco::User::valid_name($user) && Girocco::User::does_exist($user)
484 $self->{users} = \@users;
486 $self->{HEAD} = $cgi->param('HEAD') if $cgi->param('HEAD');
488 # schedule deletion of tags (will be committed by update() after auth)
489 $self->{tags_to_delete} = [$cgi->param('tags')];
491 $self->{notifymail} = $gcgi->wparam('notifymail');
492 if ($self->{notifymail}) {
493 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
494 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
497 $self->{notifyjson} = $gcgi->wparam('notifyjson');
498 if ($self->{notifyjson}) {
499 valid_web_url($self->{notifyjson})
500 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
503 $self->{notifycia} = $gcgi->wparam('notifycia');
504 if ($self->{notifycia}) {
505 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
506 or $gcgi->err("Overly suspicious CIA notify project name. If it is actually valid, contact me.");
509 if ($cgi->param('setstatusupdates')) {
510 my $val = $gcgi->wparam('statusupdates') || '0';
511 $self->{statusupdates} = $val ? 1 : 0;
514 not $gcgi->err_check;
517 sub form_defaults {
518 my $self = shift;
520 name => $self->{name},
521 email => $self->{email},
522 url => $self->{url},
523 desc => html_esc($self->{desc}),
524 README => html_esc($self->{README}),
525 hp => $self->{hp},
526 users => $self->{users},
527 notifymail => html_esc($self->{notifymail}),
528 notifyjson => html_esc($self->{notifyjson}),
529 notifycia => html_esc($self->{notifycia}),
533 # return true if $enc_passwd is a match for $plain_passwd
534 my $_check_passwd_match = sub {
535 my $enc_passwd = shift;
536 my $plain_passwd = shift;
537 defined($enc_passwd) or $enc_passwd = '';
538 defined($plain_passwd) or $plain_passwd = '';
539 # $enc_passwd may be crypt or crypt_sha1
540 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
541 # It's using sha1-crypt
542 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
543 } else {
544 # It's using crypt
545 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
549 sub authenticate {
550 my $self = shift;
551 my ($gcgi) = @_;
553 $self->{ccrypt} or die "Can't authenticate against a project with no password";
554 defined($self->{cpwd}) or $self->{cpwd} = '';
555 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
556 $gcgi->err("Your admin password does not match!");
557 return 0;
559 return 1;
562 # return true if the password from the file is empty or consists of all the same
563 # character. However, if the project was NOT loaded from the group file
564 # (!self->{loaded}) then the password is never locked.
565 # This function does NOT check $Girocco::Config::project_passwords, the caller
566 # is responsible for doing so if desired. Same for $self->{email}.
567 sub is_password_locked {
568 my $self = shift;
570 $self->{loaded} or return 0;
571 my $testcrypt = $self->{ccrypt}; # The value from the group file
572 defined($testcrypt) or $testcrypt = '';
573 $testcrypt ne '' or return 1; # No password at all
574 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
575 return 0; # Not locked
578 sub _setup {
579 use POSIX qw(strftime);
580 my $self = shift;
581 my ($pushers) = @_;
583 $self->_mkdir_forkees;
585 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
586 if ($Girocco::Config::owning_group) {
587 my $gid = scalar(getgrnam($Girocco::Config::owning_group));
588 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
589 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
590 } else {
591 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
593 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
594 or die "git init $self->{path} failed: $?";
595 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
596 or die "disabling receive.denyNonFastforwards failed: $?";
597 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
598 or die "disabling gc.auto failed: $?";
599 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
600 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
601 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
602 or die "setting girocco.creationtime failed: $?";
603 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writebitmaps', 'true') == 0
604 or die "enabling repack.writebitmaps failed: $?";
606 # /info must have right permissions,
607 # and git init didn't do it for some reason.
608 # config must have correct permissions.
609 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
610 if ($Girocco::Config::owning_group) {
611 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
612 chmod(0664, $self->{path}."/config") or die "chmod 0664 $self->{path}/config failed: $!";
613 } else {
614 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
615 chmod(0666, $self->{path}."/config") or die "chmod 0666 $self->{path}/config failed: $!";
618 $self->_properties_save;
619 $self->_alternates_setup;
620 $self->_ctags_setup;
621 $self->_group_remove;
622 $self->_group_add($pushers);
623 $self->_hooks_install;
624 #$self->perm_initialize;
625 $self->_update_index;
628 sub premirror {
629 my $self = shift;
631 $self->_setup(':');
632 $self->_clonep(1);
633 $self->perm_initialize;
636 sub conjure {
637 my $self = shift;
639 $self->_setup;
640 $self->_nofetch(1);
641 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
642 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
643 or die "create-personal-mob-area $self->{name} failed";
645 $self->perm_initialize;
648 sub clone {
649 my $self = shift;
651 unlink ($self->_clonefail_path()); # Ignore EEXIST error
652 unlink ($self->_clonelog_path()); # Ignore EEXIST error
654 use IO::Socket;
655 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
656 $sock->print("clone ".$self->{name}."\n");
657 # Just ignore reply, we are going to succeed anyway and the I/O
658 # would apparently get quite hairy.
659 $sock->flush();
660 sleep 2; # *cough*
661 $sock->close();
664 sub update {
665 my $self = shift;
667 $self->_properties_save;
668 $self->_group_update;
670 if (exists($self->{tags_to_delete})) {
671 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
674 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
676 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
677 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
678 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
679 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
681 $self->_update_index if $self->{email} ne $self->{orig_email};
682 $self->{orig_email} = $self->{email};
687 sub update_password {
688 my $self = shift;
689 my ($pwd) = @_;
691 $self->{crypt} = scrypt_sha1($pwd);
692 $self->_group_update;
695 # You can explicitly do this just on a ghost() repository too.
696 sub delete {
697 my $self = shift;
699 if (-d $self->{path}) {
700 system('rm', '-rf', $self->{path}) == 0
701 or die "rm -rf $self->{path} failed: $?";
703 # attempt to clean up any empty fork directories by removing them
704 my @pelems = split('/', $self->{name});
705 while (@pelems > 1) {
706 pop @pelems;
707 # okay to fail
708 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
710 $self->_group_remove;
711 $self->_update_index;
714 sub _contains_files {
715 my $dir = shift;
716 (-d $dir) or return 0;
717 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
718 while (my $entry = readdir($dh)) {
719 next if $entry eq '' || $entry eq '.' || $entry eq '..';
720 closedir($dh), return 1
721 if -f "$dir/$entry" ||
722 -d "$dir/$entry" && _contains_files("$dir/$entry");
724 closedir($dh);
725 return 0;
728 sub has_forks {
729 my $self = shift;
731 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
734 sub is_empty {
735 # A project is considered empty if the git repository does not
736 # have any refs. This means packed-refs does not exist or is
737 # empty or only has lines starting with '#' AND there are no
738 # files in the refs subdirectory hierarchy (no matter how deep).
740 my $self = shift;
742 (-d $self->{path}) or return 0;
743 if (-e $self->{path}.'/packed-refs') {
744 open(my $pr, '<', $self->{path}.'/packed-refs')
745 or die "open $self->{path}./packed-refs failed: $!";
746 my $foundref = 0;
747 while (my $ref = <$pr>) {
748 next if $ref =~ /^#/;
749 $foundref = 1;
750 last;
752 close($pr);
753 return 0 if $foundref;
755 (-d $self->{path}.'/refs') or return 1;
756 return !_contains_files($self->{path}.'/refs');
759 sub delete_ctag {
760 my $self = shift;
761 my ($ctag) = @_;
763 # sanity check, disallow filenames starting with . .. or /
764 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
767 sub get_ctag_names {
768 my $self = shift;
769 my @ctags = ();
770 opendir(my $dh, $self->{path}.'/ctags')
771 or return @ctags;
772 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
773 closedir($dh);
774 return @ctags;
777 sub get_heads {
778 my $self = shift;
779 my $fh;
780 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
781 defined($heads) or $heads = '';
782 chomp $heads;
783 my @res = ();
784 foreach (split(/\n/, $heads)) {
785 chomp;
786 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
787 push @res, $1;
789 @res;
792 sub get_HEAD {
793 my $self = shift;
794 my $HEAD = get_git("--git-dir=$self->{path}", 'symbolic-ref', 'HEAD');
795 defined($HEAD) or $HEAD = '';
796 chomp $HEAD;
797 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
798 return $1;
801 sub set_HEAD {
802 my $self = shift;
803 my $newHEAD = shift;
804 # Cursory checks only -- if you want to break your HEAD, be my guest
805 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
806 die "grossly invalid new HEAD: $newHEAD";
808 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
809 die "could not set HEAD" if ($? >> 8);
810 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
811 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
814 sub gen_auth {
815 my $self = shift;
816 my ($type) = @_;
817 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
819 $self->{authtype} = $type;
821 no warnings;
822 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
824 my $expire = time + 24 * 3600;
825 my $propval = "# ${type}AUTH $self->{auth} $expire";
826 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
827 $self->{auth};
830 sub del_auth {
831 my $self = shift;
833 delete $self->{auth};
834 delete $self->{authtype};
835 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
838 sub remove_user {
839 my $self = shift;
840 my ($username) = @_;
842 my $before_count = @{$self->{users}};
843 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
844 return @{$self->{users}} != $before_count;
847 ### static methods
849 sub get_forkee_name {
850 local $_ = $_[0];
851 (m#^(.*)/.*?$#)[0]; #
854 sub get_forkee_path {
855 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
856 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
857 -d $forkee ? $forkee : '';
860 # Ultimately the full project/fork name could end up being part of a Git ref name
861 # when a project's forks are combined into one giant repository for efficiency.
862 # That means that the project/fork name must satisfy the Git ref name requirements:
864 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
865 # 2. The character with an ASCII value of 0x7F is not allowed
866 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
867 # 4. The character '/' is a separator and is not allowed within a name
868 # 5. The name may not start with '.' or end with '.'
869 # 6. The name may not end with '.lock'
870 # 7. The name may not contain the '..' sequence
871 # 8. The name may not contain the '@{' sequence
872 # 9. If multiple components are used (separated by '/'), no empty '' components
874 # We also prohibit a trailing '.git' on any path component and futher restrict
875 # the allowed characters to alphanumeric and [+._-] where names must start with
876 # an alphanumeric.
878 sub _valid_name_characters {
879 local $_ = $_[0];
880 (not m#^[/+._-]#)
881 and (not m#//#)
882 and (not m#\.\.#)
883 and (not m#/[+._-]#)
884 and (not m#\./#)
885 and (not m#\.$#)
886 and (not m#\.git/#i)
887 and (not m#\.git$#i)
888 and (not m#\.lock/#i)
889 and (not m#\.lock$#i)
890 and (not m#/$#)
891 and m#^[a-zA-Z0-9/+._-]+$#;
894 sub valid_name {
895 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
896 local $_ = $_[0];
897 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
898 and @{[m#/#g]} <= 5 # maximum fork depth is 5
899 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
902 # It's possible that some forks have been kept but the forkee is gone.
903 # In this case the standard valid_name check is too strict.
904 sub does_exist {
905 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
906 my ($name, $nodie) = @_;
907 my $okay = (
908 _valid_name_characters($name)
909 and ((not $name =~ m#/#)
910 or -d get_forkee_path($name)
911 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
912 (!$okay && $nodie) and return undef;
913 !$okay and die "tried to query for project with invalid name $name!";
914 (-d $Girocco::Config::reporoot."/$name.git");
917 sub get_full_list {
918 my $class = shift;
919 my @projects;
921 open F, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
922 while (<F>) {
923 chomp;
924 @_ = split /:+/;
925 next if ($_[2] < 65536);
927 push @projects, $_[0];
929 close F;
930 @projects;