Project.pm: enable repack.writebitmaps when creating repositories
[girocco.git] / Girocco / Project.pm
blob37a84220d37e673b6d1c0a62fe8202b559134c14
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 system($Girocco::Config::basedir . '/gitweb/genindex.sh');
96 sub _property_path {
97 my $self = shift;
98 my ($name) = @_;
99 $self->{path}.'/'.$name;
102 sub _property_fget {
103 my $self = shift;
104 my ($name) = @_;
105 my $pname = $propmap{$name};
106 $pname = $propmapro{$name} unless $pname;
107 $pname or die "unknown property: $name";
108 if ($pname =~ s/^://) {
109 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "gitweb.$pname"`;
110 chomp $val;
111 return $val;
112 } elsif ($pname =~ s/^%//) {
113 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "$pname"`;
114 chomp $val;
115 return $val;
118 open P, '<', $self->_property_path($pname) or return undef;
119 my @value = <P>;
120 close P;
121 my $value = join('', @value); chomp $value;
122 $value;
125 sub _property_fput {
126 my $self = shift;
127 my ($name, $value) = @_;
128 my $pname = $propmap{$name};
129 $pname or die "unknown property: $name";
130 $value ||= '';
131 if ($pname =~ s/^://) {
132 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
133 return;
134 } elsif ($pname =~ s/^%//) {
135 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
136 return;
139 my $P = lock_file($self->_property_path($pname));
140 $value ne '' and print $P "$value\n";
141 close $P;
142 unlock_file($self->_property_path($pname));
145 sub _properties_load {
146 my $self = shift;
147 foreach my $prop (keys %propmap) {
148 $self->{$prop} = $self->_property_fget($prop);
150 foreach my $prop (keys %propmapro) {
151 $self->{$prop} = $self->_property_fget($prop);
153 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config --bool "gitweb.statusupdates" 2>/dev/null`;
154 chomp $val;
155 $val = ($val eq 'false') ? 0 : 1;
156 $self->{statusupdates} = $val;
157 delete $self->{auth};
158 $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "gitweb.repoauth"`;
159 chomp $val;
160 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
161 my $expire = $3;
162 if (time < $expire) {
163 $self->{authtype} = $1;
164 $self->{auth} = $2;
169 sub _properties_save {
170 my $self = shift;
171 foreach my $prop (keys %propmap) {
172 $self->_property_fput($prop, $self->{$prop});
174 $self->{statusupdates} = 1
175 unless defined($self->{statusupdates}) && $self->{statusupdates} =~ /^\d+$/;
176 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool',
177 "gitweb.statusupdates", $self->{statusupdates});
178 if (defined($self->{origurl}) && defined($self->{url}) &&
179 $self->{origurl} ne $self->{url} && -e $self->_property_path(".banged")) {
180 if (open(X, '>', $self->_property_path(".bangagain"))) {
181 close X;
182 chmod(0664, $self->_property_path(".bangagain"));
187 sub _nofetch_path {
188 my $self = shift;
189 $self->_property_path('.nofetch');
192 sub _nofetch {
193 my $self = shift;
194 my ($nofetch) = @_;
195 my $nf = $self->_nofetch_path;
196 if ($nofetch) {
197 open X, '>', $nf or die "nofetch failed: $!";
198 close X;
199 } else {
200 unlink $nf or die "yesfetch failed: $!";
204 sub _clonelog_path {
205 my $self = shift;
206 $self->_property_path('.clonelog');
209 sub _clonefail_path {
210 my $self = shift;
211 $self->_property_path('.clone_failed');
214 sub _clonep_path {
215 my $self = shift;
216 $self->_property_path('.clone_in_progress');
219 sub _clonep {
220 my $self = shift;
221 my ($nofetch) = @_;
222 my $np = $self->_clonep_path;
223 if ($nofetch) {
224 open X, '>', $np or die "clonep failed: $!";
225 close X;
226 } else {
227 unlink $np or die "clonef failed: $!";
230 sub _alternates_setup {
231 my $self = shift;
232 return unless $self->{name} =~ m#/#;
233 my $forkee_name = get_forkee_name($self->{name});
234 my $forkee_path = get_forkee_path($self->{name});
235 return unless -d $forkee_path;
236 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
237 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
238 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
240 # We set up both alternates and http_alternates since we cannot use
241 # relative path in alternates - that doesn't work recursively.
243 my $filename = $self->{path}.'/objects/info/alternates';
244 open X, '>', $filename or die "alternates failed: $!";
245 print X "$forkee_path/objects\n";
246 close X;
247 chmod 0664, $filename or warn "cannot chmod $filename: $!";
249 if ($Girocco::Config::httppullurl) {
250 $filename = $self->{path}.'/objects/info/http-alternates';
251 open X, '>', $filename or die "http-alternates failed: $!";
252 my $upfork = $forkee_name;
253 do { print X "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
254 close X;
255 chmod 0664, $filename or warn "cannot chmod $filename: $!";
258 # The symlink is problematic since git remote prune will traverse it.
259 #symlink "$forkee_path/refs", $self->{path}.'/refs/forkee';
261 # copy refs from parent project
262 # ownership information is changed by a root cronjob
263 system("cp -pR $forkee_path/refs $self->{path}/");
264 # initialize HEAD, hacky version
265 system("cp $forkee_path/HEAD $self->{path}/HEAD");
268 sub _ctags_setup {
269 my $self = shift;
270 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
271 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
274 sub _group_add {
275 my $self = shift;
276 my ($xtra) = @_;
277 $xtra .= join(',', @{$self->{users}});
278 filedb_atomic_append(jailed_file('/etc/group'),
279 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
282 sub _group_update {
283 my $self = shift;
284 my $xtra = join(',', @{$self->{users}});
285 filedb_atomic_edit(jailed_file('/etc/group'),
286 sub {
287 $_ = $_[0];
288 chomp;
289 if ($self->{name} eq (split /:/)[0]) {
290 # preserve readonly flag
291 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
292 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
293 } else {
294 return "$_\n";
300 sub _group_remove {
301 my $self = shift;
302 filedb_atomic_edit(jailed_file('/etc/group'),
303 sub {
304 $self->{name} ne (split /:/)[0] and return $_;
309 sub _hook_path {
310 my $self = shift;
311 my ($name) = @_;
312 $self->{path}.'/hooks/'.$name;
315 sub _hook_install {
316 my $self = shift;
317 my ($name) = @_;
318 open SRC, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
319 open DST, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
320 while (<SRC>) { print DST $_; }
321 close DST;
322 close SRC;
323 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
326 sub _hooks_install {
327 my $self = shift;
328 foreach my $hook ('pre-receive', 'post-receive', 'update', 'post-update') {
329 $self->_hook_install($hook);
333 # private constructor, do not use
334 sub _new {
335 my $class = shift;
336 my ($name, $base_path, $path) = @_;
337 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
338 $path ||= "$base_path/$name.git";
339 my $proj = { name => $name, base_path => $base_path, path => $path };
341 bless $proj, $class;
344 # public constructor #0
345 # creates a virtual project not connected to disk image
346 # you can conjure() it later to disk
347 sub ghost {
348 my $class = shift;
349 my ($name, $mirror) = @_;
350 my $self = $class->_new($name, $Girocco::Config::reporoot);
351 $self->{users} = [];
352 $self->{mirror} = $mirror;
353 $self->{email} = $self->{orig_email} = '';
354 $self;
357 # public constructor #1
358 sub load {
359 my $class = shift;
360 my $name = shift || '';
362 open F, '<', jailed_file("/etc/group") or die "project load failed: $!";
363 while (<F>) {
364 chomp;
365 @_ = split /:+/;
366 next unless (shift eq $name);
368 my $self = $class->_new($name, $Girocco::Config::reporoot);
369 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
371 my $ulist;
372 ($self->{crypt}, $self->{gid}, $ulist) = @_;
373 $ulist ||= '';
374 $self->{users} = [split /,/, $ulist];
375 $self->{HEAD} = $self->get_HEAD;
376 $self->{orig_HEAD} = $self->{HEAD};
377 $self->{orig_users} = [@{$self->{users}}];
378 $self->{mirror} = ! -e $self->_nofetch_path;
379 $self->{clone_in_progress} = -e $self->_clonep_path;
380 $self->{clone_logged} = -e $self->_clonelog_path;
381 $self->{clone_failed} = -e $self->_clonefail_path;
382 $self->{ccrypt} = $self->{crypt};
384 $self->_properties_load;
385 $self->{orig_email} = $self->{email};
386 $self->{loaded} = 1; # indicates self was loaded from etc/group file
387 return $self;
389 close F;
390 undef;
393 # $proj may not be in sane state if this returns false!
394 sub cgi_fill {
395 my $self = shift;
396 my ($gcgi) = @_;
397 my $cgi = $gcgi->cgi;
399 my ($pwd, $pwd2) = ($cgi->param('pwd'), $cgi->param('pwd2'));
400 # in case passwords are disabled
401 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
402 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
403 $gcgi->err("Empty passwords are not permitted.");
405 if ($pwd ne '' or not $self->{crypt}) {
406 $self->{crypt} = scrypt_sha1($pwd);
408 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
409 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
412 $self->{cpwd} = $cgi->param('cpwd');
414 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
415 my $newtype = $forkee ? 'fork' : 'project';
416 length($project) <= 64
417 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
419 if ($Girocco::Config::project_owners eq 'email') {
420 $self->{email} = $gcgi->wparam('email');
421 valid_email($self->{email})
422 or $gcgi->err("Your email sure looks weird...?");
423 length($self->{email}) <= 96
424 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
427 $self->{url} = $gcgi->wparam('url');
428 if ($self->{url}) {
429 valid_repo_url($self->{url})
430 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
431 if ($Girocco::Config::restrict_mirror_hosts) {
432 my $mh = extract_url_hostname($self->{url});
433 is_dns_hostname($mh)
434 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
435 !is_our_hostname($mh)
436 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
440 $self->{desc} = $gcgi->wparam('desc');
441 length($self->{desc}) <= 1024
442 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
444 $self->{README} = $gcgi->wparam('README');
445 length($self->{README}) <= 8192
446 or $gcgi->err("README length &gt; 8kb!");
448 $self->{hp} = $gcgi->wparam('hp');
449 if ($self->{hp}) {
450 valid_web_url($self->{hp})
451 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
454 $self->{users} = [grep { Girocco::User::valid_name($_) && Girocco::User::does_exist($_) } $cgi->param('user')];
456 $self->{HEAD} = $cgi->param('HEAD') if $cgi->param('HEAD');
458 # schedule deletion of tags (will be committed by update() after auth)
459 $self->{tags_to_delete} = [$cgi->param('tags')];
461 $self->{notifymail} = $gcgi->wparam('notifymail');
462 if ($self->{notifymail}) {
463 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
464 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
467 $self->{notifyjson} = $gcgi->wparam('notifyjson');
468 if ($self->{notifyjson}) {
469 valid_web_url($self->{notifyjson})
470 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
473 $self->{notifycia} = $gcgi->wparam('notifycia');
474 if ($self->{notifycia}) {
475 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
476 or $gcgi->err("Overly suspicious CIA notify project name. If it is actually valid, contact me.");
479 if ($cgi->param('setstatusupdates')) {
480 my $val = $gcgi->wparam('statusupdates') || '0';
481 $self->{statusupdates} = $val ? 1 : 0;
484 not $gcgi->err_check;
487 sub form_defaults {
488 my $self = shift;
490 name => $self->{name},
491 email => $self->{email},
492 url => $self->{url},
493 desc => html_esc($self->{desc}),
494 README => html_esc($self->{README}),
495 hp => $self->{hp},
496 users => $self->{users},
497 notifymail => html_esc($self->{notifymail}),
498 notifyjson => html_esc($self->{notifyjson}),
499 notifycia => html_esc($self->{notifycia}),
503 # return true if $enc_passwd is a match for $plain_passwd
504 my $_check_passwd_match = sub {
505 my $enc_passwd = shift;
506 my $plain_passwd = shift;
507 defined($enc_passwd) or $enc_passwd = '';
508 defined($plain_passwd) or $plain_passwd = '';
509 # $enc_passwd may be crypt or crypt_sha1
510 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
511 # It's using sha1-crypt
512 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
513 } else {
514 # It's using crypt
515 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
519 sub authenticate {
520 my $self = shift;
521 my ($gcgi) = @_;
523 $self->{ccrypt} or die "Can't authenticate against a project with no password";
524 defined($self->{cpwd}) or $self->{cpwd} = '';
525 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
526 $gcgi->err("Your admin password does not match!");
527 return 0;
529 return 1;
532 # return true if the password from the file is empty or consists of all the same
533 # character. However, if the project was NOT loaded from the group file
534 # (!self->{loaded}) then the password is never locked.
535 # This function does NOT check $Girocco::Config::project_passwords, the caller
536 # is responsible for doing so if desired. Same for $self->{email}.
537 sub is_password_locked {
538 my $self = shift;
540 $self->{loaded} or return 0;
541 my $testcrypt = $self->{ccrypt}; # The value from the group file
542 defined($testcrypt) or $testcrypt = '';
543 $testcrypt ne '' or return 1; # No password at all
544 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
545 return 0; # Not locked
548 sub _setup {
549 use POSIX qw(strftime);
550 my $self = shift;
551 my ($pushers) = @_;
553 $self->_mkdir_forkees;
555 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
556 if ($Girocco::Config::owning_group) {
557 my $gid = scalar(getgrnam($Girocco::Config::owning_group));
558 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
559 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
560 } else {
561 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
563 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--bare', '--shared='.$self->shared_mode()) == 0
564 or die "git init $self->{path} failed: $?";
565 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
566 or die "disabling receive.denyNonFastforwards failed: $?";
567 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
568 or die "disabling gc.auto failed: $?";
569 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
570 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
571 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
572 or die "setting girocco.creationtime failed: $?";
573 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writebitmaps', 'true') == 0
574 or die "enabling repack.writebitmaps failed: $?";
576 # /info must have right permissions,
577 # and git init didn't do it for some reason.
578 if ($Girocco::Config::owning_group) {
579 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
580 } else {
581 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
584 $self->_properties_save;
585 $self->_alternates_setup;
586 $self->_ctags_setup;
587 $self->_group_remove;
588 $self->_group_add($pushers);
589 $self->_hooks_install;
590 #$self->perm_initialize;
591 $self->_update_index;
594 sub premirror {
595 my $self = shift;
597 $self->_setup(':');
598 $self->_clonep(1);
599 $self->perm_initialize;
602 sub conjure {
603 my $self = shift;
605 $self->_setup;
606 $self->_nofetch(1);
607 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
608 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
609 or die "create-personal-mob-area $self->{name} failed";
611 $self->perm_initialize;
614 sub clone {
615 my $self = shift;
617 unlink ($self->_clonefail_path()); # Ignore EEXIST error
618 unlink ($self->_clonelog_path()); # Ignore EEXIST error
620 use IO::Socket;
621 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
622 $sock->print("clone ".$self->{name}."\n");
623 # Just ignore reply, we are going to succeed anyway and the I/O
624 # would apparently get quite hairy.
625 $sock->flush();
626 sleep 2; # *cough*
627 $sock->close();
630 sub update {
631 my $self = shift;
633 $self->_properties_save;
634 $self->_group_update;
636 if (exists($self->{tags_to_delete})) {
637 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
640 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
642 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
643 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
644 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
645 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
647 $self->_update_index if $self->{email} ne $self->{orig_email};
648 $self->{orig_email} = $self->{email};
653 sub update_password {
654 my $self = shift;
655 my ($pwd) = @_;
657 $self->{crypt} = scrypt_sha1($pwd);
658 $self->_group_update;
661 # You can explicitly do this just on a ghost() repository too.
662 sub delete {
663 my $self = shift;
665 if (-d $self->{path}) {
666 system('rm', '-rf', $self->{path}) == 0
667 or die "rm -rf $self->{path} failed: $?";
669 # attempt to clean up any empty fork directories by removing them
670 my @pelems = split('/', $self->{name});
671 while (@pelems > 1) {
672 pop @pelems;
673 # okay to fail
674 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
676 $self->_group_remove;
677 $self->_update_index;
680 sub _contains_files {
681 my $dir = shift;
682 (-d $dir) or return 0;
683 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
684 while (my $entry = readdir($dh)) {
685 next if $entry eq '' || $entry eq '.' || $entry eq '..';
686 closedir($dh), return 1
687 if -f "$dir/$entry" ||
688 -d "$dir/$entry" && _contains_files("$dir/$entry");
690 closedir($dh);
691 return 0;
694 sub has_forks {
695 my $self = shift;
697 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
700 sub is_empty {
701 # A project is considered empty if the git repository does not
702 # have any refs. This means packed-refs does not exist or is
703 # empty or only has lines starting with '#' AND there are no
704 # files in the refs subdirectory hierarchy (no matter how deep).
706 my $self = shift;
708 (-d $self->{path}) or return 0;
709 if (-e $self->{path}.'/packed-refs') {
710 open(my $pr, '<', $self->{path}.'/packed-refs')
711 or die "open $self->{path}./packed-refs failed: $!";
712 my $foundref = 0;
713 while (my $ref = <$pr>) {
714 next if $ref =~ /^#/;
715 $foundref = 1;
716 last;
718 close($pr);
719 return 0 if $foundref;
721 (-d $self->{path}.'/refs') or return 1;
722 return !_contains_files($self->{path}.'/refs');
725 sub delete_ctag {
726 my $self = shift;
727 my ($ctag) = @_;
729 # sanity check, disallow filenames starting with . .. or /
730 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
733 sub get_ctag_names {
734 my $self = shift;
735 my @ctags = ();
736 opendir(my $dh, $self->{path}.'/ctags')
737 or return @ctags;
738 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
739 closedir($dh);
740 return @ctags;
743 sub get_heads {
744 my $self = shift;
745 my $fh;
746 open($fh, '-|', "$Girocco::Config::git_bin --git-dir=$self->{path} show-ref --heads") or die "could not get list of heads";
747 my @res;
748 while (<$fh>) {
749 chomp;
750 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
751 push @res, $1;
753 close $fh;
754 @res;
757 sub get_HEAD {
758 my $self = shift;
759 my $HEAD = `$Girocco::Config::git_bin --git-dir=$self->{path} symbolic-ref HEAD`;
760 chomp $HEAD;
761 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
762 return $1;
765 sub set_HEAD {
766 my $self = shift;
767 my $newHEAD = shift;
768 # Cursory checks only -- if you want to break your HEAD, be my guest
769 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
770 die "grossly invalid new HEAD: $newHEAD";
772 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
773 die "could not set HEAD" if ($? >> 8);
774 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
775 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
778 sub gen_auth {
779 my $self = shift;
780 my ($type) = @_;
781 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
783 $self->{authtype} = $type;
785 no warnings;
786 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
788 my $expire = time + 24 * 3600;
789 my $propval = "# ${type}AUTH $self->{auth} $expire";
790 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
791 $self->{auth};
794 sub del_auth {
795 my $self = shift;
797 delete $self->{auth};
798 delete $self->{authtype};
799 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
802 sub remove_user {
803 my $self = shift;
804 my ($username) = @_;
806 my $before_count = @{$self->{users}};
807 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
808 return @{$self->{users}} != $before_count;
811 ### static methods
813 sub get_forkee_name {
814 local $_ = $_[0];
815 (m#^(.*)/.*?$#)[0]; #
818 sub get_forkee_path {
819 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
820 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
821 -d $forkee ? $forkee : '';
824 # Ultimately the full project/fork name could end up being part of a Git ref name
825 # when a project's forks are combined into one giant repository for efficiency.
826 # That means that the project/fork name must satisfy the Git ref name requirements:
828 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
829 # 2. The character with an ASCII value of 0x7F is not allowed
830 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
831 # 4. The character '/' is a separator and is not allowed within a name
832 # 5. The name may not start with '.' or end with '.'
833 # 6. The name may not end with '.lock'
834 # 7. The name may not contain the '..' sequence
835 # 8. The name may not contain the '@{' sequence
836 # 9. If multiple components are used (separated by '/'), no empty '' components
838 # We also prohibit a trailing '.git' on any path component and futher restrict
839 # the allowed characters to alphanumeric and [+._-] where names must start with
840 # an alphanumeric.
842 # The rules are relaxed slightly for existing projects (for now) to accomodate them.
844 sub _valid_name_characters {
845 local $_ = $_[0];
846 my $relaxed = $_[1];
847 (not m#^[/+._-]#)
848 and (not m#//#)
849 and (not m#\.\.#)
850 and (not m#/[+._-]# or $relaxed)
851 and (not m#\./#)
852 and (not m#\.$# or $relaxed)
853 and (not m#\.git/#i)
854 and (not m#\.git$#i)
855 and (not m#\.lock/#i)
856 and (not m#\.lock$#i)
857 and (not m#/$#)
858 and m#^[a-zA-Z0-9/+._-]+$#;
861 sub valid_name {
862 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
863 local $_ = $_[0];
864 _valid_name_characters($_) and not exists($reservedprojectnames{$_})
865 and @{[m#/#g]} <= 5 # maximum fork depth is 5
866 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
869 # It's possible that some forks have been kept but the forkee is gone.
870 # In this case the standard valid_name check is too strict.
871 sub does_exist {
872 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
873 my ($name, $nodie) = @_;
874 my $okay = (
875 _valid_name_characters($name, 1)
876 and ((not $name =~ m#/#)
877 or -d get_forkee_path($name)
878 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
879 (!$okay && $nodie) and return undef;
880 !$okay and die "tried to query for project with invalid name $name!";
881 (-d $Girocco::Config::reporoot."/$name.git");
884 sub get_full_list {
885 my $class = shift;
886 my @projects;
888 open F, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
889 while (<F>) {
890 chomp;
891 @_ = split /:+/;
892 next if ($_[2] < 65536);
894 push @projects, $_[0];
896 close F;
897 @projects;