User.pm: add no-pty to each key in ssh keys file
[girocco.git] / Girocco / Project.pm
bloba07189bbcf8dcb44139a14827a54515330cc79a2
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 system("'$Girocco::Config::git_bin' --git-dir='$forkee_path' show-ref > '$self->{path}/packed-refs'");
263 # initialize HEAD, hacky version
264 system("cp $forkee_path/HEAD $self->{path}/HEAD");
265 chmod 0664, "$self->{path}/packed-refs", "$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 my $hooksdir = $self->{path}.'/hooks';
319 -d $hooksdir or mkdir $hooksdir or
320 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
321 open SRC, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
322 open DST, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
323 while (<SRC>) { print DST $_; }
324 close DST;
325 close SRC;
326 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
329 sub _hooks_install {
330 my $self = shift;
331 foreach my $hook ('pre-receive', 'post-receive', 'update', 'post-update') {
332 $self->_hook_install($hook);
336 # private constructor, do not use
337 sub _new {
338 my $class = shift;
339 my ($name, $base_path, $path) = @_;
340 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
341 $path ||= "$base_path/$name.git";
342 my $proj = { name => $name, base_path => $base_path, path => $path };
344 bless $proj, $class;
347 # public constructor #0
348 # creates a virtual project not connected to disk image
349 # you can conjure() it later to disk
350 sub ghost {
351 my $class = shift;
352 my ($name, $mirror) = @_;
353 my $self = $class->_new($name, $Girocco::Config::reporoot);
354 $self->{users} = [];
355 $self->{mirror} = $mirror;
356 $self->{email} = $self->{orig_email} = '';
357 $self;
360 # public constructor #1
361 sub load {
362 my $class = shift;
363 my $name = shift || '';
365 open F, '<', jailed_file("/etc/group") or die "project load failed: $!";
366 while (<F>) {
367 chomp;
368 @_ = split /:+/;
369 next unless (shift eq $name);
371 my $self = $class->_new($name, $Girocco::Config::reporoot);
372 (-d $self->{path}) or die "invalid path (".$self->{path}.") for project ".$self->{name};
374 my $ulist;
375 ($self->{crypt}, $self->{gid}, $ulist) = @_;
376 $ulist ||= '';
377 $self->{users} = [split /,/, $ulist];
378 $self->{HEAD} = $self->get_HEAD;
379 $self->{orig_HEAD} = $self->{HEAD};
380 $self->{orig_users} = [@{$self->{users}}];
381 $self->{mirror} = ! -e $self->_nofetch_path;
382 $self->{clone_in_progress} = -e $self->_clonep_path;
383 $self->{clone_logged} = -e $self->_clonelog_path;
384 $self->{clone_failed} = -e $self->_clonefail_path;
385 $self->{ccrypt} = $self->{crypt};
387 $self->_properties_load;
388 $self->{orig_email} = $self->{email};
389 $self->{loaded} = 1; # indicates self was loaded from etc/group file
390 return $self;
392 close F;
393 undef;
396 # $proj may not be in sane state if this returns false!
397 sub cgi_fill {
398 my $self = shift;
399 my ($gcgi) = @_;
400 my $cgi = $gcgi->cgi;
402 my ($pwd, $pwd2) = ($cgi->param('pwd'), $cgi->param('pwd2'));
403 # in case passwords are disabled
404 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
405 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
406 $gcgi->err("Empty passwords are not permitted.");
408 if ($pwd ne '' or not $self->{crypt}) {
409 $self->{crypt} = scrypt_sha1($pwd);
411 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
412 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
415 $self->{cpwd} = $cgi->param('cpwd');
417 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
418 my $newtype = $forkee ? 'fork' : 'project';
419 length($project) <= 64
420 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
422 if ($Girocco::Config::project_owners eq 'email') {
423 $self->{email} = $gcgi->wparam('email');
424 valid_email($self->{email})
425 or $gcgi->err("Your email sure looks weird...?");
426 length($self->{email}) <= 96
427 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
430 $self->{url} = $gcgi->wparam('url');
431 if ($self->{url}) {
432 valid_repo_url($self->{url})
433 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
434 if ($Girocco::Config::restrict_mirror_hosts) {
435 my $mh = extract_url_hostname($self->{url});
436 is_dns_hostname($mh)
437 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
438 !is_our_hostname($mh)
439 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
443 $self->{desc} = $gcgi->wparam('desc');
444 length($self->{desc}) <= 1024
445 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
447 $self->{README} = $gcgi->wparam('README');
448 length($self->{README}) <= 8192
449 or $gcgi->err("README length &gt; 8kb!");
451 $self->{hp} = $gcgi->wparam('hp');
452 if ($self->{hp}) {
453 valid_web_url($self->{hp})
454 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
457 my %users = ();
458 my @users = ();
459 foreach my $user ($cgi->param('user')) {
460 if (!exists($users{$user})) {
461 $users{$user} = 1;
462 push(@users, $user) if Girocco::User::valid_name($user) && Girocco::User::does_exist($user)
465 $self->{users} = \@users;
467 $self->{HEAD} = $cgi->param('HEAD') if $cgi->param('HEAD');
469 # schedule deletion of tags (will be committed by update() after auth)
470 $self->{tags_to_delete} = [$cgi->param('tags')];
472 $self->{notifymail} = $gcgi->wparam('notifymail');
473 if ($self->{notifymail}) {
474 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
475 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
478 $self->{notifyjson} = $gcgi->wparam('notifyjson');
479 if ($self->{notifyjson}) {
480 valid_web_url($self->{notifyjson})
481 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
484 $self->{notifycia} = $gcgi->wparam('notifycia');
485 if ($self->{notifycia}) {
486 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
487 or $gcgi->err("Overly suspicious CIA notify project name. If it is actually valid, contact me.");
490 if ($cgi->param('setstatusupdates')) {
491 my $val = $gcgi->wparam('statusupdates') || '0';
492 $self->{statusupdates} = $val ? 1 : 0;
495 not $gcgi->err_check;
498 sub form_defaults {
499 my $self = shift;
501 name => $self->{name},
502 email => $self->{email},
503 url => $self->{url},
504 desc => html_esc($self->{desc}),
505 README => html_esc($self->{README}),
506 hp => $self->{hp},
507 users => $self->{users},
508 notifymail => html_esc($self->{notifymail}),
509 notifyjson => html_esc($self->{notifyjson}),
510 notifycia => html_esc($self->{notifycia}),
514 # return true if $enc_passwd is a match for $plain_passwd
515 my $_check_passwd_match = sub {
516 my $enc_passwd = shift;
517 my $plain_passwd = shift;
518 defined($enc_passwd) or $enc_passwd = '';
519 defined($plain_passwd) or $plain_passwd = '';
520 # $enc_passwd may be crypt or crypt_sha1
521 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
522 # It's using sha1-crypt
523 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
524 } else {
525 # It's using crypt
526 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
530 sub authenticate {
531 my $self = shift;
532 my ($gcgi) = @_;
534 $self->{ccrypt} or die "Can't authenticate against a project with no password";
535 defined($self->{cpwd}) or $self->{cpwd} = '';
536 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
537 $gcgi->err("Your admin password does not match!");
538 return 0;
540 return 1;
543 # return true if the password from the file is empty or consists of all the same
544 # character. However, if the project was NOT loaded from the group file
545 # (!self->{loaded}) then the password is never locked.
546 # This function does NOT check $Girocco::Config::project_passwords, the caller
547 # is responsible for doing so if desired. Same for $self->{email}.
548 sub is_password_locked {
549 my $self = shift;
551 $self->{loaded} or return 0;
552 my $testcrypt = $self->{ccrypt}; # The value from the group file
553 defined($testcrypt) or $testcrypt = '';
554 $testcrypt ne '' or return 1; # No password at all
555 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
556 return 0; # Not locked
559 sub _setup {
560 use POSIX qw(strftime);
561 my $self = shift;
562 my ($pushers) = @_;
564 $self->_mkdir_forkees;
566 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
567 if ($Girocco::Config::owning_group) {
568 my $gid = scalar(getgrnam($Girocco::Config::owning_group));
569 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
570 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
571 } else {
572 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
574 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
575 or die "git init $self->{path} failed: $?";
576 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
577 or die "disabling receive.denyNonFastforwards failed: $?";
578 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
579 or die "disabling gc.auto failed: $?";
580 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
581 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
582 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
583 or die "setting girocco.creationtime failed: $?";
584 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writebitmaps', 'true') == 0
585 or die "enabling repack.writebitmaps failed: $?";
587 # /info must have right permissions,
588 # and git init didn't do it for some reason.
589 # config must have correct permissions.
590 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
591 if ($Girocco::Config::owning_group) {
592 chmod(02775, $self->{path}."/info") or die "chmod 02775 $self->{path}/info failed: $!";
593 chmod(0664, $self->{path}."/config") or die "chmod 0664 $self->{path}/config failed: $!";
594 } else {
595 chmod(02777, $self->{path}."/info") or die "chmod 02777 $self->{path}/info failed: $!";
596 chmod(0666, $self->{path}."/config") or die "chmod 0666 $self->{path}/config failed: $!";
599 $self->_properties_save;
600 $self->_alternates_setup;
601 $self->_ctags_setup;
602 $self->_group_remove;
603 $self->_group_add($pushers);
604 $self->_hooks_install;
605 #$self->perm_initialize;
606 $self->_update_index;
609 sub premirror {
610 my $self = shift;
612 $self->_setup(':');
613 $self->_clonep(1);
614 $self->perm_initialize;
617 sub conjure {
618 my $self = shift;
620 $self->_setup;
621 $self->_nofetch(1);
622 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
623 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
624 or die "create-personal-mob-area $self->{name} failed";
626 $self->perm_initialize;
629 sub clone {
630 my $self = shift;
632 unlink ($self->_clonefail_path()); # Ignore EEXIST error
633 unlink ($self->_clonelog_path()); # Ignore EEXIST error
635 use IO::Socket;
636 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
637 $sock->print("clone ".$self->{name}."\n");
638 # Just ignore reply, we are going to succeed anyway and the I/O
639 # would apparently get quite hairy.
640 $sock->flush();
641 sleep 2; # *cough*
642 $sock->close();
645 sub update {
646 my $self = shift;
648 $self->_properties_save;
649 $self->_group_update;
651 if (exists($self->{tags_to_delete})) {
652 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
655 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
657 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
658 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
659 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
660 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
662 $self->_update_index if $self->{email} ne $self->{orig_email};
663 $self->{orig_email} = $self->{email};
668 sub update_password {
669 my $self = shift;
670 my ($pwd) = @_;
672 $self->{crypt} = scrypt_sha1($pwd);
673 $self->_group_update;
676 # You can explicitly do this just on a ghost() repository too.
677 sub delete {
678 my $self = shift;
680 if (-d $self->{path}) {
681 system('rm', '-rf', $self->{path}) == 0
682 or die "rm -rf $self->{path} failed: $?";
684 # attempt to clean up any empty fork directories by removing them
685 my @pelems = split('/', $self->{name});
686 while (@pelems > 1) {
687 pop @pelems;
688 # okay to fail
689 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
691 $self->_group_remove;
692 $self->_update_index;
695 sub _contains_files {
696 my $dir = shift;
697 (-d $dir) or return 0;
698 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
699 while (my $entry = readdir($dh)) {
700 next if $entry eq '' || $entry eq '.' || $entry eq '..';
701 closedir($dh), return 1
702 if -f "$dir/$entry" ||
703 -d "$dir/$entry" && _contains_files("$dir/$entry");
705 closedir($dh);
706 return 0;
709 sub has_forks {
710 my $self = shift;
712 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
715 sub is_empty {
716 # A project is considered empty if the git repository does not
717 # have any refs. This means packed-refs does not exist or is
718 # empty or only has lines starting with '#' AND there are no
719 # files in the refs subdirectory hierarchy (no matter how deep).
721 my $self = shift;
723 (-d $self->{path}) or return 0;
724 if (-e $self->{path}.'/packed-refs') {
725 open(my $pr, '<', $self->{path}.'/packed-refs')
726 or die "open $self->{path}./packed-refs failed: $!";
727 my $foundref = 0;
728 while (my $ref = <$pr>) {
729 next if $ref =~ /^#/;
730 $foundref = 1;
731 last;
733 close($pr);
734 return 0 if $foundref;
736 (-d $self->{path}.'/refs') or return 1;
737 return !_contains_files($self->{path}.'/refs');
740 sub delete_ctag {
741 my $self = shift;
742 my ($ctag) = @_;
744 # sanity check, disallow filenames starting with . .. or /
745 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
748 sub get_ctag_names {
749 my $self = shift;
750 my @ctags = ();
751 opendir(my $dh, $self->{path}.'/ctags')
752 or return @ctags;
753 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
754 closedir($dh);
755 return @ctags;
758 sub get_heads {
759 my $self = shift;
760 my $fh;
761 open($fh, '-|', "$Girocco::Config::git_bin --git-dir=$self->{path} show-ref --heads") or die "could not get list of heads";
762 my @res;
763 while (<$fh>) {
764 chomp;
765 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
766 push @res, $1;
768 close $fh;
769 @res;
772 sub get_HEAD {
773 my $self = shift;
774 my $HEAD = `$Girocco::Config::git_bin --git-dir=$self->{path} symbolic-ref HEAD`;
775 chomp $HEAD;
776 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
777 return $1;
780 sub set_HEAD {
781 my $self = shift;
782 my $newHEAD = shift;
783 # Cursory checks only -- if you want to break your HEAD, be my guest
784 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
785 die "grossly invalid new HEAD: $newHEAD";
787 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
788 die "could not set HEAD" if ($? >> 8);
789 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
790 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
793 sub gen_auth {
794 my $self = shift;
795 my ($type) = @_;
796 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
798 $self->{authtype} = $type;
800 no warnings;
801 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
803 my $expire = time + 24 * 3600;
804 my $propval = "# ${type}AUTH $self->{auth} $expire";
805 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
806 $self->{auth};
809 sub del_auth {
810 my $self = shift;
812 delete $self->{auth};
813 delete $self->{authtype};
814 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
817 sub remove_user {
818 my $self = shift;
819 my ($username) = @_;
821 my $before_count = @{$self->{users}};
822 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
823 return @{$self->{users}} != $before_count;
826 ### static methods
828 sub get_forkee_name {
829 local $_ = $_[0];
830 (m#^(.*)/.*?$#)[0]; #
833 sub get_forkee_path {
834 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
835 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
836 -d $forkee ? $forkee : '';
839 # Ultimately the full project/fork name could end up being part of a Git ref name
840 # when a project's forks are combined into one giant repository for efficiency.
841 # That means that the project/fork name must satisfy the Git ref name requirements:
843 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
844 # 2. The character with an ASCII value of 0x7F is not allowed
845 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
846 # 4. The character '/' is a separator and is not allowed within a name
847 # 5. The name may not start with '.' or end with '.'
848 # 6. The name may not end with '.lock'
849 # 7. The name may not contain the '..' sequence
850 # 8. The name may not contain the '@{' sequence
851 # 9. If multiple components are used (separated by '/'), no empty '' components
853 # We also prohibit a trailing '.git' on any path component and futher restrict
854 # the allowed characters to alphanumeric and [+._-] where names must start with
855 # an alphanumeric.
857 sub _valid_name_characters {
858 local $_ = $_[0];
859 (not m#^[/+._-]#)
860 and (not m#//#)
861 and (not m#\.\.#)
862 and (not m#/[+._-]#)
863 and (not m#\./#)
864 and (not m#\.$#)
865 and (not m#\.git/#i)
866 and (not m#\.git$#i)
867 and (not m#\.lock/#i)
868 and (not m#\.lock$#i)
869 and (not m#/$#)
870 and m#^[a-zA-Z0-9/+._-]+$#;
873 sub valid_name {
874 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
875 local $_ = $_[0];
876 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
877 and @{[m#/#g]} <= 5 # maximum fork depth is 5
878 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
881 # It's possible that some forks have been kept but the forkee is gone.
882 # In this case the standard valid_name check is too strict.
883 sub does_exist {
884 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
885 my ($name, $nodie) = @_;
886 my $okay = (
887 _valid_name_characters($name)
888 and ((not $name =~ m#/#)
889 or -d get_forkee_path($name)
890 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
891 (!$okay && $nodie) and return undef;
892 !$okay and die "tried to query for project with invalid name $name!";
893 (-d $Girocco::Config::reporoot."/$name.git");
896 sub get_full_list {
897 my $class = shift;
898 my @projects;
900 open F, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
901 while (<F>) {
902 chomp;
903 @_ = split /:+/;
904 next if ($_[2] < 65536);
906 push @projects, $_[0];
908 close F;
909 @projects;