forks: restrict project forks to no more than 5 levels deep
[girocco.git] / Girocco / Project.pm
blobc00f29920f622e549fbc435911ff1fb78dbe4b34
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 our %propmap = (
58 url => ':baseurl',
59 email => ':owner',
60 desc => 'description',
61 README => 'README.html',
62 hp => ':homepage',
63 notifymail => '%hooks.mailinglist',
64 notifytag => '%hooks.announcelist',
65 notifyjson => '%hooks.jsonurl',
66 notifycia => '%hooks.cianame',
69 our %propmapro = (
70 lastchange => ':lastchange',
71 lastactivity => 'info/lastactivity',
74 # Projects with any of these names will be disallowed to avoid possible
75 # collisions with cgi script paths or chroot paths
76 our %reservedprojectnames = (
77 c => 1, # /c/ -> cgit
78 h => 1, # /h/ -> html.cgi
79 r => 1, # /r/ -> git http
80 w => 1, # /w/ -> gitweb
81 srv => 1, # /srv/git/ -> chroot ssh git repositories
84 sub _update_index {
85 system($Girocco::Config::basedir . '/gitweb/genindex.sh');
88 sub _property_path {
89 my $self = shift;
90 my ($name) = @_;
91 $self->{path}.'/'.$name;
94 sub _property_fget {
95 my $self = shift;
96 my ($name) = @_;
97 my $pname = $propmap{$name};
98 $pname = $propmapro{$name} unless $pname;
99 $pname or die "unknown property: $name";
100 if ($pname =~ s/^://) {
101 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "gitweb.$pname"`;
102 chomp $val;
103 return $val;
104 } elsif ($pname =~ s/^%//) {
105 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "$pname"`;
106 chomp $val;
107 return $val;
110 open P, '<', $self->_property_path($pname) or return undef;
111 my @value = <P>;
112 close P;
113 my $value = join('', @value); chomp $value;
114 $value;
117 sub _property_fput {
118 my $self = shift;
119 my ($name, $value) = @_;
120 my $pname = $propmap{$name};
121 $pname or die "unknown property: $name";
122 $value ||= '';
123 if ($pname =~ s/^://) {
124 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
125 return;
126 } elsif ($pname =~ s/^%//) {
127 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
128 return;
131 my $P = lock_file($self->_property_path($pname));
132 $value ne '' and print $P "$value\n";
133 close $P;
134 unlock_file($self->_property_path($pname));
137 sub _properties_load {
138 my $self = shift;
139 foreach my $prop (keys %propmap) {
140 $self->{$prop} = $self->_property_fget($prop);
142 foreach my $prop (keys %propmapro) {
143 $self->{$prop} = $self->_property_fget($prop);
145 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config --bool "gitweb.statusupdates" 2>/dev/null`;
146 chomp $val;
147 $val = ($val eq 'false') ? 0 : 1;
148 $self->{statusupdates} = $val;
149 delete $self->{auth};
150 $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "gitweb.repoauth"`;
151 chomp $val;
152 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
153 my $expire = $3;
154 if (time < $expire) {
155 $self->{authtype} = $1;
156 $self->{auth} = $2;
161 sub _properties_save {
162 my $self = shift;
163 foreach my $prop (keys %propmap) {
164 $self->_property_fput($prop, $self->{$prop});
166 $self->{statusupdates} = 1
167 unless defined($self->{statusupdates}) && $self->{statusupdates} =~ /^\d+$/;
168 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool',
169 "gitweb.statusupdates", $self->{statusupdates});
172 sub _nofetch_path {
173 my $self = shift;
174 $self->_property_path('.nofetch');
177 sub _nofetch {
178 my $self = shift;
179 my ($nofetch) = @_;
180 my $nf = $self->_nofetch_path;
181 if ($nofetch) {
182 open X, '>', $nf or die "nofetch failed: $!";
183 close X;
184 } else {
185 unlink $nf or die "yesfetch failed: $!";
189 sub _clonelog_path {
190 my $self = shift;
191 $self->_property_path('.clonelog');
194 sub _clonefail_path {
195 my $self = shift;
196 $self->_property_path('.clone_failed');
199 sub _clonep_path {
200 my $self = shift;
201 $self->_property_path('.clone_in_progress');
204 sub _clonep {
205 my $self = shift;
206 my ($nofetch) = @_;
207 my $np = $self->_clonep_path;
208 if ($nofetch) {
209 open X, '>', $np or die "clonep failed: $!";
210 close X;
211 } else {
212 unlink $np or die "clonef failed: $!";
215 sub _alternates_setup {
216 my $self = shift;
217 return unless $self->{name} =~ m#/#;
218 my $forkee_name = get_forkee_name($self->{name});
219 my $forkee_path = get_forkee_path($self->{name});
220 return unless -d $forkee_path;
221 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
222 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
223 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
225 # We set up both alternates and http_alternates since we cannot use
226 # relative path in alternates - that doesn't work recursively.
228 my $filename = $self->{path}.'/objects/info/alternates';
229 open X, '>', $filename or die "alternates failed: $!";
230 print X "$forkee_path/objects\n";
231 close X;
232 chmod 0664, $filename or warn "cannot chmod $filename: $!";
234 if ($Girocco::Config::httppullurl) {
235 $filename = $self->{path}.'/objects/info/http-alternates';
236 open X, '>', $filename or die "http-alternates failed: $!";
237 my $upfork = $forkee_name;
238 do { print X "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
239 close X;
240 chmod 0664, $filename or warn "cannot chmod $filename: $!";
243 # The symlink is problematic since git remote prune will traverse it.
244 #symlink "$forkee_path/refs", $self->{path}.'/refs/forkee';
246 # copy refs from parent project
247 # ownership information is changed by a root cronjob
248 system("cp -pR $forkee_path/refs $self->{path}/");
249 # initialize HEAD, hacky version
250 system("cp $forkee_path/HEAD $self->{path}/HEAD");
253 sub _ctags_setup {
254 my $self = shift;
255 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
256 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
259 sub _group_add {
260 my $self = shift;
261 my ($xtra) = @_;
262 $xtra .= join(',', @{$self->{users}});
263 filedb_atomic_append(jailed_file('/etc/group'),
264 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
267 sub _group_update {
268 my $self = shift;
269 my $xtra = join(',', @{$self->{users}});
270 filedb_atomic_edit(jailed_file('/etc/group'),
271 sub {
272 $_ = $_[0];
273 chomp;
274 if ($self->{name} eq (split /:/)[0]) {
275 # preserve readonly flag
276 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
277 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
278 } else {
279 return "$_\n";
285 sub _group_remove {
286 my $self = shift;
287 filedb_atomic_edit(jailed_file('/etc/group'),
288 sub {
289 $self->{name} ne (split /:/)[0] and return $_;
294 sub _hook_path {
295 my $self = shift;
296 my ($name) = @_;
297 $self->{path}.'/hooks/'.$name;
300 sub _hook_install {
301 my $self = shift;
302 my ($name) = @_;
303 open SRC, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
304 open DST, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
305 while (<SRC>) { print DST $_; }
306 close DST;
307 close SRC;
308 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
311 sub _hooks_install {
312 my $self = shift;
313 foreach my $hook ('pre-receive', 'post-receive', 'update', 'post-update') {
314 $self->_hook_install($hook);
318 # private constructor, do not use
319 sub _new {
320 my $class = shift;
321 my ($name, $base_path, $path) = @_;
322 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
323 $path ||= "$base_path/$name.git";
324 my $proj = { name => $name, base_path => $base_path, path => $path };
326 bless $proj, $class;
329 # public constructor #0
330 # creates a virtual project not connected to disk image
331 # you can conjure() it later to disk
332 sub ghost {
333 my $class = shift;
334 my ($name, $mirror) = @_;
335 my $self = $class->_new($name, $Girocco::Config::reporoot);
336 $self->{users} = [];
337 $self->{mirror} = $mirror;
338 $self->{email} = $self->{orig_email} = '';
339 $self;
342 # public constructor #1
343 sub load {
344 my $class = shift;
345 my $name = shift || '';
347 open F, '<', jailed_file("/etc/group") or die "project load failed: $!";
348 while (<F>) {
349 chomp;
350 @_ = split /:+/;
351 next unless (shift eq $name);
353 my $self = $class->_new($name, $Girocco::Config::reporoot);
354 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
356 my $ulist;
357 ($self->{crypt}, $self->{gid}, $ulist) = @_;
358 $ulist ||= '';
359 $self->{users} = [split /,/, $ulist];
360 $self->{HEAD} = $self->get_HEAD;
361 $self->{orig_HEAD} = $self->{HEAD};
362 $self->{orig_users} = [@{$self->{users}}];
363 $self->{mirror} = ! -e $self->_nofetch_path;
364 $self->{clone_in_progress} = -e $self->_clonep_path;
365 $self->{clone_logged} = -e $self->_clonelog_path;
366 $self->{clone_failed} = -e $self->_clonefail_path;
367 $self->{ccrypt} = $self->{crypt};
369 $self->_properties_load;
370 $self->{orig_email} = $self->{email};
371 return $self;
373 close F;
374 undef;
377 # $proj may not be in sane state if this returns false!
378 sub cgi_fill {
379 my $self = shift;
380 my ($gcgi) = @_;
381 my $cgi = $gcgi->cgi;
383 my ($pwd, $pwd2) = ($cgi->param('pwd'), $cgi->param('pwd2'));
384 # in case passwords are disabled
385 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
386 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
387 $gcgi->err("Empty passwords are not permitted.");
389 if ($pwd ne '' or not $self->{crypt}) {
390 $self->{crypt} = scrypt_sha1($pwd);
392 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
393 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
396 $self->{cpwd} = $cgi->param('cpwd');
398 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
399 my $newtype = $forkee ? 'fork' : 'project';
400 length($project) <= 64
401 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
403 if ($Girocco::Config::project_owners eq 'email') {
404 $self->{email} = $gcgi->wparam('email');
405 valid_email($self->{email})
406 or $gcgi->err("Your email sure looks weird...?");
407 length($self->{email}) <= 96
408 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
411 $self->{url} = $gcgi->wparam('url');
412 if ($self->{url}) {
413 valid_repo_url($self->{url})
414 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
415 if ($Girocco::Config::restrict_mirror_hosts) {
416 my $mh = extract_url_hostname($self->{url});
417 is_dns_hostname($mh)
418 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
419 !is_our_hostname($mh)
420 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
424 $self->{desc} = $gcgi->wparam('desc');
425 length($self->{desc}) <= 1024
426 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
428 $self->{README} = $gcgi->wparam('README');
429 length($self->{README}) <= 8192
430 or $gcgi->err("README length &gt; 8kb!");
432 $self->{hp} = $gcgi->wparam('hp');
433 if ($self->{hp}) {
434 valid_web_url($self->{hp})
435 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
438 $self->{users} = [grep { Girocco::User::valid_name($_) && Girocco::User::does_exist($_) } $cgi->param('user')];
440 $self->{HEAD} = $cgi->param('HEAD') if $cgi->param('HEAD');
442 # schedule deletion of tags (will be committed by update() after auth)
443 $self->{tags_to_delete} = [$cgi->param('tags')];
445 $self->{notifymail} = $gcgi->wparam('notifymail');
446 if ($self->{notifymail}) {
447 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
448 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
451 $self->{notifyjson} = $gcgi->wparam('notifyjson');
452 if ($self->{notifyjson}) {
453 valid_web_url($self->{notifyjson})
454 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
457 $self->{notifycia} = $gcgi->wparam('notifycia');
458 if ($self->{notifycia}) {
459 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
460 or $gcgi->err("Overly suspicious CIA notify project name. If it is actually valid, contact me.");
463 if ($cgi->param('setstatusupdates')) {
464 my $val = $gcgi->wparam('statusupdates') || '0';
465 $self->{statusupdates} = $val ? 1 : 0;
468 not $gcgi->err_check;
471 sub form_defaults {
472 my $self = shift;
474 name => $self->{name},
475 email => $self->{email},
476 url => $self->{url},
477 desc => html_esc($self->{desc}),
478 README => html_esc($self->{README}),
479 hp => $self->{hp},
480 users => $self->{users},
481 notifymail => html_esc($self->{notifymail}),
482 notifyjson => html_esc($self->{notifyjson}),
483 notifycia => html_esc($self->{notifycia}),
487 # return true if $enc_passwd is a match for $plain_passwd
488 my $_check_passwd_match = sub {
489 my $enc_passwd = shift;
490 my $plain_passwd = shift;
491 defined($enc_passwd) or $enc_passwd = '';
492 defined($plain_passwd) or $plain_passwd = '';
493 # $enc_passwd may be crypt or crypt_sha1
494 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
495 # It's using sha1-crypt
496 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
497 } else {
498 # It's using crypt
499 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
503 sub authenticate {
504 my $self = shift;
505 my ($gcgi) = @_;
507 $self->{ccrypt} or die "Can't authenticate against a project with no password";
508 defined($self->{cpwd}) or $self->{cpwd} = '';
509 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
510 $gcgi->err("Your admin password does not match!");
511 return 0;
513 return 1;
516 sub _setup {
517 my $self = shift;
518 my ($pushers) = @_;
520 $self->_mkdir_forkees;
522 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
523 if ($Girocco::Config::owning_group) {
524 my $gid = scalar(getgrnam($Girocco::Config::owning_group));
525 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
526 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
527 } else {
528 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
530 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--bare', '--shared='.$self->shared_mode()) == 0
531 or die "git init $self->{path} failed: $?";
532 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
533 or die "disabling receive.denyNonFastforwards failed: $?";
534 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
535 or die "disabling gc.auto failed: $?";
537 # /info must have right permissions,
538 # and git init didn't do it for some reason.
539 if ($Girocco::Config::owning_group) {
540 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
541 } else {
542 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
545 $self->_properties_save;
546 $self->_alternates_setup;
547 $self->_ctags_setup;
548 $self->_group_remove;
549 $self->_group_add($pushers);
550 $self->_hooks_install;
551 #$self->perm_initialize;
552 $self->_update_index;
555 sub premirror {
556 my $self = shift;
558 $self->_setup(':');
559 $self->_clonep(1);
560 $self->perm_initialize;
563 sub conjure {
564 my $self = shift;
566 $self->_setup;
567 $self->_nofetch(1);
568 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
569 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
570 or die "create-personal-mob-area $self->{name} failed";
572 $self->perm_initialize;
575 sub clone {
576 my $self = shift;
578 unlink ($self->_clonefail_path()); # Ignore EEXIST error
579 unlink ($self->_clonelog_path()); # Ignore EEXIST error
581 use IO::Socket;
582 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
583 $sock->print("clone ".$self->{name}."\n");
584 # Just ignore reply, we are going to succeed anyway and the I/O
585 # would apparently get quite hairy.
586 $sock->flush();
587 sleep 2; # *cough*
588 $sock->close();
591 sub update {
592 my $self = shift;
594 $self->_properties_save;
595 $self->_group_update;
597 if (exists($self->{tags_to_delete})) {
598 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
601 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
603 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
604 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
605 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
606 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
608 $self->_update_index if $self->{email} ne $self->{orig_email};
609 $self->{orig_email} = $self->{email};
614 sub update_password {
615 my $self = shift;
616 my ($pwd) = @_;
618 $self->{crypt} = scrypt_sha1($pwd);
619 $self->_group_update;
622 # You can explicitly do this just on a ghost() repository too.
623 sub delete {
624 my $self = shift;
626 if (-d $self->{path}) {
627 system('rm', '-rf', $self->{path}) == 0
628 or die "rm -rf $self->{path} failed: $?";
630 # attempt to clean up any empty fork directories by removing them
631 my @pelems = split('/', $self->{name});
632 while (@pelems > 1) {
633 pop @pelems;
634 # okay to fail
635 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
637 $self->_group_remove;
638 $self->_update_index;
641 sub _contains_files {
642 my $dir = shift;
643 (-d $dir) or return 0;
644 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
645 while (my $entry = readdir($dh)) {
646 next if $entry eq '' || $entry eq '.' || $entry eq '..';
647 closedir($dh), return 1
648 if -f "$dir/$entry" ||
649 -d "$dir/$entry" && _contains_files("$dir/$entry");
651 closedir($dh);
652 return 0;
655 sub has_forks {
656 my $self = shift;
658 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
661 sub is_empty {
662 # A project is considered empty if the git repository does not
663 # have any refs. This means packed-refs does not exist or is
664 # empty or only has lines starting with '#' AND there are no
665 # files in the refs subdirectory hierarchy (no matter how deep).
667 my $self = shift;
669 (-d $self->{path}) or return 0;
670 if (-e $self->{path}.'/packed-refs') {
671 open(my $pr, '<', $self->{path}.'/packed-refs')
672 or die "open $self->{path}./packed-refs failed: $!";
673 my $foundref = 0;
674 while (my $ref = <$pr>) {
675 next if $ref =~ /^#/;
676 $foundref = 1;
677 last;
679 close($pr);
680 return 0 if $foundref;
682 (-d $self->{path}.'/refs') or return 1;
683 return !_contains_files($self->{path}.'/refs');
686 sub delete_ctag {
687 my $self = shift;
688 my ($ctag) = @_;
690 # sanity check, disallow filenames starting with . .. or /
691 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
694 sub get_ctag_names {
695 my $self = shift;
696 my @ctags = ();
697 opendir(my $dh, $self->{path}.'/ctags')
698 or return @ctags;
699 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
700 closedir($dh);
701 return @ctags;
704 sub get_heads {
705 my $self = shift;
706 my $fh;
707 open($fh, '-|', "$Girocco::Config::git_bin --git-dir=$self->{path} show-ref --heads") or die "could not get list of heads";
708 my @res;
709 while (<$fh>) {
710 chomp;
711 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
712 push @res, $1;
714 close $fh;
715 @res;
718 sub get_HEAD {
719 my $self = shift;
720 my $HEAD = `$Girocco::Config::git_bin --git-dir=$self->{path} symbolic-ref HEAD`;
721 chomp $HEAD;
722 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
723 return $1;
726 sub set_HEAD {
727 my $self = shift;
728 my $newHEAD = shift;
729 # Cursory checks only -- if you want to break your HEAD, be my guest
730 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
731 die "grossly invalid new HEAD: $newHEAD";
733 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
734 die "could not set HEAD" if ($? >> 8);
735 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
736 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
739 sub gen_auth {
740 my $self = shift;
741 my ($type) = @_;
742 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
744 $self->{authtype} = $type;
746 no warnings;
747 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
749 my $expire = time + 24 * 3600;
750 my $propval = "# ${type}AUTH $self->{auth} $expire";
751 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
752 $self->{auth};
755 sub del_auth {
756 my $self = shift;
758 delete $self->{auth};
759 delete $self->{authtype};
760 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
763 sub remove_user {
764 my $self = shift;
765 my ($username) = @_;
767 my $before_count = @{$self->{users}};
768 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
769 return @{$self->{users}} != $before_count;
772 ### static methods
774 sub get_forkee_name {
775 local $_ = $_[0];
776 (m#^(.*)/.*?$#)[0]; #
779 sub get_forkee_path {
780 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
781 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
782 -d $forkee ? $forkee : '';
785 # Ultimately the full project/fork name could end up being part of a Git ref name
786 # when a project's forks are combined into one giant repository for efficiency.
787 # That means that the project/fork name must satisfy the Git ref name requirements:
789 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
790 # 2. The character with an ASCII value of 0x7F is not allowed
791 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
792 # 4. The character '/' is a separator and is not allowed within a name
793 # 5. The name may not start with '.' or end with '.'
794 # 6. The name may not end with '.lock'
795 # 7. The name may not contain the '..' sequence
796 # 8. The name may not contain the '@{' sequence
797 # 9. If multiple components are used (separated by '/'), no empty '' components
799 # We also prohibit a trailing '.git' on any path component and futher restrict
800 # the allowed characters to alphanumeric and [+._-] where names must start with
801 # an alphanumeric.
803 # The rules are relaxed slightly for existing projects (for now) to accomodate them.
805 sub _valid_name_characters {
806 local $_ = $_[0];
807 my $relaxed = $_[1];
808 (not m#^[/+._-]#)
809 and (not m#//#)
810 and (not m#\.\.#)
811 and (not m#/[+._-]# or $relaxed)
812 and (not m#\./#)
813 and (not m#\.$# or $relaxed)
814 and (not m#\.git/#i)
815 and (not m#\.git$#i)
816 and (not m#\.lock/#i)
817 and (not m#\.lock$#i)
818 and (not m#/$#)
819 and m#^[a-zA-Z0-9/+._-]+$#;
822 sub valid_name {
823 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
824 local $_ = $_[0];
825 _valid_name_characters($_) and not exists($reservedprojectnames{$_})
826 and @{[m#/#g]} <= 5 # maximum fork depth is 5
827 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
830 # It's possible that some forks have been kept but the forkee is gone.
831 # In this case the standard valid_name check is too strict.
832 sub does_exist {
833 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
834 my ($name, $nodie) = @_;
835 my $okay = (
836 _valid_name_characters($name, 1)
837 and ((not $name =~ m#/#)
838 or -d get_forkee_path($name)
839 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
840 (!$okay && $nodie) and return undef;
841 !$okay and die "tried to query for project with invalid name $name!";
842 (-d $Girocco::Config::reporoot."/$name.git");
845 sub get_full_list {
846 my $class = shift;
847 my @projects;
849 open F, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
850 while (<F>) {
851 chomp;
852 @_ = split /:+/;
853 next if ($_[2] < 65536);
855 push @projects, $_[0];
857 close F;
858 @projects;