Project.pm: new is_password_locked function
[girocco.git] / Girocco / Project.pm
blobc38d130aeda486846536098b7a7159b46262c40b
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 $self->{loaded} = 1; # indicates self was loaded from etc/group file
372 return $self;
374 close F;
375 undef;
378 # $proj may not be in sane state if this returns false!
379 sub cgi_fill {
380 my $self = shift;
381 my ($gcgi) = @_;
382 my $cgi = $gcgi->cgi;
384 my ($pwd, $pwd2) = ($cgi->param('pwd'), $cgi->param('pwd2'));
385 # in case passwords are disabled
386 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
387 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
388 $gcgi->err("Empty passwords are not permitted.");
390 if ($pwd ne '' or not $self->{crypt}) {
391 $self->{crypt} = scrypt_sha1($pwd);
393 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
394 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
397 $self->{cpwd} = $cgi->param('cpwd');
399 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
400 my $newtype = $forkee ? 'fork' : 'project';
401 length($project) <= 64
402 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
404 if ($Girocco::Config::project_owners eq 'email') {
405 $self->{email} = $gcgi->wparam('email');
406 valid_email($self->{email})
407 or $gcgi->err("Your email sure looks weird...?");
408 length($self->{email}) <= 96
409 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
412 $self->{url} = $gcgi->wparam('url');
413 if ($self->{url}) {
414 valid_repo_url($self->{url})
415 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocol is supported. If the URL contains funny characters, contact me.");
416 if ($Girocco::Config::restrict_mirror_hosts) {
417 my $mh = extract_url_hostname($self->{url});
418 is_dns_hostname($mh)
419 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
420 !is_our_hostname($mh)
421 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
425 $self->{desc} = $gcgi->wparam('desc');
426 length($self->{desc}) <= 1024
427 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
429 $self->{README} = $gcgi->wparam('README');
430 length($self->{README}) <= 8192
431 or $gcgi->err("README length &gt; 8kb!");
433 $self->{hp} = $gcgi->wparam('hp');
434 if ($self->{hp}) {
435 valid_web_url($self->{hp})
436 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
439 $self->{users} = [grep { Girocco::User::valid_name($_) && Girocco::User::does_exist($_) } $cgi->param('user')];
441 $self->{HEAD} = $cgi->param('HEAD') if $cgi->param('HEAD');
443 # schedule deletion of tags (will be committed by update() after auth)
444 $self->{tags_to_delete} = [$cgi->param('tags')];
446 $self->{notifymail} = $gcgi->wparam('notifymail');
447 if ($self->{notifymail}) {
448 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
449 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
452 $self->{notifyjson} = $gcgi->wparam('notifyjson');
453 if ($self->{notifyjson}) {
454 valid_web_url($self->{notifyjson})
455 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
458 $self->{notifycia} = $gcgi->wparam('notifycia');
459 if ($self->{notifycia}) {
460 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
461 or $gcgi->err("Overly suspicious CIA notify project name. If it is actually valid, contact me.");
464 if ($cgi->param('setstatusupdates')) {
465 my $val = $gcgi->wparam('statusupdates') || '0';
466 $self->{statusupdates} = $val ? 1 : 0;
469 not $gcgi->err_check;
472 sub form_defaults {
473 my $self = shift;
475 name => $self->{name},
476 email => $self->{email},
477 url => $self->{url},
478 desc => html_esc($self->{desc}),
479 README => html_esc($self->{README}),
480 hp => $self->{hp},
481 users => $self->{users},
482 notifymail => html_esc($self->{notifymail}),
483 notifyjson => html_esc($self->{notifyjson}),
484 notifycia => html_esc($self->{notifycia}),
488 # return true if $enc_passwd is a match for $plain_passwd
489 my $_check_passwd_match = sub {
490 my $enc_passwd = shift;
491 my $plain_passwd = shift;
492 defined($enc_passwd) or $enc_passwd = '';
493 defined($plain_passwd) or $plain_passwd = '';
494 # $enc_passwd may be crypt or crypt_sha1
495 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
496 # It's using sha1-crypt
497 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
498 } else {
499 # It's using crypt
500 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
504 sub authenticate {
505 my $self = shift;
506 my ($gcgi) = @_;
508 $self->{ccrypt} or die "Can't authenticate against a project with no password";
509 defined($self->{cpwd}) or $self->{cpwd} = '';
510 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
511 $gcgi->err("Your admin password does not match!");
512 return 0;
514 return 1;
517 # return true if the password from the file is empty or consists of all the same
518 # character. However, if the project was NOT loaded from the group file
519 # (!self->{loaded}) then the password is never locked.
520 # This function does NOT check $Girocco::Config::project_passwords, the caller
521 # is responsible for doing so if desired. Same for $self->{email}.
522 sub is_password_locked {
523 my $self = shift;
525 $self->{loaded} or return 0;
526 my $testcrypt = $self->{ccrypt}; # The value from the group file
527 defined($testcrypt) or $testcrypt = '';
528 $testcrypt ne '' or return 1; # No password at all
529 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
530 return 0; # Not locked
533 sub _setup {
534 my $self = shift;
535 my ($pushers) = @_;
537 $self->_mkdir_forkees;
539 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
540 if ($Girocco::Config::owning_group) {
541 my $gid = scalar(getgrnam($Girocco::Config::owning_group));
542 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
543 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
544 } else {
545 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
547 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--bare', '--shared='.$self->shared_mode()) == 0
548 or die "git init $self->{path} failed: $?";
549 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
550 or die "disabling receive.denyNonFastforwards failed: $?";
551 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
552 or die "disabling gc.auto failed: $?";
554 # /info must have right permissions,
555 # and git init didn't do it for some reason.
556 if ($Girocco::Config::owning_group) {
557 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
558 } else {
559 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
562 $self->_properties_save;
563 $self->_alternates_setup;
564 $self->_ctags_setup;
565 $self->_group_remove;
566 $self->_group_add($pushers);
567 $self->_hooks_install;
568 #$self->perm_initialize;
569 $self->_update_index;
572 sub premirror {
573 my $self = shift;
575 $self->_setup(':');
576 $self->_clonep(1);
577 $self->perm_initialize;
580 sub conjure {
581 my $self = shift;
583 $self->_setup;
584 $self->_nofetch(1);
585 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
586 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
587 or die "create-personal-mob-area $self->{name} failed";
589 $self->perm_initialize;
592 sub clone {
593 my $self = shift;
595 unlink ($self->_clonefail_path()); # Ignore EEXIST error
596 unlink ($self->_clonelog_path()); # Ignore EEXIST error
598 use IO::Socket;
599 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
600 $sock->print("clone ".$self->{name}."\n");
601 # Just ignore reply, we are going to succeed anyway and the I/O
602 # would apparently get quite hairy.
603 $sock->flush();
604 sleep 2; # *cough*
605 $sock->close();
608 sub update {
609 my $self = shift;
611 $self->_properties_save;
612 $self->_group_update;
614 if (exists($self->{tags_to_delete})) {
615 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
618 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
620 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
621 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
622 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
623 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
625 $self->_update_index if $self->{email} ne $self->{orig_email};
626 $self->{orig_email} = $self->{email};
631 sub update_password {
632 my $self = shift;
633 my ($pwd) = @_;
635 $self->{crypt} = scrypt_sha1($pwd);
636 $self->_group_update;
639 # You can explicitly do this just on a ghost() repository too.
640 sub delete {
641 my $self = shift;
643 if (-d $self->{path}) {
644 system('rm', '-rf', $self->{path}) == 0
645 or die "rm -rf $self->{path} failed: $?";
647 # attempt to clean up any empty fork directories by removing them
648 my @pelems = split('/', $self->{name});
649 while (@pelems > 1) {
650 pop @pelems;
651 # okay to fail
652 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
654 $self->_group_remove;
655 $self->_update_index;
658 sub _contains_files {
659 my $dir = shift;
660 (-d $dir) or return 0;
661 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
662 while (my $entry = readdir($dh)) {
663 next if $entry eq '' || $entry eq '.' || $entry eq '..';
664 closedir($dh), return 1
665 if -f "$dir/$entry" ||
666 -d "$dir/$entry" && _contains_files("$dir/$entry");
668 closedir($dh);
669 return 0;
672 sub has_forks {
673 my $self = shift;
675 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
678 sub is_empty {
679 # A project is considered empty if the git repository does not
680 # have any refs. This means packed-refs does not exist or is
681 # empty or only has lines starting with '#' AND there are no
682 # files in the refs subdirectory hierarchy (no matter how deep).
684 my $self = shift;
686 (-d $self->{path}) or return 0;
687 if (-e $self->{path}.'/packed-refs') {
688 open(my $pr, '<', $self->{path}.'/packed-refs')
689 or die "open $self->{path}./packed-refs failed: $!";
690 my $foundref = 0;
691 while (my $ref = <$pr>) {
692 next if $ref =~ /^#/;
693 $foundref = 1;
694 last;
696 close($pr);
697 return 0 if $foundref;
699 (-d $self->{path}.'/refs') or return 1;
700 return !_contains_files($self->{path}.'/refs');
703 sub delete_ctag {
704 my $self = shift;
705 my ($ctag) = @_;
707 # sanity check, disallow filenames starting with . .. or /
708 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
711 sub get_ctag_names {
712 my $self = shift;
713 my @ctags = ();
714 opendir(my $dh, $self->{path}.'/ctags')
715 or return @ctags;
716 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
717 closedir($dh);
718 return @ctags;
721 sub get_heads {
722 my $self = shift;
723 my $fh;
724 open($fh, '-|', "$Girocco::Config::git_bin --git-dir=$self->{path} show-ref --heads") or die "could not get list of heads";
725 my @res;
726 while (<$fh>) {
727 chomp;
728 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
729 push @res, $1;
731 close $fh;
732 @res;
735 sub get_HEAD {
736 my $self = shift;
737 my $HEAD = `$Girocco::Config::git_bin --git-dir=$self->{path} symbolic-ref HEAD`;
738 chomp $HEAD;
739 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
740 return $1;
743 sub set_HEAD {
744 my $self = shift;
745 my $newHEAD = shift;
746 # Cursory checks only -- if you want to break your HEAD, be my guest
747 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
748 die "grossly invalid new HEAD: $newHEAD";
750 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
751 die "could not set HEAD" if ($? >> 8);
752 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
753 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
756 sub gen_auth {
757 my $self = shift;
758 my ($type) = @_;
759 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
761 $self->{authtype} = $type;
763 no warnings;
764 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
766 my $expire = time + 24 * 3600;
767 my $propval = "# ${type}AUTH $self->{auth} $expire";
768 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
769 $self->{auth};
772 sub del_auth {
773 my $self = shift;
775 delete $self->{auth};
776 delete $self->{authtype};
777 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
780 sub remove_user {
781 my $self = shift;
782 my ($username) = @_;
784 my $before_count = @{$self->{users}};
785 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
786 return @{$self->{users}} != $before_count;
789 ### static methods
791 sub get_forkee_name {
792 local $_ = $_[0];
793 (m#^(.*)/.*?$#)[0]; #
796 sub get_forkee_path {
797 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
798 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
799 -d $forkee ? $forkee : '';
802 # Ultimately the full project/fork name could end up being part of a Git ref name
803 # when a project's forks are combined into one giant repository for efficiency.
804 # That means that the project/fork name must satisfy the Git ref name requirements:
806 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
807 # 2. The character with an ASCII value of 0x7F is not allowed
808 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
809 # 4. The character '/' is a separator and is not allowed within a name
810 # 5. The name may not start with '.' or end with '.'
811 # 6. The name may not end with '.lock'
812 # 7. The name may not contain the '..' sequence
813 # 8. The name may not contain the '@{' sequence
814 # 9. If multiple components are used (separated by '/'), no empty '' components
816 # We also prohibit a trailing '.git' on any path component and futher restrict
817 # the allowed characters to alphanumeric and [+._-] where names must start with
818 # an alphanumeric.
820 # The rules are relaxed slightly for existing projects (for now) to accomodate them.
822 sub _valid_name_characters {
823 local $_ = $_[0];
824 my $relaxed = $_[1];
825 (not m#^[/+._-]#)
826 and (not m#//#)
827 and (not m#\.\.#)
828 and (not m#/[+._-]# or $relaxed)
829 and (not m#\./#)
830 and (not m#\.$# or $relaxed)
831 and (not m#\.git/#i)
832 and (not m#\.git$#i)
833 and (not m#\.lock/#i)
834 and (not m#\.lock$#i)
835 and (not m#/$#)
836 and m#^[a-zA-Z0-9/+._-]+$#;
839 sub valid_name {
840 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
841 local $_ = $_[0];
842 _valid_name_characters($_) and not exists($reservedprojectnames{$_})
843 and @{[m#/#g]} <= 5 # maximum fork depth is 5
844 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
847 # It's possible that some forks have been kept but the forkee is gone.
848 # In this case the standard valid_name check is too strict.
849 sub does_exist {
850 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
851 my ($name, $nodie) = @_;
852 my $okay = (
853 _valid_name_characters($name, 1)
854 and ((not $name =~ m#/#)
855 or -d get_forkee_path($name)
856 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
857 (!$okay && $nodie) and return undef;
858 !$okay and die "tried to query for project with invalid name $name!";
859 (-d $Girocco::Config::reporoot."/$name.git");
862 sub get_full_list {
863 my $class = shift;
864 my @projects;
866 open F, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
867 while (<F>) {
868 chomp;
869 @_ = split /:+/;
870 next if ($_[2] < 65536);
872 push @projects, $_[0];
874 close F;
875 @projects;