clone.sh: properly set HEAD on initial clone
[girocco.git] / Girocco / Project.pm
blobb71a5905221e4bf556b1c4ac2520aca758460a4a
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: $?";
574 # /info must have right permissions,
575 # and git init didn't do it for some reason.
576 if ($Girocco::Config::owning_group) {
577 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
578 } else {
579 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
582 $self->_properties_save;
583 $self->_alternates_setup;
584 $self->_ctags_setup;
585 $self->_group_remove;
586 $self->_group_add($pushers);
587 $self->_hooks_install;
588 #$self->perm_initialize;
589 $self->_update_index;
592 sub premirror {
593 my $self = shift;
595 $self->_setup(':');
596 $self->_clonep(1);
597 $self->perm_initialize;
600 sub conjure {
601 my $self = shift;
603 $self->_setup;
604 $self->_nofetch(1);
605 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
606 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
607 or die "create-personal-mob-area $self->{name} failed";
609 $self->perm_initialize;
612 sub clone {
613 my $self = shift;
615 unlink ($self->_clonefail_path()); # Ignore EEXIST error
616 unlink ($self->_clonelog_path()); # Ignore EEXIST error
618 use IO::Socket;
619 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
620 $sock->print("clone ".$self->{name}."\n");
621 # Just ignore reply, we are going to succeed anyway and the I/O
622 # would apparently get quite hairy.
623 $sock->flush();
624 sleep 2; # *cough*
625 $sock->close();
628 sub update {
629 my $self = shift;
631 $self->_properties_save;
632 $self->_group_update;
634 if (exists($self->{tags_to_delete})) {
635 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
638 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
640 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
641 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
642 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
643 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
645 $self->_update_index if $self->{email} ne $self->{orig_email};
646 $self->{orig_email} = $self->{email};
651 sub update_password {
652 my $self = shift;
653 my ($pwd) = @_;
655 $self->{crypt} = scrypt_sha1($pwd);
656 $self->_group_update;
659 # You can explicitly do this just on a ghost() repository too.
660 sub delete {
661 my $self = shift;
663 if (-d $self->{path}) {
664 system('rm', '-rf', $self->{path}) == 0
665 or die "rm -rf $self->{path} failed: $?";
667 # attempt to clean up any empty fork directories by removing them
668 my @pelems = split('/', $self->{name});
669 while (@pelems > 1) {
670 pop @pelems;
671 # okay to fail
672 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
674 $self->_group_remove;
675 $self->_update_index;
678 sub _contains_files {
679 my $dir = shift;
680 (-d $dir) or return 0;
681 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
682 while (my $entry = readdir($dh)) {
683 next if $entry eq '' || $entry eq '.' || $entry eq '..';
684 closedir($dh), return 1
685 if -f "$dir/$entry" ||
686 -d "$dir/$entry" && _contains_files("$dir/$entry");
688 closedir($dh);
689 return 0;
692 sub has_forks {
693 my $self = shift;
695 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
698 sub is_empty {
699 # A project is considered empty if the git repository does not
700 # have any refs. This means packed-refs does not exist or is
701 # empty or only has lines starting with '#' AND there are no
702 # files in the refs subdirectory hierarchy (no matter how deep).
704 my $self = shift;
706 (-d $self->{path}) or return 0;
707 if (-e $self->{path}.'/packed-refs') {
708 open(my $pr, '<', $self->{path}.'/packed-refs')
709 or die "open $self->{path}./packed-refs failed: $!";
710 my $foundref = 0;
711 while (my $ref = <$pr>) {
712 next if $ref =~ /^#/;
713 $foundref = 1;
714 last;
716 close($pr);
717 return 0 if $foundref;
719 (-d $self->{path}.'/refs') or return 1;
720 return !_contains_files($self->{path}.'/refs');
723 sub delete_ctag {
724 my $self = shift;
725 my ($ctag) = @_;
727 # sanity check, disallow filenames starting with . .. or /
728 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
731 sub get_ctag_names {
732 my $self = shift;
733 my @ctags = ();
734 opendir(my $dh, $self->{path}.'/ctags')
735 or return @ctags;
736 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
737 closedir($dh);
738 return @ctags;
741 sub get_heads {
742 my $self = shift;
743 my $fh;
744 open($fh, '-|', "$Girocco::Config::git_bin --git-dir=$self->{path} show-ref --heads") or die "could not get list of heads";
745 my @res;
746 while (<$fh>) {
747 chomp;
748 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
749 push @res, $1;
751 close $fh;
752 @res;
755 sub get_HEAD {
756 my $self = shift;
757 my $HEAD = `$Girocco::Config::git_bin --git-dir=$self->{path} symbolic-ref HEAD`;
758 chomp $HEAD;
759 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
760 return $1;
763 sub set_HEAD {
764 my $self = shift;
765 my $newHEAD = shift;
766 # Cursory checks only -- if you want to break your HEAD, be my guest
767 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
768 die "grossly invalid new HEAD: $newHEAD";
770 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
771 die "could not set HEAD" if ($? >> 8);
772 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
773 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
776 sub gen_auth {
777 my $self = shift;
778 my ($type) = @_;
779 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
781 $self->{authtype} = $type;
783 no warnings;
784 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
786 my $expire = time + 24 * 3600;
787 my $propval = "# ${type}AUTH $self->{auth} $expire";
788 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
789 $self->{auth};
792 sub del_auth {
793 my $self = shift;
795 delete $self->{auth};
796 delete $self->{authtype};
797 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
800 sub remove_user {
801 my $self = shift;
802 my ($username) = @_;
804 my $before_count = @{$self->{users}};
805 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
806 return @{$self->{users}} != $before_count;
809 ### static methods
811 sub get_forkee_name {
812 local $_ = $_[0];
813 (m#^(.*)/.*?$#)[0]; #
816 sub get_forkee_path {
817 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
818 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
819 -d $forkee ? $forkee : '';
822 # Ultimately the full project/fork name could end up being part of a Git ref name
823 # when a project's forks are combined into one giant repository for efficiency.
824 # That means that the project/fork name must satisfy the Git ref name requirements:
826 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
827 # 2. The character with an ASCII value of 0x7F is not allowed
828 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
829 # 4. The character '/' is a separator and is not allowed within a name
830 # 5. The name may not start with '.' or end with '.'
831 # 6. The name may not end with '.lock'
832 # 7. The name may not contain the '..' sequence
833 # 8. The name may not contain the '@{' sequence
834 # 9. If multiple components are used (separated by '/'), no empty '' components
836 # We also prohibit a trailing '.git' on any path component and futher restrict
837 # the allowed characters to alphanumeric and [+._-] where names must start with
838 # an alphanumeric.
840 # The rules are relaxed slightly for existing projects (for now) to accomodate them.
842 sub _valid_name_characters {
843 local $_ = $_[0];
844 my $relaxed = $_[1];
845 (not m#^[/+._-]#)
846 and (not m#//#)
847 and (not m#\.\.#)
848 and (not m#/[+._-]# or $relaxed)
849 and (not m#\./#)
850 and (not m#\.$# or $relaxed)
851 and (not m#\.git/#i)
852 and (not m#\.git$#i)
853 and (not m#\.lock/#i)
854 and (not m#\.lock$#i)
855 and (not m#/$#)
856 and m#^[a-zA-Z0-9/+._-]+$#;
859 sub valid_name {
860 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
861 local $_ = $_[0];
862 _valid_name_characters($_) and not exists($reservedprojectnames{$_})
863 and @{[m#/#g]} <= 5 # maximum fork depth is 5
864 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
867 # It's possible that some forks have been kept but the forkee is gone.
868 # In this case the standard valid_name check is too strict.
869 sub does_exist {
870 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
871 my ($name, $nodie) = @_;
872 my $okay = (
873 _valid_name_characters($name, 1)
874 and ((not $name =~ m#/#)
875 or -d get_forkee_path($name)
876 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
877 (!$okay && $nodie) and return undef;
878 !$okay and die "tried to query for project with invalid name $name!";
879 (-d $Girocco::Config::reporoot."/$name.git");
882 sub get_full_list {
883 my $class = shift;
884 my @projects;
886 open F, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
887 while (<F>) {
888 chomp;
889 @_ = split /:+/;
890 next if ($_[2] < 65536);
892 push @projects, $_[0];
894 close F;
895 @projects;