updating: bang again if baseurl is changed
[girocco.git] / Girocco / Project.pm
blob277350e0b1263e5f0caa4c1123bd72dcac4bde39
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 c => 1, # /c/ -> cgit
85 h => 1, # /h/ -> html.cgi
86 r => 1, # /r/ -> git http
87 w => 1, # /w/ -> gitweb
88 srv => 1, # /srv/git/ -> chroot ssh git repositories
91 sub _update_index {
92 system($Girocco::Config::basedir . '/gitweb/genindex.sh');
95 sub _property_path {
96 my $self = shift;
97 my ($name) = @_;
98 $self->{path}.'/'.$name;
101 sub _property_fget {
102 my $self = shift;
103 my ($name) = @_;
104 my $pname = $propmap{$name};
105 $pname = $propmapro{$name} unless $pname;
106 $pname or die "unknown property: $name";
107 if ($pname =~ s/^://) {
108 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "gitweb.$pname"`;
109 chomp $val;
110 return $val;
111 } elsif ($pname =~ s/^%//) {
112 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "$pname"`;
113 chomp $val;
114 return $val;
117 open P, '<', $self->_property_path($pname) or return undef;
118 my @value = <P>;
119 close P;
120 my $value = join('', @value); chomp $value;
121 $value;
124 sub _property_fput {
125 my $self = shift;
126 my ($name, $value) = @_;
127 my $pname = $propmap{$name};
128 $pname or die "unknown property: $name";
129 $value ||= '';
130 if ($pname =~ s/^://) {
131 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
132 return;
133 } elsif ($pname =~ s/^%//) {
134 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
135 return;
138 my $P = lock_file($self->_property_path($pname));
139 $value ne '' and print $P "$value\n";
140 close $P;
141 unlock_file($self->_property_path($pname));
144 sub _properties_load {
145 my $self = shift;
146 foreach my $prop (keys %propmap) {
147 $self->{$prop} = $self->_property_fget($prop);
149 foreach my $prop (keys %propmapro) {
150 $self->{$prop} = $self->_property_fget($prop);
152 my $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config --bool "gitweb.statusupdates" 2>/dev/null`;
153 chomp $val;
154 $val = ($val eq 'false') ? 0 : 1;
155 $self->{statusupdates} = $val;
156 delete $self->{auth};
157 $val = `"$Girocco::Config::git_bin" --git-dir="$self->{path}" config "gitweb.repoauth"`;
158 chomp $val;
159 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
160 my $expire = $3;
161 if (time < $expire) {
162 $self->{authtype} = $1;
163 $self->{auth} = $2;
168 sub _properties_save {
169 my $self = shift;
170 foreach my $prop (keys %propmap) {
171 $self->_property_fput($prop, $self->{$prop});
173 $self->{statusupdates} = 1
174 unless defined($self->{statusupdates}) && $self->{statusupdates} =~ /^\d+$/;
175 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool',
176 "gitweb.statusupdates", $self->{statusupdates});
177 if (defined($self->{origurl}) && defined($self->{url}) &&
178 $self->{origurl} ne $self->{url} && -e $self->_property_path(".banged")) {
179 if (open(X, '>', $self->_property_path(".bangagain"))) {
180 close X;
181 chmod(0664, $self->_property_path(".bangagain"));
186 sub _nofetch_path {
187 my $self = shift;
188 $self->_property_path('.nofetch');
191 sub _nofetch {
192 my $self = shift;
193 my ($nofetch) = @_;
194 my $nf = $self->_nofetch_path;
195 if ($nofetch) {
196 open X, '>', $nf or die "nofetch failed: $!";
197 close X;
198 } else {
199 unlink $nf or die "yesfetch failed: $!";
203 sub _clonelog_path {
204 my $self = shift;
205 $self->_property_path('.clonelog');
208 sub _clonefail_path {
209 my $self = shift;
210 $self->_property_path('.clone_failed');
213 sub _clonep_path {
214 my $self = shift;
215 $self->_property_path('.clone_in_progress');
218 sub _clonep {
219 my $self = shift;
220 my ($nofetch) = @_;
221 my $np = $self->_clonep_path;
222 if ($nofetch) {
223 open X, '>', $np or die "clonep failed: $!";
224 close X;
225 } else {
226 unlink $np or die "clonef failed: $!";
229 sub _alternates_setup {
230 my $self = shift;
231 return unless $self->{name} =~ m#/#;
232 my $forkee_name = get_forkee_name($self->{name});
233 my $forkee_path = get_forkee_path($self->{name});
234 return unless -d $forkee_path;
235 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
236 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
237 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
239 # We set up both alternates and http_alternates since we cannot use
240 # relative path in alternates - that doesn't work recursively.
242 my $filename = $self->{path}.'/objects/info/alternates';
243 open X, '>', $filename or die "alternates failed: $!";
244 print X "$forkee_path/objects\n";
245 close X;
246 chmod 0664, $filename or warn "cannot chmod $filename: $!";
248 if ($Girocco::Config::httppullurl) {
249 $filename = $self->{path}.'/objects/info/http-alternates';
250 open X, '>', $filename or die "http-alternates failed: $!";
251 my $upfork = $forkee_name;
252 do { print X "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
253 close X;
254 chmod 0664, $filename or warn "cannot chmod $filename: $!";
257 # The symlink is problematic since git remote prune will traverse it.
258 #symlink "$forkee_path/refs", $self->{path}.'/refs/forkee';
260 # copy refs from parent project
261 # ownership information is changed by a root cronjob
262 system("cp -pR $forkee_path/refs $self->{path}/");
263 # initialize HEAD, hacky version
264 system("cp $forkee_path/HEAD $self->{path}/HEAD");
267 sub _ctags_setup {
268 my $self = shift;
269 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
270 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
273 sub _group_add {
274 my $self = shift;
275 my ($xtra) = @_;
276 $xtra .= join(',', @{$self->{users}});
277 filedb_atomic_append(jailed_file('/etc/group'),
278 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
281 sub _group_update {
282 my $self = shift;
283 my $xtra = join(',', @{$self->{users}});
284 filedb_atomic_edit(jailed_file('/etc/group'),
285 sub {
286 $_ = $_[0];
287 chomp;
288 if ($self->{name} eq (split /:/)[0]) {
289 # preserve readonly flag
290 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
291 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
292 } else {
293 return "$_\n";
299 sub _group_remove {
300 my $self = shift;
301 filedb_atomic_edit(jailed_file('/etc/group'),
302 sub {
303 $self->{name} ne (split /:/)[0] and return $_;
308 sub _hook_path {
309 my $self = shift;
310 my ($name) = @_;
311 $self->{path}.'/hooks/'.$name;
314 sub _hook_install {
315 my $self = shift;
316 my ($name) = @_;
317 open SRC, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
318 open DST, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
319 while (<SRC>) { print DST $_; }
320 close DST;
321 close SRC;
322 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
325 sub _hooks_install {
326 my $self = shift;
327 foreach my $hook ('pre-receive', 'post-receive', 'update', 'post-update') {
328 $self->_hook_install($hook);
332 # private constructor, do not use
333 sub _new {
334 my $class = shift;
335 my ($name, $base_path, $path) = @_;
336 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
337 $path ||= "$base_path/$name.git";
338 my $proj = { name => $name, base_path => $base_path, path => $path };
340 bless $proj, $class;
343 # public constructor #0
344 # creates a virtual project not connected to disk image
345 # you can conjure() it later to disk
346 sub ghost {
347 my $class = shift;
348 my ($name, $mirror) = @_;
349 my $self = $class->_new($name, $Girocco::Config::reporoot);
350 $self->{users} = [];
351 $self->{mirror} = $mirror;
352 $self->{email} = $self->{orig_email} = '';
353 $self;
356 # public constructor #1
357 sub load {
358 my $class = shift;
359 my $name = shift || '';
361 open F, '<', jailed_file("/etc/group") or die "project load failed: $!";
362 while (<F>) {
363 chomp;
364 @_ = split /:+/;
365 next unless (shift eq $name);
367 my $self = $class->_new($name, $Girocco::Config::reporoot);
368 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
370 my $ulist;
371 ($self->{crypt}, $self->{gid}, $ulist) = @_;
372 $ulist ||= '';
373 $self->{users} = [split /,/, $ulist];
374 $self->{HEAD} = $self->get_HEAD;
375 $self->{orig_HEAD} = $self->{HEAD};
376 $self->{orig_users} = [@{$self->{users}}];
377 $self->{mirror} = ! -e $self->_nofetch_path;
378 $self->{clone_in_progress} = -e $self->_clonep_path;
379 $self->{clone_logged} = -e $self->_clonelog_path;
380 $self->{clone_failed} = -e $self->_clonefail_path;
381 $self->{ccrypt} = $self->{crypt};
383 $self->_properties_load;
384 $self->{orig_email} = $self->{email};
385 $self->{loaded} = 1; # indicates self was loaded from etc/group file
386 return $self;
388 close F;
389 undef;
392 # $proj may not be in sane state if this returns false!
393 sub cgi_fill {
394 my $self = shift;
395 my ($gcgi) = @_;
396 my $cgi = $gcgi->cgi;
398 my ($pwd, $pwd2) = ($cgi->param('pwd'), $cgi->param('pwd2'));
399 # in case passwords are disabled
400 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
401 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
402 $gcgi->err("Empty passwords are not permitted.");
404 if ($pwd ne '' or not $self->{crypt}) {
405 $self->{crypt} = scrypt_sha1($pwd);
407 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
408 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
411 $self->{cpwd} = $cgi->param('cpwd');
413 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
414 my $newtype = $forkee ? 'fork' : 'project';
415 length($project) <= 64
416 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
418 if ($Girocco::Config::project_owners eq 'email') {
419 $self->{email} = $gcgi->wparam('email');
420 valid_email($self->{email})
421 or $gcgi->err("Your email sure looks weird...?");
422 length($self->{email}) <= 96
423 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
426 $self->{url} = $gcgi->wparam('url');
427 if ($self->{url}) {
428 valid_repo_url($self->{url})
429 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
430 if ($Girocco::Config::restrict_mirror_hosts) {
431 my $mh = extract_url_hostname($self->{url});
432 is_dns_hostname($mh)
433 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
434 !is_our_hostname($mh)
435 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
439 $self->{desc} = $gcgi->wparam('desc');
440 length($self->{desc}) <= 1024
441 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
443 $self->{README} = $gcgi->wparam('README');
444 length($self->{README}) <= 8192
445 or $gcgi->err("README length &gt; 8kb!");
447 $self->{hp} = $gcgi->wparam('hp');
448 if ($self->{hp}) {
449 valid_web_url($self->{hp})
450 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
453 $self->{users} = [grep { Girocco::User::valid_name($_) && Girocco::User::does_exist($_) } $cgi->param('user')];
455 $self->{HEAD} = $cgi->param('HEAD') if $cgi->param('HEAD');
457 # schedule deletion of tags (will be committed by update() after auth)
458 $self->{tags_to_delete} = [$cgi->param('tags')];
460 $self->{notifymail} = $gcgi->wparam('notifymail');
461 if ($self->{notifymail}) {
462 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
463 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
466 $self->{notifyjson} = $gcgi->wparam('notifyjson');
467 if ($self->{notifyjson}) {
468 valid_web_url($self->{notifyjson})
469 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
472 $self->{notifycia} = $gcgi->wparam('notifycia');
473 if ($self->{notifycia}) {
474 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
475 or $gcgi->err("Overly suspicious CIA notify project name. If it is actually valid, contact me.");
478 if ($cgi->param('setstatusupdates')) {
479 my $val = $gcgi->wparam('statusupdates') || '0';
480 $self->{statusupdates} = $val ? 1 : 0;
483 not $gcgi->err_check;
486 sub form_defaults {
487 my $self = shift;
489 name => $self->{name},
490 email => $self->{email},
491 url => $self->{url},
492 desc => html_esc($self->{desc}),
493 README => html_esc($self->{README}),
494 hp => $self->{hp},
495 users => $self->{users},
496 notifymail => html_esc($self->{notifymail}),
497 notifyjson => html_esc($self->{notifyjson}),
498 notifycia => html_esc($self->{notifycia}),
502 # return true if $enc_passwd is a match for $plain_passwd
503 my $_check_passwd_match = sub {
504 my $enc_passwd = shift;
505 my $plain_passwd = shift;
506 defined($enc_passwd) or $enc_passwd = '';
507 defined($plain_passwd) or $plain_passwd = '';
508 # $enc_passwd may be crypt or crypt_sha1
509 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
510 # It's using sha1-crypt
511 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
512 } else {
513 # It's using crypt
514 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
518 sub authenticate {
519 my $self = shift;
520 my ($gcgi) = @_;
522 $self->{ccrypt} or die "Can't authenticate against a project with no password";
523 defined($self->{cpwd}) or $self->{cpwd} = '';
524 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
525 $gcgi->err("Your admin password does not match!");
526 return 0;
528 return 1;
531 # return true if the password from the file is empty or consists of all the same
532 # character. However, if the project was NOT loaded from the group file
533 # (!self->{loaded}) then the password is never locked.
534 # This function does NOT check $Girocco::Config::project_passwords, the caller
535 # is responsible for doing so if desired. Same for $self->{email}.
536 sub is_password_locked {
537 my $self = shift;
539 $self->{loaded} or return 0;
540 my $testcrypt = $self->{ccrypt}; # The value from the group file
541 defined($testcrypt) or $testcrypt = '';
542 $testcrypt ne '' or return 1; # No password at all
543 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
544 return 0; # Not locked
547 sub _setup {
548 use POSIX qw(strftime);
549 my $self = shift;
550 my ($pushers) = @_;
552 $self->_mkdir_forkees;
554 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
555 if ($Girocco::Config::owning_group) {
556 my $gid = scalar(getgrnam($Girocco::Config::owning_group));
557 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
558 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
559 } else {
560 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
562 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--bare', '--shared='.$self->shared_mode()) == 0
563 or die "git init $self->{path} failed: $?";
564 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
565 or die "disabling receive.denyNonFastforwards failed: $?";
566 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
567 or die "disabling gc.auto failed: $?";
568 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
569 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
570 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
571 or die "setting girocco.creationtime failed: $?";
573 # /info must have right permissions,
574 # and git init didn't do it for some reason.
575 if ($Girocco::Config::owning_group) {
576 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
577 } else {
578 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
581 $self->_properties_save;
582 $self->_alternates_setup;
583 $self->_ctags_setup;
584 $self->_group_remove;
585 $self->_group_add($pushers);
586 $self->_hooks_install;
587 #$self->perm_initialize;
588 $self->_update_index;
591 sub premirror {
592 my $self = shift;
594 $self->_setup(':');
595 $self->_clonep(1);
596 $self->perm_initialize;
599 sub conjure {
600 my $self = shift;
602 $self->_setup;
603 $self->_nofetch(1);
604 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
605 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
606 or die "create-personal-mob-area $self->{name} failed";
608 $self->perm_initialize;
611 sub clone {
612 my $self = shift;
614 unlink ($self->_clonefail_path()); # Ignore EEXIST error
615 unlink ($self->_clonelog_path()); # Ignore EEXIST error
617 use IO::Socket;
618 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
619 $sock->print("clone ".$self->{name}."\n");
620 # Just ignore reply, we are going to succeed anyway and the I/O
621 # would apparently get quite hairy.
622 $sock->flush();
623 sleep 2; # *cough*
624 $sock->close();
627 sub update {
628 my $self = shift;
630 $self->_properties_save;
631 $self->_group_update;
633 if (exists($self->{tags_to_delete})) {
634 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
637 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
639 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
640 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
641 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
642 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
644 $self->_update_index if $self->{email} ne $self->{orig_email};
645 $self->{orig_email} = $self->{email};
650 sub update_password {
651 my $self = shift;
652 my ($pwd) = @_;
654 $self->{crypt} = scrypt_sha1($pwd);
655 $self->_group_update;
658 # You can explicitly do this just on a ghost() repository too.
659 sub delete {
660 my $self = shift;
662 if (-d $self->{path}) {
663 system('rm', '-rf', $self->{path}) == 0
664 or die "rm -rf $self->{path} failed: $?";
666 # attempt to clean up any empty fork directories by removing them
667 my @pelems = split('/', $self->{name});
668 while (@pelems > 1) {
669 pop @pelems;
670 # okay to fail
671 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
673 $self->_group_remove;
674 $self->_update_index;
677 sub _contains_files {
678 my $dir = shift;
679 (-d $dir) or return 0;
680 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
681 while (my $entry = readdir($dh)) {
682 next if $entry eq '' || $entry eq '.' || $entry eq '..';
683 closedir($dh), return 1
684 if -f "$dir/$entry" ||
685 -d "$dir/$entry" && _contains_files("$dir/$entry");
687 closedir($dh);
688 return 0;
691 sub has_forks {
692 my $self = shift;
694 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
697 sub is_empty {
698 # A project is considered empty if the git repository does not
699 # have any refs. This means packed-refs does not exist or is
700 # empty or only has lines starting with '#' AND there are no
701 # files in the refs subdirectory hierarchy (no matter how deep).
703 my $self = shift;
705 (-d $self->{path}) or return 0;
706 if (-e $self->{path}.'/packed-refs') {
707 open(my $pr, '<', $self->{path}.'/packed-refs')
708 or die "open $self->{path}./packed-refs failed: $!";
709 my $foundref = 0;
710 while (my $ref = <$pr>) {
711 next if $ref =~ /^#/;
712 $foundref = 1;
713 last;
715 close($pr);
716 return 0 if $foundref;
718 (-d $self->{path}.'/refs') or return 1;
719 return !_contains_files($self->{path}.'/refs');
722 sub delete_ctag {
723 my $self = shift;
724 my ($ctag) = @_;
726 # sanity check, disallow filenames starting with . .. or /
727 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
730 sub get_ctag_names {
731 my $self = shift;
732 my @ctags = ();
733 opendir(my $dh, $self->{path}.'/ctags')
734 or return @ctags;
735 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
736 closedir($dh);
737 return @ctags;
740 sub get_heads {
741 my $self = shift;
742 my $fh;
743 open($fh, '-|', "$Girocco::Config::git_bin --git-dir=$self->{path} show-ref --heads") or die "could not get list of heads";
744 my @res;
745 while (<$fh>) {
746 chomp;
747 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
748 push @res, $1;
750 close $fh;
751 @res;
754 sub get_HEAD {
755 my $self = shift;
756 my $HEAD = `$Girocco::Config::git_bin --git-dir=$self->{path} symbolic-ref HEAD`;
757 chomp $HEAD;
758 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
759 return $1;
762 sub set_HEAD {
763 my $self = shift;
764 my $newHEAD = shift;
765 # Cursory checks only -- if you want to break your HEAD, be my guest
766 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
767 die "grossly invalid new HEAD: $newHEAD";
769 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
770 die "could not set HEAD" if ($? >> 8);
771 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
772 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
775 sub gen_auth {
776 my $self = shift;
777 my ($type) = @_;
778 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
780 $self->{authtype} = $type;
782 no warnings;
783 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
785 my $expire = time + 24 * 3600;
786 my $propval = "# ${type}AUTH $self->{auth} $expire";
787 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
788 $self->{auth};
791 sub del_auth {
792 my $self = shift;
794 delete $self->{auth};
795 delete $self->{authtype};
796 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
799 sub remove_user {
800 my $self = shift;
801 my ($username) = @_;
803 my $before_count = @{$self->{users}};
804 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
805 return @{$self->{users}} != $before_count;
808 ### static methods
810 sub get_forkee_name {
811 local $_ = $_[0];
812 (m#^(.*)/.*?$#)[0]; #
815 sub get_forkee_path {
816 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
817 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
818 -d $forkee ? $forkee : '';
821 # Ultimately the full project/fork name could end up being part of a Git ref name
822 # when a project's forks are combined into one giant repository for efficiency.
823 # That means that the project/fork name must satisfy the Git ref name requirements:
825 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
826 # 2. The character with an ASCII value of 0x7F is not allowed
827 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
828 # 4. The character '/' is a separator and is not allowed within a name
829 # 5. The name may not start with '.' or end with '.'
830 # 6. The name may not end with '.lock'
831 # 7. The name may not contain the '..' sequence
832 # 8. The name may not contain the '@{' sequence
833 # 9. If multiple components are used (separated by '/'), no empty '' components
835 # We also prohibit a trailing '.git' on any path component and futher restrict
836 # the allowed characters to alphanumeric and [+._-] where names must start with
837 # an alphanumeric.
839 # The rules are relaxed slightly for existing projects (for now) to accomodate them.
841 sub _valid_name_characters {
842 local $_ = $_[0];
843 my $relaxed = $_[1];
844 (not m#^[/+._-]#)
845 and (not m#//#)
846 and (not m#\.\.#)
847 and (not m#/[+._-]# or $relaxed)
848 and (not m#\./#)
849 and (not m#\.$# or $relaxed)
850 and (not m#\.git/#i)
851 and (not m#\.git$#i)
852 and (not m#\.lock/#i)
853 and (not m#\.lock$#i)
854 and (not m#/$#)
855 and m#^[a-zA-Z0-9/+._-]+$#;
858 sub valid_name {
859 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
860 local $_ = $_[0];
861 _valid_name_characters($_) and not exists($reservedprojectnames{$_})
862 and @{[m#/#g]} <= 5 # maximum fork depth is 5
863 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
866 # It's possible that some forks have been kept but the forkee is gone.
867 # In this case the standard valid_name check is too strict.
868 sub does_exist {
869 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
870 my ($name, $nodie) = @_;
871 my $okay = (
872 _valid_name_characters($name, 1)
873 and ((not $name =~ m#/#)
874 or -d get_forkee_path($name)
875 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
876 (!$okay && $nodie) and return undef;
877 !$okay and die "tried to query for project with invalid name $name!";
878 (-d $Girocco::Config::reporoot."/$name.git");
881 sub get_full_list {
882 my $class = shift;
883 my @projects;
885 open F, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
886 while (<F>) {
887 chomp;
888 @_ = split /:+/;
889 next if ($_[2] < 65536);
891 push @projects, $_[0];
893 close F;
894 @projects;