Record user and project creation and recycle times.
[girocco.git] / Girocco / Project.pm
blobdaad4ddc59f27c3cc3d0305f344f11472f3c5b4d
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',
80 # Projects with any of these names will be disallowed to avoid possible
81 # collisions with cgi script paths or chroot paths
82 our %reservedprojectnames = (
83 c => 1, # /c/ -> cgit
84 h => 1, # /h/ -> html.cgi
85 r => 1, # /r/ -> git http
86 w => 1, # /w/ -> gitweb
87 srv => 1, # /srv/git/ -> chroot ssh git repositories
90 sub _update_index {
91 system($Girocco::Config::basedir . '/gitweb/genindex.sh');
94 sub _property_path {
95 my $self = shift;
96 my ($name) = @_;
97 $self->{path}.'/'.$name;
100 sub _property_fget {
101 my $self = shift;
102 my ($name) = @_;
103 my $pname = $propmap{$name};
104 $pname = $propmapro{$name} unless $pname;
105 $pname or die "unknown property: $name";
106 if ($pname =~ s/^://) {
107 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "gitweb.$pname"`;
108 chomp $val;
109 return $val;
110 } elsif ($pname =~ s/^%//) {
111 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "$pname"`;
112 chomp $val;
113 return $val;
116 open P, '<', $self->_property_path($pname) or return undef;
117 my @value = <P>;
118 close P;
119 my $value = join('', @value); chomp $value;
120 $value;
123 sub _property_fput {
124 my $self = shift;
125 my ($name, $value) = @_;
126 my $pname = $propmap{$name};
127 $pname or die "unknown property: $name";
128 $value ||= '';
129 if ($pname =~ s/^://) {
130 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
131 return;
132 } elsif ($pname =~ s/^%//) {
133 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
134 return;
137 my $P = lock_file($self->_property_path($pname));
138 $value ne '' and print $P "$value\n";
139 close $P;
140 unlock_file($self->_property_path($pname));
143 sub _properties_load {
144 my $self = shift;
145 foreach my $prop (keys %propmap) {
146 $self->{$prop} = $self->_property_fget($prop);
148 foreach my $prop (keys %propmapro) {
149 $self->{$prop} = $self->_property_fget($prop);
151 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config --bool "gitweb.statusupdates" 2>/dev/null`;
152 chomp $val;
153 $val = ($val eq 'false') ? 0 : 1;
154 $self->{statusupdates} = $val;
155 delete $self->{auth};
156 $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "gitweb.repoauth"`;
157 chomp $val;
158 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
159 my $expire = $3;
160 if (time < $expire) {
161 $self->{authtype} = $1;
162 $self->{auth} = $2;
167 sub _properties_save {
168 my $self = shift;
169 foreach my $prop (keys %propmap) {
170 $self->_property_fput($prop, $self->{$prop});
172 $self->{statusupdates} = 1
173 unless defined($self->{statusupdates}) && $self->{statusupdates} =~ /^\d+$/;
174 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool',
175 "gitweb.statusupdates", $self->{statusupdates});
178 sub _nofetch_path {
179 my $self = shift;
180 $self->_property_path('.nofetch');
183 sub _nofetch {
184 my $self = shift;
185 my ($nofetch) = @_;
186 my $nf = $self->_nofetch_path;
187 if ($nofetch) {
188 open X, '>', $nf or die "nofetch failed: $!";
189 close X;
190 } else {
191 unlink $nf or die "yesfetch failed: $!";
195 sub _clonelog_path {
196 my $self = shift;
197 $self->_property_path('.clonelog');
200 sub _clonefail_path {
201 my $self = shift;
202 $self->_property_path('.clone_failed');
205 sub _clonep_path {
206 my $self = shift;
207 $self->_property_path('.clone_in_progress');
210 sub _clonep {
211 my $self = shift;
212 my ($nofetch) = @_;
213 my $np = $self->_clonep_path;
214 if ($nofetch) {
215 open X, '>', $np or die "clonep failed: $!";
216 close X;
217 } else {
218 unlink $np or die "clonef failed: $!";
221 sub _alternates_setup {
222 my $self = shift;
223 return unless $self->{name} =~ m#/#;
224 my $forkee_name = get_forkee_name($self->{name});
225 my $forkee_path = get_forkee_path($self->{name});
226 return unless -d $forkee_path;
227 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
228 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
229 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
231 # We set up both alternates and http_alternates since we cannot use
232 # relative path in alternates - that doesn't work recursively.
234 my $filename = $self->{path}.'/objects/info/alternates';
235 open X, '>', $filename or die "alternates failed: $!";
236 print X "$forkee_path/objects\n";
237 close X;
238 chmod 0664, $filename or warn "cannot chmod $filename: $!";
240 if ($Girocco::Config::httppullurl) {
241 $filename = $self->{path}.'/objects/info/http-alternates';
242 open X, '>', $filename or die "http-alternates failed: $!";
243 my $upfork = $forkee_name;
244 do { print X "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
245 close X;
246 chmod 0664, $filename or warn "cannot chmod $filename: $!";
249 # The symlink is problematic since git remote prune will traverse it.
250 #symlink "$forkee_path/refs", $self->{path}.'/refs/forkee';
252 # copy refs from parent project
253 # ownership information is changed by a root cronjob
254 system("cp -pR $forkee_path/refs $self->{path}/");
255 # initialize HEAD, hacky version
256 system("cp $forkee_path/HEAD $self->{path}/HEAD");
259 sub _ctags_setup {
260 my $self = shift;
261 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
262 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
265 sub _group_add {
266 my $self = shift;
267 my ($xtra) = @_;
268 $xtra .= join(',', @{$self->{users}});
269 filedb_atomic_append(jailed_file('/etc/group'),
270 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
273 sub _group_update {
274 my $self = shift;
275 my $xtra = join(',', @{$self->{users}});
276 filedb_atomic_edit(jailed_file('/etc/group'),
277 sub {
278 $_ = $_[0];
279 chomp;
280 if ($self->{name} eq (split /:/)[0]) {
281 # preserve readonly flag
282 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
283 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
284 } else {
285 return "$_\n";
291 sub _group_remove {
292 my $self = shift;
293 filedb_atomic_edit(jailed_file('/etc/group'),
294 sub {
295 $self->{name} ne (split /:/)[0] and return $_;
300 sub _hook_path {
301 my $self = shift;
302 my ($name) = @_;
303 $self->{path}.'/hooks/'.$name;
306 sub _hook_install {
307 my $self = shift;
308 my ($name) = @_;
309 open SRC, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
310 open DST, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
311 while (<SRC>) { print DST $_; }
312 close DST;
313 close SRC;
314 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
317 sub _hooks_install {
318 my $self = shift;
319 foreach my $hook ('pre-receive', 'post-receive', 'update', 'post-update') {
320 $self->_hook_install($hook);
324 # private constructor, do not use
325 sub _new {
326 my $class = shift;
327 my ($name, $base_path, $path) = @_;
328 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
329 $path ||= "$base_path/$name.git";
330 my $proj = { name => $name, base_path => $base_path, path => $path };
332 bless $proj, $class;
335 # public constructor #0
336 # creates a virtual project not connected to disk image
337 # you can conjure() it later to disk
338 sub ghost {
339 my $class = shift;
340 my ($name, $mirror) = @_;
341 my $self = $class->_new($name, $Girocco::Config::reporoot);
342 $self->{users} = [];
343 $self->{mirror} = $mirror;
344 $self->{email} = $self->{orig_email} = '';
345 $self;
348 # public constructor #1
349 sub load {
350 my $class = shift;
351 my $name = shift || '';
353 open F, '<', jailed_file("/etc/group") or die "project load failed: $!";
354 while (<F>) {
355 chomp;
356 @_ = split /:+/;
357 next unless (shift eq $name);
359 my $self = $class->_new($name, $Girocco::Config::reporoot);
360 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
362 my $ulist;
363 ($self->{crypt}, $self->{gid}, $ulist) = @_;
364 $ulist ||= '';
365 $self->{users} = [split /,/, $ulist];
366 $self->{HEAD} = $self->get_HEAD;
367 $self->{orig_HEAD} = $self->{HEAD};
368 $self->{orig_users} = [@{$self->{users}}];
369 $self->{mirror} = ! -e $self->_nofetch_path;
370 $self->{clone_in_progress} = -e $self->_clonep_path;
371 $self->{clone_logged} = -e $self->_clonelog_path;
372 $self->{clone_failed} = -e $self->_clonefail_path;
373 $self->{ccrypt} = $self->{crypt};
375 $self->_properties_load;
376 $self->{orig_email} = $self->{email};
377 $self->{loaded} = 1; # indicates self was loaded from etc/group file
378 return $self;
380 close F;
381 undef;
384 # $proj may not be in sane state if this returns false!
385 sub cgi_fill {
386 my $self = shift;
387 my ($gcgi) = @_;
388 my $cgi = $gcgi->cgi;
390 my ($pwd, $pwd2) = ($cgi->param('pwd'), $cgi->param('pwd2'));
391 # in case passwords are disabled
392 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
393 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
394 $gcgi->err("Empty passwords are not permitted.");
396 if ($pwd ne '' or not $self->{crypt}) {
397 $self->{crypt} = scrypt_sha1($pwd);
399 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
400 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
403 $self->{cpwd} = $cgi->param('cpwd');
405 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
406 my $newtype = $forkee ? 'fork' : 'project';
407 length($project) <= 64
408 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
410 if ($Girocco::Config::project_owners eq 'email') {
411 $self->{email} = $gcgi->wparam('email');
412 valid_email($self->{email})
413 or $gcgi->err("Your email sure looks weird...?");
414 length($self->{email}) <= 96
415 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
418 $self->{url} = $gcgi->wparam('url');
419 if ($self->{url}) {
420 valid_repo_url($self->{url})
421 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
422 if ($Girocco::Config::restrict_mirror_hosts) {
423 my $mh = extract_url_hostname($self->{url});
424 is_dns_hostname($mh)
425 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
426 !is_our_hostname($mh)
427 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
431 $self->{desc} = $gcgi->wparam('desc');
432 length($self->{desc}) <= 1024
433 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
435 $self->{README} = $gcgi->wparam('README');
436 length($self->{README}) <= 8192
437 or $gcgi->err("README length &gt; 8kb!");
439 $self->{hp} = $gcgi->wparam('hp');
440 if ($self->{hp}) {
441 valid_web_url($self->{hp})
442 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
445 $self->{users} = [grep { Girocco::User::valid_name($_) && Girocco::User::does_exist($_) } $cgi->param('user')];
447 $self->{HEAD} = $cgi->param('HEAD') if $cgi->param('HEAD');
449 # schedule deletion of tags (will be committed by update() after auth)
450 $self->{tags_to_delete} = [$cgi->param('tags')];
452 $self->{notifymail} = $gcgi->wparam('notifymail');
453 if ($self->{notifymail}) {
454 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
455 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
458 $self->{notifyjson} = $gcgi->wparam('notifyjson');
459 if ($self->{notifyjson}) {
460 valid_web_url($self->{notifyjson})
461 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
464 $self->{notifycia} = $gcgi->wparam('notifycia');
465 if ($self->{notifycia}) {
466 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
467 or $gcgi->err("Overly suspicious CIA notify project name. If it is actually valid, contact me.");
470 if ($cgi->param('setstatusupdates')) {
471 my $val = $gcgi->wparam('statusupdates') || '0';
472 $self->{statusupdates} = $val ? 1 : 0;
475 not $gcgi->err_check;
478 sub form_defaults {
479 my $self = shift;
481 name => $self->{name},
482 email => $self->{email},
483 url => $self->{url},
484 desc => html_esc($self->{desc}),
485 README => html_esc($self->{README}),
486 hp => $self->{hp},
487 users => $self->{users},
488 notifymail => html_esc($self->{notifymail}),
489 notifyjson => html_esc($self->{notifyjson}),
490 notifycia => html_esc($self->{notifycia}),
494 # return true if $enc_passwd is a match for $plain_passwd
495 my $_check_passwd_match = sub {
496 my $enc_passwd = shift;
497 my $plain_passwd = shift;
498 defined($enc_passwd) or $enc_passwd = '';
499 defined($plain_passwd) or $plain_passwd = '';
500 # $enc_passwd may be crypt or crypt_sha1
501 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
502 # It's using sha1-crypt
503 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
504 } else {
505 # It's using crypt
506 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
510 sub authenticate {
511 my $self = shift;
512 my ($gcgi) = @_;
514 $self->{ccrypt} or die "Can't authenticate against a project with no password";
515 defined($self->{cpwd}) or $self->{cpwd} = '';
516 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
517 $gcgi->err("Your admin password does not match!");
518 return 0;
520 return 1;
523 # return true if the password from the file is empty or consists of all the same
524 # character. However, if the project was NOT loaded from the group file
525 # (!self->{loaded}) then the password is never locked.
526 # This function does NOT check $Girocco::Config::project_passwords, the caller
527 # is responsible for doing so if desired. Same for $self->{email}.
528 sub is_password_locked {
529 my $self = shift;
531 $self->{loaded} or return 0;
532 my $testcrypt = $self->{ccrypt}; # The value from the group file
533 defined($testcrypt) or $testcrypt = '';
534 $testcrypt ne '' or return 1; # No password at all
535 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
536 return 0; # Not locked
539 sub _setup {
540 use POSIX qw(strftime);
541 my $self = shift;
542 my ($pushers) = @_;
544 $self->_mkdir_forkees;
546 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
547 if ($Girocco::Config::owning_group) {
548 my $gid = scalar(getgrnam($Girocco::Config::owning_group));
549 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
550 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
551 } else {
552 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
554 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--bare', '--shared='.$self->shared_mode()) == 0
555 or die "git init $self->{path} failed: $?";
556 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
557 or die "disabling receive.denyNonFastforwards failed: $?";
558 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
559 or die "disabling gc.auto failed: $?";
560 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
561 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
562 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
563 or die "setting girocco.creationtime failed: $?";
565 # /info must have right permissions,
566 # and git init didn't do it for some reason.
567 if ($Girocco::Config::owning_group) {
568 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
569 } else {
570 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
573 $self->_properties_save;
574 $self->_alternates_setup;
575 $self->_ctags_setup;
576 $self->_group_remove;
577 $self->_group_add($pushers);
578 $self->_hooks_install;
579 #$self->perm_initialize;
580 $self->_update_index;
583 sub premirror {
584 my $self = shift;
586 $self->_setup(':');
587 $self->_clonep(1);
588 $self->perm_initialize;
591 sub conjure {
592 my $self = shift;
594 $self->_setup;
595 $self->_nofetch(1);
596 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
597 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
598 or die "create-personal-mob-area $self->{name} failed";
600 $self->perm_initialize;
603 sub clone {
604 my $self = shift;
606 unlink ($self->_clonefail_path()); # Ignore EEXIST error
607 unlink ($self->_clonelog_path()); # Ignore EEXIST error
609 use IO::Socket;
610 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
611 $sock->print("clone ".$self->{name}."\n");
612 # Just ignore reply, we are going to succeed anyway and the I/O
613 # would apparently get quite hairy.
614 $sock->flush();
615 sleep 2; # *cough*
616 $sock->close();
619 sub update {
620 my $self = shift;
622 $self->_properties_save;
623 $self->_group_update;
625 if (exists($self->{tags_to_delete})) {
626 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
629 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
631 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
632 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
633 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
634 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
636 $self->_update_index if $self->{email} ne $self->{orig_email};
637 $self->{orig_email} = $self->{email};
642 sub update_password {
643 my $self = shift;
644 my ($pwd) = @_;
646 $self->{crypt} = scrypt_sha1($pwd);
647 $self->_group_update;
650 # You can explicitly do this just on a ghost() repository too.
651 sub delete {
652 my $self = shift;
654 if (-d $self->{path}) {
655 system('rm', '-rf', $self->{path}) == 0
656 or die "rm -rf $self->{path} failed: $?";
658 # attempt to clean up any empty fork directories by removing them
659 my @pelems = split('/', $self->{name});
660 while (@pelems > 1) {
661 pop @pelems;
662 # okay to fail
663 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
665 $self->_group_remove;
666 $self->_update_index;
669 sub _contains_files {
670 my $dir = shift;
671 (-d $dir) or return 0;
672 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
673 while (my $entry = readdir($dh)) {
674 next if $entry eq '' || $entry eq '.' || $entry eq '..';
675 closedir($dh), return 1
676 if -f "$dir/$entry" ||
677 -d "$dir/$entry" && _contains_files("$dir/$entry");
679 closedir($dh);
680 return 0;
683 sub has_forks {
684 my $self = shift;
686 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
689 sub is_empty {
690 # A project is considered empty if the git repository does not
691 # have any refs. This means packed-refs does not exist or is
692 # empty or only has lines starting with '#' AND there are no
693 # files in the refs subdirectory hierarchy (no matter how deep).
695 my $self = shift;
697 (-d $self->{path}) or return 0;
698 if (-e $self->{path}.'/packed-refs') {
699 open(my $pr, '<', $self->{path}.'/packed-refs')
700 or die "open $self->{path}./packed-refs failed: $!";
701 my $foundref = 0;
702 while (my $ref = <$pr>) {
703 next if $ref =~ /^#/;
704 $foundref = 1;
705 last;
707 close($pr);
708 return 0 if $foundref;
710 (-d $self->{path}.'/refs') or return 1;
711 return !_contains_files($self->{path}.'/refs');
714 sub delete_ctag {
715 my $self = shift;
716 my ($ctag) = @_;
718 # sanity check, disallow filenames starting with . .. or /
719 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
722 sub get_ctag_names {
723 my $self = shift;
724 my @ctags = ();
725 opendir(my $dh, $self->{path}.'/ctags')
726 or return @ctags;
727 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
728 closedir($dh);
729 return @ctags;
732 sub get_heads {
733 my $self = shift;
734 my $fh;
735 open($fh, '-|', "$Girocco::Config::git_bin --git-dir=$self->{path} show-ref --heads") or die "could not get list of heads";
736 my @res;
737 while (<$fh>) {
738 chomp;
739 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
740 push @res, $1;
742 close $fh;
743 @res;
746 sub get_HEAD {
747 my $self = shift;
748 my $HEAD = `$Girocco::Config::git_bin --git-dir=$self->{path} symbolic-ref HEAD`;
749 chomp $HEAD;
750 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
751 return $1;
754 sub set_HEAD {
755 my $self = shift;
756 my $newHEAD = shift;
757 # Cursory checks only -- if you want to break your HEAD, be my guest
758 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
759 die "grossly invalid new HEAD: $newHEAD";
761 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
762 die "could not set HEAD" if ($? >> 8);
763 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
764 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
767 sub gen_auth {
768 my $self = shift;
769 my ($type) = @_;
770 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
772 $self->{authtype} = $type;
774 no warnings;
775 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
777 my $expire = time + 24 * 3600;
778 my $propval = "# ${type}AUTH $self->{auth} $expire";
779 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
780 $self->{auth};
783 sub del_auth {
784 my $self = shift;
786 delete $self->{auth};
787 delete $self->{authtype};
788 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
791 sub remove_user {
792 my $self = shift;
793 my ($username) = @_;
795 my $before_count = @{$self->{users}};
796 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
797 return @{$self->{users}} != $before_count;
800 ### static methods
802 sub get_forkee_name {
803 local $_ = $_[0];
804 (m#^(.*)/.*?$#)[0]; #
807 sub get_forkee_path {
808 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
809 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
810 -d $forkee ? $forkee : '';
813 # Ultimately the full project/fork name could end up being part of a Git ref name
814 # when a project's forks are combined into one giant repository for efficiency.
815 # That means that the project/fork name must satisfy the Git ref name requirements:
817 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
818 # 2. The character with an ASCII value of 0x7F is not allowed
819 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
820 # 4. The character '/' is a separator and is not allowed within a name
821 # 5. The name may not start with '.' or end with '.'
822 # 6. The name may not end with '.lock'
823 # 7. The name may not contain the '..' sequence
824 # 8. The name may not contain the '@{' sequence
825 # 9. If multiple components are used (separated by '/'), no empty '' components
827 # We also prohibit a trailing '.git' on any path component and futher restrict
828 # the allowed characters to alphanumeric and [+._-] where names must start with
829 # an alphanumeric.
831 # The rules are relaxed slightly for existing projects (for now) to accomodate them.
833 sub _valid_name_characters {
834 local $_ = $_[0];
835 my $relaxed = $_[1];
836 (not m#^[/+._-]#)
837 and (not m#//#)
838 and (not m#\.\.#)
839 and (not m#/[+._-]# or $relaxed)
840 and (not m#\./#)
841 and (not m#\.$# or $relaxed)
842 and (not m#\.git/#i)
843 and (not m#\.git$#i)
844 and (not m#\.lock/#i)
845 and (not m#\.lock$#i)
846 and (not m#/$#)
847 and m#^[a-zA-Z0-9/+._-]+$#;
850 sub valid_name {
851 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
852 local $_ = $_[0];
853 _valid_name_characters($_) and not exists($reservedprojectnames{$_})
854 and @{[m#/#g]} <= 5 # maximum fork depth is 5
855 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
858 # It's possible that some forks have been kept but the forkee is gone.
859 # In this case the standard valid_name check is too strict.
860 sub does_exist {
861 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
862 my ($name, $nodie) = @_;
863 my $okay = (
864 _valid_name_characters($name, 1)
865 and ((not $name =~ m#/#)
866 or -d get_forkee_path($name)
867 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
868 (!$okay && $nodie) and return undef;
869 !$okay and die "tried to query for project with invalid name $name!";
870 (-d $Girocco::Config::reporoot."/$name.git");
873 sub get_full_list {
874 my $class = shift;
875 my @projects;
877 open F, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
878 while (<F>) {
879 chomp;
880 @_ = split /:+/;
881 next if ($_[2] < 65536);
883 push @projects, $_[0];
885 close F;
886 @projects;