hooks: add a post-commit hook
[girocco.git] / Girocco / Project.pm
blobae284e31f4e2126a420f263a4a683e297bacf316
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 cleanmirror => ['Mirror refs', 'cleanmirror', 'placeholder'],
38 homepage => ['Homepage URL', 'hp', 'text'],
39 shortdesc => ['Short description', 'desc', 'text'],
40 README => ['<span style="display:inline-block;vertical-align:top">'.
41 'README (HTML, &lt; 8 KiB)<br />leave blank for automatic</span>',
42 'README', 'textarea', 'Enter only &#x201c;<!-- comments -->&#x201d; '.
43 'to completely suppress any README'],
44 notifymail => ['Commit notify &#x2013; mail to', 'notifymail', 'text',
45 'comma separated address list'],
46 reverseorder => ['Show oldest first', 'reverseorder', 'checkbox',
47 'show new revisions in oldest to newest order (instead of the default newest to oldest older)'.
48 ' in &#x201c;Commit notify&#x201d; email when showing new revisions'],
49 summaryonly => ['Summaries only', 'summaryonly', 'checkbox',
50 'suppress patch/diff output in &#x201c;Commit notify&#x201d; email when showing new revisions'],
51 notifytag => ['Tag notify &#x2013; mail to', 'notifytag', 'text',
52 'comma separated address list &#x2013; if not empty, tag '.
53 'notifications are sent here INSTEAD of to '.
54 '&#x201c;Commit notify &#x2013; mail to&#x201d; address(es)'],
55 notifyjson => ['Commit notify &#x2013; '.
56 '<a title="'.html_esc('single field name is &#x201c;payload&#x201d;', 1).'" href="'.
57 'https://developer.github.com/v3/activity/events/types/#pushevent'.
58 '">POST JSON</a> at', 'notifyjson', 'text'],
59 notifycia => ['Commit notify &#x2013; <a href="http://cia.vc/doc/">CIA project</a> name',
60 'notifycia', 'text', 'CIA is defunct &#x2013; this value is ignored'],
63 sub _mkdir_forkees {
64 my $self = shift;
65 my @pelems = split('/', $self->{name});
66 pop @pelems; # do not create dir for the project itself
67 my $path = $self->{base_path};
68 foreach my $pelem (@pelems) {
69 $path .= "/$pelem";
70 (-d "$path") or mkdir $path or die "mkdir $path: $!";
71 chmod 02775, $path; # ok if fails (dir may already exist and be owned by someone else)
75 # With a leading ':' get from project local config replacing ':' with 'gitweb.'
76 # With a leading '%' get from project local config after removing '%'
77 # With a leading '!' get boolean from project local config after removing '!' (prefixed with 'gitweb.' if no '.')
78 # With a leading [:%!] a trailing ':defval' may be added to select the default value to use if unset
79 # Otherwise it's a project file name to be loaded
80 # %propmapro entries are loaded but never written
81 # %propmapromirror entries are loaded only for mirrors but never written
83 our %propmap = (
84 url => ':baseurl',
85 email => ':owner',
86 desc => 'description',
87 README => 'README.html',
88 hp => ':homepage',
89 notifymail => '%hooks.mailinglist',
90 notifytag => '%hooks.announcelist',
91 notifyjson => '%hooks.jsonurl',
92 notifycia => '%hooks.cianame',
93 cleanmirror => '!girocco.cleanmirror',
94 statusupdates => '!statusupdates:1',
95 reverseorder => '!hooks.reverseorder',
96 summaryonly => '!hooks.summaryonly',
99 our %propmapro = (
100 lastchange => ':lastchange',
101 lastactivity => 'info/lastactivity',
102 lastgc => ':lastgc',
103 lastreceive => ':lastreceive',
104 lastparentgc => ':lastparentgc',
105 lastrefresh => ':lastrefresh',
106 creationtime => '%girocco.creationtime',
107 reposizek => '%girocco.reposizek',
108 origurl => ':baseurl',
111 our %propmapromirror = (
112 bangcount => '%girocco.bang.count',
113 bangfirstfail => '%girocco.bang.firstfail',
114 bangmessagesent => '!girocco.bang.messagesent',
115 showpush => '!showpush',
118 # Projects with any of these names will be disallowed to avoid possible
119 # collisions with cgi script paths or chroot paths
120 # NOTE: names are checked after using lc on them, so all entries MUST be lowercase
121 our %reservedprojectnames = (
122 admin => 1, # /admin/ links
123 alternates => 1, # .git/objects/info/alternates
124 b => 1, # /b/ -> bundle.cgi
125 blog => 1, # /blog/ links
126 c => 1, # /c/ -> cgit
127 'git-receive-pack' => 1, # smart HTTP
128 'git-upload-archive' => 1, # smart HTTP
129 'git-upload-pack' => 1, # smart HTTP
130 h => 1, # /h/ -> html.cgi
131 head => 1, # .git/HEAD
132 'http-alternates' => 1, # .git/objects/info/http-alternates
133 info => 1, # .git/info
134 objects => 1, # .git/objects
135 packs => 1, # .git/objects/info/packs
136 r => 1, # /r/ -> git http
137 refs => 1, # .git/refs
138 w => 1, # /w/ -> gitweb
139 wiki => 1, # /wiki/ links
140 srv => 1, # /srv/git/ -> chroot ssh git repositories
143 sub _update_index {
144 my $self = shift;
145 system("$Girocco::Config::basedir/gitweb/genindex.sh", $self->{name});
148 sub _readlocalconfigfile {
149 my $self = shift;
150 my $undefonerr = shift || 0;
151 delete $self->{configfilehash};
152 my $confighash = read_config_file_hash($self->{path} . "/config");
153 my $result = 1;
154 defined($confighash) || $undefonerr or $result = 0, $confighash = {};
155 return undef unless defined($confighash);
156 $self->{configfilehash} = $confighash;
157 return $result;
160 # @_[0]: argument to convert to boolean result (0 or 1)
161 # @_[1]: value to use if argument is undef (default is 0)
162 # Returns 0 or 1
163 sub _boolval {
164 my ($val, $def) = @_;
165 defined($def) or $def = 0;
166 defined($val) or $val = $def;
167 $val =~ s/\s+//gs;
168 $val = lc($val);
169 return 0 if $val eq '' || $val eq 'false' || $val eq 'off' || $val eq 'no' || $val =~ /^[-+]?0+$/;
170 return 1;
173 sub _property_path {
174 my $self = shift;
175 my ($name) = @_;
176 $self->{path}.'/'.$name;
179 sub _property_fget {
180 my $self = shift;
181 my ($name, $nodef) = @_;
182 my $pname = $propmap{$name};
183 $pname = $propmapro{$name} unless $pname;
184 $pname = $propmapromirror{$name} unless $pname;
185 $pname or die "unknown property: $name";
186 if ($pname =~ /^([:%!])([^:]+)(:.*)?$/) {
187 my ($where, $pname, $defval) = ($1, lc($2), substr(($3||":"),1));
188 $defval = '' if $nodef;
189 $self->_readlocalconfigfile
190 unless ref($self->{configfilehash}) eq 'HASH';
191 $pname = "gitweb." . $pname if $where eq ':' or $where eq '!' && $pname !~ /[.]/;
192 my $val = $self->{configfilehash}->{$pname};
193 defined($val) or $val = $defval;
194 chomp $val;
195 $val = _boolval($val, $defval) if $where eq '!';
196 return $nodef && !exists($self->{configfilehash}->{$pname}) ? undef : $val;
199 open my $p, '<', $self->_property_path($pname) or return undef;
200 my @value = <$p>;
201 close $p;
202 my $value = join('', @value); chomp $value;
203 $value;
206 sub _prop_is_same {
207 my $self = shift;
208 my ($name, $value) = @_;
209 my $existing = $self->_property_fget($name, 1);
210 defined($value) or $value = '';
211 return defined($existing) && $existing eq $value;
214 sub _property_fput {
215 my $self = shift;
216 my ($name, $value, $nosetsame) = @_;
217 my $pname = $propmap{$name};
218 $pname or die "unknown property: $name";
219 my $defval = '';
220 ($pname, $defval) = ($1, substr(($2||":"),1)) if $pname =~ /^([:%!][^:]+)(:.*)?$/;
221 defined($value) or $value = $defval;
222 if ($pname =~ s/^://) {
223 return if $nosetsame && $self->_prop_is_same($name, $value);
224 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
225 return;
226 } elsif ($pname =~ s/^%//) {
227 return if $nosetsame && $self->_prop_is_same($name, $value);
228 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
229 return;
230 } elsif ($pname =~ s/^!//) {
231 $pname = "gitweb." . $pname unless $pname =~ /[.]/;
232 $value = _boolval($value, $defval);
233 return if $nosetsame && $self->_prop_is_same($name, $value);
234 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool', $pname, $value);
235 return;
238 my $P = lock_file($self->_property_path($pname));
239 chomp $value;
240 $value ne '' and print $P "$value\n";
241 close $P;
242 unlock_file($self->_property_path($pname));
245 sub _cleanup_readme {
246 my $self = shift;
247 defined($self->{README}) or $self->{README} = '';
248 $self->{README} =~ s/\r\n?/\n/gs;
249 $self->{README} =~ s/^\s+//s;
250 $self->{README} =~ s/\s+$//s;
251 $self->{README} eq '' or $self->{README} .= "\n";
254 sub _lint_readme {
255 my $self = shift;
256 my $htmlfrag = shift;
257 defined($htmlfrag) or $htmlfrag = 1;
258 return 0 unless defined($self->{README}) && $self->{README} ne '';
259 my $test = '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>';
260 $test .= $self->{README};
261 $test .= '</div></body></html>';
262 my ($code, $errors) = capture_command(2, $test, 'xmllint', '--nonet',
263 '--noout', '--nowarning', '-');
264 return 0 unless $code;
265 my $cnt = 0;
266 my @errs = ();
267 for my $line (split(/\n+/, $errors)) {
268 $line = html_esc($line) if $htmlfrag;
269 $line =~ s/ /\&#160;/gs if $htmlfrag;
270 ++$cnt, $line = 'README'.$1 if $line =~ /^-(:\d+:.*)$/;
271 if ($htmlfrag) {
272 push @errs, '<tt>' . $line . '</tt>';
273 } else {
274 push @errs, $line . "\n";
277 if ($htmlfrag) {
278 return ($cnt, join("<br />\n", @errs));
279 } else {
280 return ($cnt, join("", @errs));
284 sub _properties_load {
285 my $self = shift;
286 foreach my $prop (keys %propmap) {
287 $self->{$prop} = $self->_property_fget($prop);
289 foreach my $prop (keys %propmapro) {
290 $self->{$prop} = $self->_property_fget($prop);
292 if ($self->{mirror}) {
293 foreach my $prop (keys %propmapromirror) {
294 $self->{$prop} = $self->_property_fget($prop);
297 $self->_readlocalconfigfile
298 unless ref($self->{configfilehash}) eq 'HASH';
299 delete $self->{auth};
300 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
301 defined($val) or $val = '';
302 chomp $val;
303 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
304 my $expire = $3;
305 if (time < $expire) {
306 $self->{authtype} = $1;
307 $self->{auth} = $2;
310 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
311 if (defined($self->{configfilehash}->{'girocco.autogchack'})) {
312 $self->{autogchack} = _boolval($self->{configfilehash}->{'girocco.autogchack'});
315 $self->_cleanup_readme;
316 delete $self->{configfilehash};
319 sub _set_bangagain {
320 my $self = shift;
321 my $fd;
322 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
323 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
324 if (open($fd, '>', $self->_bangagain_path)) {
325 close $fd;
326 chmod(0664, $self->_bangagain_path);
331 sub _properties_save {
332 my $self = shift;
333 delete $self->{configfilehash};
334 foreach my $prop (keys %propmap) {
335 $self->_property_fput($prop, $self->{$prop}, 1);
337 $self->_set_bangagain;
340 sub _nofetch_path {
341 my $self = shift;
342 $self->_property_path('.nofetch');
345 sub _nofetch {
346 my $self = shift;
347 my ($nofetch) = @_;
348 my $nf = $self->_nofetch_path;
349 if ($nofetch) {
350 open my $x, '>', $nf or die "nofetch failed: $!";
351 close $x;
352 } else {
353 unlink $nf or die "yesfetch failed: $!";
357 sub _banged_path {
358 my $self = shift;
359 $self->_property_path('.banged');
362 sub _bangagain_path {
363 my $self = shift;
364 $self->_property_path('.bangagain');
367 sub _gcp_path {
368 my $self = shift;
369 $self->_property_path('.gc_in_progress');
372 sub _clonelog_path {
373 my $self = shift;
374 $self->_property_path('.clonelog');
377 sub _clonefail_path {
378 my $self = shift;
379 $self->_property_path('.clone_failed');
382 sub _clonep_path {
383 my $self = shift;
384 $self->_property_path('.clone_in_progress');
387 sub _clonep {
388 my $self = shift;
389 my ($nofetch) = @_;
390 my $np = $self->_clonep_path;
391 if ($nofetch) {
392 open my $x, '>', $np or die "clonep failed: $!";
393 close $x;
394 } else {
395 unlink $np or die "clonef failed: $!";
398 sub _alternates_setup {
399 use POSIX qw(:fcntl_h);
400 my $self = shift;
401 return unless $self->{name} =~ m#/#;
402 my $forkee_name = get_forkee_name($self->{name});
403 my $forkee_path = get_forkee_path($self->{name});
404 return unless -d $forkee_path;
405 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
406 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
407 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
408 mkdir $self->{path}.'/objects/pack'; chmod 02775, $self->{path}.'/objects/pack';
410 # If somehow either our objects/pack or the prospective alternate's pack
411 # directory does not exist decline to set up any alternates
412 my $altpath = "$forkee_path/objects";
413 -d $self->{path}.'/objects/pack' && -d $altpath.'/pack' or return
415 # If our objects/pack and the prospective alternate's pack directory
416 # do not share the same device then decline to set up any alternates
417 my ($selfdev) = stat($self->{path}.'/objects/pack');
418 my ($altdev) = stat($altpath.'/pack');
419 defined($selfdev) && defined($altdev) && $selfdev ne "" && $altdev ne "" && $selfdev == $altdev or return;
421 # We set up both alternates and http_alternates since we cannot use
422 # relative path in alternates - that doesn't work recursively.
424 my $filename = $self->{path}.'/objects/info/alternates';
425 open my $x, '>', $filename or die "alternates failed: $!";
426 print $x "$altpath\n";
427 close $x;
428 chmod 0664, $filename or warn "cannot chmod $filename: $!";
430 if ($Girocco::Config::httppullurl) {
431 $filename = $self->{path}.'/objects/info/http-alternates';
432 open my $x, '>', $filename or die "http-alternates failed: $!";
433 my $upfork = $forkee_name;
434 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
435 close $x;
436 chmod 0664, $filename or warn "cannot chmod $filename: $!";
439 # copy lastactivity from the parent project
440 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
441 my $activity = <$x>;
442 close $x;
443 last unless $activity;
444 open $x, '>', $self->{path}.'/info/lastactivity' or last;
445 print $x $activity;
446 close $x;
447 chomp $activity;
448 $self->{'lastactivity'} = $activity;
451 # copy refs from parent project
452 my $dupout;
453 open $dupout, '>&1' or
454 die "could not dup STDOUT_FILENO: $!";
455 my $packedrefsfd = POSIX::open("$self->{path}/packed-refs", O_WRONLY|O_TRUNC|O_CREAT, 0664);
456 defined($packedrefsfd) && $packedrefsfd >= 0 or die "could not open fork's packed-refs file for writing: $!";
457 POSIX::dup2($packedrefsfd, 1) or
458 die "could not dup2 STDOUT_FILENO: $!";
459 POSIX::close($packedrefsfd);
460 my $result = system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
461 my $resultstr = $!;
462 POSIX::dup2(fileno($dupout), 1);
463 close($dupout);
464 $result == 0 or die "could not create fork's packed-refs file data: $resultstr";
465 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
467 # initialize HEAD
468 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
469 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
470 chomp $HEAD;
471 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
472 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
475 sub _set_changed {
476 my $self = shift;
477 my $fd;
478 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
481 sub _set_forkchange {
482 my $self = shift;
483 my $changedtoo = shift;
484 return unless $self->{name} =~ m#/#;
485 my $forkee_path = get_forkee_path($self->{name});
486 return unless -d $forkee_path;
487 # mark forkee as changed
488 my $fd;
489 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
490 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
491 return if -e $forkee_path.'/htmlcache/summary.forkchange';
492 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
495 sub _ctags_setup {
496 my $self = shift;
497 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
498 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
501 sub _group_add {
502 my $self = shift;
503 my ($xtra) = @_;
504 $xtra .= join(',', @{$self->{users}});
505 my $crypt = $self->{crypt};
506 defined($crypt) or $crypt = 'unknown';
507 filedb_atomic_append(jailed_file('/etc/group'),
508 join(':', $self->{name}, $crypt, '\i', $xtra));
511 sub _group_update {
512 my $self = shift;
513 my $xtra = join(',', @{$self->{users}});
514 filedb_atomic_edit(jailed_file('/etc/group'),
515 sub {
516 $_ = $_[0];
517 chomp;
518 if ($self->{name} eq (split /:/)[0]) {
519 # preserve readonly flag
520 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
521 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
522 } else {
523 return "$_\n";
529 sub _group_remove {
530 my $self = shift;
531 filedb_atomic_edit(jailed_file('/etc/group'),
532 sub {
533 $self->{name} ne (split /:/)[0] and return $_;
538 sub _hook_path {
539 my $self = shift;
540 my ($name) = @_;
541 $self->{path}.'/hooks/'.$name;
544 sub _hook_install {
545 my $self = shift;
546 my ($name) = @_;
547 my $hooksdir = $self->{path}.'/hooks';
548 my $oldmask = umask();
549 umask($oldmask & ~0070);
550 -d $hooksdir or mkdir $hooksdir or
551 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
552 umask($oldmask);
553 my $globalhooks = $Girocco::Config::reporoot . "/_global/hooks";
554 -f "$globalhooks/$name" && -r _ or die "cannot find hook $name: $!";
555 ! -e $self->_hook_path($name) || unlink $self->_hook_path($name) && ! -e $self->_hook_path($name) or
556 die "hooks directory contains unremovable pre-existing hook $name: $!";
557 symlink("$globalhooks/$name", $self->_hook_path($name)) or
558 die "cannot create hook $name symlink: $!";
561 sub _hooks_install {
562 my $self = shift;
563 foreach my $hook ('pre-auto-gc', 'pre-receive', 'post-commit', 'post-receive', 'update') {
564 $self->_hook_install($hook);
568 # private constructor, do not use
569 sub _new {
570 my $class = shift;
571 my ($name, $base_path, $path, $orphan, $optp) = @_;
572 does_exist($name,1) || valid_name($name, $orphan, $optp) or die "refusing to create project with invalid name ($name)!";
573 $path ||= "$base_path/$name.git";
574 my $proj = { name => $name, base_path => $base_path, path => $path };
576 bless $proj, $class;
579 # public constructor #0
580 # creates a virtual project not connected to disk image
581 # you can conjure() it later to disk
582 sub ghost {
583 my $class = shift;
584 my ($name, $mirror, $orphan, $optp) = @_;
585 my $self = $class->_new($name, $Girocco::Config::reporoot, undef, $orphan, $optp);
586 $self->{users} = [];
587 $self->{mirror} = $mirror;
588 $self->{email} = $self->{orig_email} = '';
589 $self;
592 # public constructor #1
593 sub load {
594 my $class = shift;
595 my $name = shift || '';
597 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
598 my $r = qr/^\Q$name\E:/;
599 foreach (grep /$r/, <$fd>) {
600 chomp;
602 my $self = $class->_new($name, $Girocco::Config::reporoot);
603 (-d $self->{path} && $self->_readlocalconfigfile(1))
604 or die "invalid path (".$self->{path}.") for project ".$self->{name};
606 my $ulist;
607 (undef, $self->{crypt}, $self->{gid}, $ulist) = split /:/;
608 $ulist ||= '';
609 $self->{users} = [split /,/, $ulist];
610 $self->{HEAD} = $self->get_HEAD;
611 $self->{orig_HEAD} = $self->{HEAD};
612 $self->{orig_users} = [@{$self->{users}}];
613 $self->{mirror} = ! -e $self->_nofetch_path;
614 $self->{banged} = -e $self->_banged_path if $self->{mirror};
615 $self->{gc_in_progress} = -e $self->_gcp_path;
616 $self->{clone_in_progress} = -e $self->_clonep_path;
617 $self->{clone_logged} = -e $self->_clonelog_path;
618 $self->{clone_failed} = -e $self->_clonefail_path;
619 $self->{ccrypt} = $self->{crypt};
621 $self->_properties_load;
622 $self->{orig_email} = $self->{email};
623 $self->{loaded} = 1; # indicates self was loaded from etc/group file
624 close $fd;
625 return $self;
627 close $fd;
628 undef;
631 # $proj may not be in sane state if this returns false!
632 # fields listed in %$metadata_fields that are NOT also
633 # in @Girocco::Config::project_fields are totally ignored!
634 sub cgi_fill {
635 my $self = shift;
636 my ($gcgi) = @_;
637 my $cgi = $gcgi->cgi;
638 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
639 my $field_enabled = sub {
640 !exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]})};
642 my $pwd = $cgi->param('pwd');
643 my $pwd2 = $cgi->param('pwd2');
644 # in case passwords are disabled
645 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd2 = '';
646 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
647 $gcgi->err("Empty passwords are not permitted.");
649 if ($pwd ne '' or not $self->{crypt}) {
650 $self->{crypt} = scrypt_sha1($pwd);
652 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
653 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
656 $self->{cpwd} = $cgi->param('cpwd');
658 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
659 my $newtype = $forkee ? 'fork' : 'project';
660 length($project) <= 64
661 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
663 if ($Girocco::Config::project_owners eq 'email') {
664 $self->{email} = $gcgi->wparam('email');
665 valid_email($self->{email})
666 or $gcgi->err("Your email sure looks weird...?");
667 length($self->{email}) <= 96
668 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
671 # No setting the url unless we're either new or an existing mirror!
672 unless ($self->{loaded} && !$self->{mirror}) {
673 $self->{url} = $gcgi->wparam('url') ;
674 if ($field_enabled->('cleanmirror')) {
675 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
678 # Always validate the url if we're an existing mirror
679 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
680 # Always allow the url to be left unchanged without validation when editing
681 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
682 valid_repo_url($self->{url})
683 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
684 if ($Girocco::Config::restrict_mirror_hosts) {
685 my $mh = extract_url_hostname($self->{url});
686 is_dns_hostname($mh)
687 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
688 !is_our_hostname($mh)
689 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
693 if ($field_enabled->('desc')) {
694 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
695 length($self->{desc}) <= 1024
696 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
699 if ($field_enabled->('README')) {
700 $self->{README} = to_utf8($gcgi->wparam('README'), 1);
701 $self->_cleanup_readme;
702 length($self->{README}) <= 8192
703 or $gcgi->err("README length &gt; 8kb!");
704 my ($cnt, $err) = (0);
705 ($cnt, $err) = $self->_lint_readme if $gcgi->ok && $Girocco::Config::xmllint_readme;
706 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
709 if ($field_enabled->('hp')) {
710 $self->{hp} = $gcgi->wparam('hp');
711 if ($self->{hp}) {
712 valid_web_url($self->{hp})
713 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
717 # No mucking about with users unless we're a push project
718 if (($self->{loaded} && !$self->{mirror}) ||
719 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
720 my %users = ();
721 my @users = ();
722 foreach my $user ($cgi->multi_param('user')) {
723 if (!exists($users{$user})) {
724 $users{$user} = 1;
725 push(@users, $user) if Girocco::User::does_exist($user, 1);
728 $self->{users} = \@users;
731 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
732 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
733 my $newhead;
734 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
735 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
736 if ($newhead eq $self->{orig_HEAD} ||
737 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
738 $self->{HEAD} = $newhead;
739 } else {
740 $gcgi->err("Invalid default branch (no such ref)");
744 # schedule deletion of tags (will be committed by update() after auth)
745 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
747 if ($field_enabled->('notifymail')) {
748 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
749 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
750 $self->{notifymail} = $newaddrs;
751 } else {
752 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
754 if ($field_enabled->('reverseorder')) {
755 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
757 if ($field_enabled->('summaryonly')) {
758 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
762 if ($field_enabled->('notifytag')) {
763 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
764 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
765 $self->{notifytag} = $newaddrs;
766 } else {
767 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
771 if ($field_enabled->('notifyjson')) {
772 $self->{notifyjson} = $gcgi->wparam('notifyjson');
773 if ($self->{notifyjson}) {
774 valid_web_url($self->{notifyjson})
775 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
779 if ($field_enabled->('notifycia')) {
780 $self->{notifycia} = $gcgi->wparam('notifycia');
781 if ($self->{notifycia}) {
782 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
783 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
787 if ($cgi->param('setstatusupdates')) {
788 my $val = $gcgi->wparam('statusupdates') || '0';
789 $self->{statusupdates} = $val ? 1 : 0;
792 not $gcgi->err_check;
795 sub form_defaults {
796 my $self = shift;
798 name => $self->{name},
799 email => $self->{email},
800 url => $self->{url},
801 cleanmirror => $self->{cleanmirror},
802 desc => html_esc($self->{desc}),
803 README => html_esc($self->{README}),
804 hp => $self->{hp},
805 users => $self->{users},
806 notifymail => html_esc($self->{notifymail}),
807 reverseorder => $self->{reverseorder},
808 summaryonly => $self->{summaryonly},
809 notifytag => html_esc($self->{notifytag}),
810 notifyjson => html_esc($self->{notifyjson}),
811 notifycia => html_esc($self->{notifycia}),
815 # return true if $enc_passwd is a match for $plain_passwd
816 my $_check_passwd_match = sub {
817 my $enc_passwd = shift;
818 my $plain_passwd = shift;
819 defined($enc_passwd) or $enc_passwd = '';
820 defined($plain_passwd) or $plain_passwd = '';
821 # $enc_passwd may be crypt or crypt_sha1
822 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
823 # It's using sha1-crypt
824 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
825 } else {
826 # It's using crypt
827 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
831 sub authenticate {
832 my $self = shift;
833 my ($gcgi) = @_;
835 $self->{ccrypt} or die "Can't authenticate against a project with no password";
836 defined($self->{cpwd}) or $self->{cpwd} = '';
837 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
838 $gcgi->err("Your admin password does not match!");
839 return 0;
841 return 1;
844 # return true if the password from the file is empty or consists of all the same
845 # character. However, if the project was NOT loaded from the group file
846 # (!self->{loaded}) then the password is never locked.
847 # This function does NOT check $Girocco::Config::project_passwords, the caller
848 # is responsible for doing so if desired. Same for $self->{email}.
849 sub is_password_locked {
850 my $self = shift;
852 $self->{loaded} or return 0;
853 my $testcrypt = $self->{ccrypt}; # The value from the group file
854 defined($testcrypt) or $testcrypt = '';
855 $testcrypt ne '' or return 1; # No password at all
856 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
857 return 0; # Not locked
860 sub _setup {
861 use POSIX qw(strftime);
862 my $self = shift;
863 my ($pushers) = @_;
864 my $fd;
866 defined($self->{path}) && $self->{path} ne "" or die "invalid setup call";
867 $self->_mkdir_forkees unless $self->{adopt};
869 my $gid;
870 $self->{adopt} || mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
871 -d $self->{path} or die "unable to setup nonexistent $self->{path}";
872 if ($Girocco::Config::owning_group) {
873 $gid = scalar(getgrnam($Girocco::Config::owning_group));
874 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
875 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
876 } else {
877 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
879 delete $ENV{GIT_OBJECT_DIRECTORY};
880 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
881 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
882 or die "git init $self->{path} failed: $?";
883 # we don't need these two, remove them (they will normally be created empty) if they exist
884 rmdir $self->{path}."/branches";
885 rmdir $self->{path}."/remotes";
886 -d $self->{path}."/info" or mkdir $self->{path}."/info"
887 or die "info directory does not exist and unable to create it: $!";
888 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
889 or die "hooks directory does not exist and unable to create it: $!";
890 # clean out any kruft that may have come in from the initial template directory
891 foreach my $cleandir (qw(hooks info)) {
892 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
893 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
894 closedir $hooksdir;
897 if ($Girocco::Config::owning_group) {
898 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
900 # hooks never world writable
901 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
902 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.compression', '5') == 0
903 or die "setting core.compression failed: $?";
904 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
905 or die "disabling core.logAllRefUpdates failed: $?";
906 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
907 or die "disabling core.ignoreCase failed: $?";
908 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.hooksPath',
909 ($Girocco::Config::localhooks ? $self->{path}."/hooks" : $Girocco::Config::reporoot . "/_global/hooks")) == 0
910 or die "setting core.hooksPath failed: $?";
911 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'extensions.preciousObjects', 'true') == 0
912 or die "setting extensions.preciousObjects failed: $?";
913 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
914 or die "enabling transfer.fsckObjects failed: $?";
915 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.unpackLimit', '1') == 0
916 or die "setting transfer.unpackLimit failed: $?";
917 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
918 or die "disabling receive.denyNonFastForwards failed: $?";
919 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
920 or die "disabling receive.denyDeleteCurrent failed: $?";
921 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
922 or die "disabling gc.auto failed: $?";
923 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
924 or die "disabling receive.autogc failed: $?";
925 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
926 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
927 or die "enabling receive.updateServerInfo failed: $?";
928 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
929 or die "enabling repack.writeBitmaps failed: $?";
930 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
931 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
932 or die "setting girocco.creationtime failed: $?";
933 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
934 or die "htmlcache directory does not exist and unable to create it: $!";
935 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
936 or die "bundles directory does not exist and unable to create it: $!";
937 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
938 or die "reflogs directory does not exist and unable to create it: $!";
939 foreach my $file (qw(info/lastactivity .delaygc)) {
940 if (open $fd, '>', $self->{path}."/".$file) {
941 close $fd;
942 chmod 0664, $self->{path}."/".$file;
946 # /info must have right permissions,
947 # and git init didn't do it for some reason.
948 # config must have correct permissions.
949 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
950 # also make sure /refs, /objects and /htmlcache are correct too.
951 my ($dmode, $dmodestr, $fmode, $fmodestr);
952 if ($Girocco::Config::owning_group) {
953 ($dmode, $dmodestr) = (02775, '02775');
954 ($fmode, $fmodestr) = (0664, '0664');
955 } else {
956 ($dmode, $dmodestr) = (02777, '02777');
957 ($fmode, $fmodestr) = (0666, '0666');
959 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
960 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
962 foreach my $file (qw(config)) {
963 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
965 # these ones are probably not strictly required but are nice to have
966 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
967 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
968 chmod($dmode, $self->{path}."/$dir");
970 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::htmlcache_owning_group) {
971 my $htmlgid = scalar(getgrnam($Girocco::Config::htmlcache_owning_group));
972 if (defined($htmlgid) && $htmlgid ne $gid) {
973 chown(-1, $htmlgid, $self->{path}."/htmlcache") or die "chgrp $htmlgid $self->{path}/htmlcache failed: $!";
974 chmod($dmode, $self->{path}."/htmlcache") or die "chmod $dmodestr $self->{path}/htmlcache failed: $!";
977 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::ctags_owning_group) {
978 my $ctagsgid = scalar(getgrnam($Girocco::Config::ctags_owning_group));
979 if (defined($ctagsgid) && $ctagsgid ne $gid) {
980 chown(-1, $ctagsgid, $self->{path}."/ctags") or die "chgrp $ctagsgid $self->{path}/ctags failed: $!";
981 chmod($dmode, $self->{path}."/ctags") or die "chmod $dmodestr $self->{path}/ctags failed: $!";
985 $self->_properties_save;
986 $self->_alternates_setup unless $self->{noalternates} || $self->{adopt};
987 $self->_ctags_setup;
988 $self->_group_remove;
989 $self->_group_add($pushers);
990 $self->_hooks_install;
991 $self->_update_index;
992 $self->_set_changed;
993 $self->_set_forkchange(1);
996 sub premirror {
997 my $self = shift;
999 delete $self->{adopt};
1000 $self->_setup(':');
1001 $self->_clonep(1);
1002 if ($Girocco::Config::autogchack) {
1003 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1004 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1006 $self->perm_initialize;
1009 sub conjure {
1010 my $self = shift;
1012 delete $self->{adopt};
1013 $self->_setup;
1014 $self->_nofetch(1);
1015 if ($Girocco::Config::autogchack && $Girocco::Config::autogchack ne "mirror") {
1016 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1017 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1019 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1020 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1021 or die "create-personal-mob-area $self->{name} failed";
1023 $self->perm_initialize;
1026 sub clone {
1027 my $self = shift;
1029 unlink ($self->_clonefail_path()); # Ignore EEXIST error
1030 unlink ($self->_clonelog_path()); # Ignore EEXIST error
1032 use IO::Socket;
1033 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
1034 select((select($sock),$|=1)[0]);
1035 $sock->print("clone ".$self->{name}."\n");
1036 # Just ignore reply, we are going to succeed anyway and the I/O
1037 # would apparently get quite hairy.
1038 $sock->flush();
1039 sleep 2; # *cough*
1040 $sock->close();
1043 # call this after ghost instead of conjure or premirror+clone to adopt a pre-existing Git dir
1044 # ghost must be called with the proper value of $mirror for the to-be-adopted project
1045 # for mirrors the $proj->{url} needs to be set and for push projects the $proj->{users} array ref
1046 sub adopt {
1047 my $self = shift;
1048 my $name = $self->{name};
1050 # Sanity check first
1051 defined($name) && $name ne "" && !$self->{loaded} or return undef;
1052 does_exist($name, 1) or return undef;
1053 defined($self->{path}) && $self->{path} eq $Girocco::Config::reporoot."/$name.git" or return undef;
1054 defined($self->{base_path}) && $self->{base_path} eq $Girocco::Config::reporoot or return undef;
1055 defined($self->{email}) && defined($self->{orig_email}) && defined($self->{mirror}) && ref($self->{users}) eq 'ARRAY'
1056 or return undef;
1057 !defined(Girocco::Project->load($name)) or return undef;
1058 is_git_dir($self->{path}) or return undef;
1059 my $config = read_config_file_hash($self->{path}."/config");
1060 defined($config) && _boolval($config->{"core.bare"}) or die "refusing to adopt non-bare repository";
1061 defined(read_HEAD_symref($self->{path})) or die "refusing to adopt non-symref HEAD repository";
1063 # Adopt the project by creating a new $chroot/etc/group entry and setting up anything that's missing
1064 $self->_nofetch(!$self->{mirror});
1065 $self->{adopt} = 1;
1066 $self->_setup($self->{mirror} ? ":" : "");
1067 delete $self->{adopt};
1068 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
1069 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1070 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1072 if (!$self->{mirror} && $Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1073 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1074 or die "create-personal-mob-area $self->{name} failed";
1076 my $result = $self->perm_initialize;
1077 unlink("$self->{path}/.delaygc") unless $self->is_empty;
1078 # Pick up any pre-existing settings
1079 my $p = Girocco::Project->load($name);
1080 %$self = %$p if defined($p) && $p->{loaded};
1081 $result;
1084 sub _update_users {
1085 my $self = shift;
1087 $self->_group_update;
1088 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
1089 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
1090 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
1091 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
1094 sub update {
1095 my $self = shift;
1097 $self->_properties_save;
1098 $self->_update_users;
1100 if (exists($self->{tags_to_delete})) {
1101 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1104 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1106 $self->_update_index if $self->{email} ne $self->{orig_email};
1107 $self->{orig_email} = $self->{email};
1108 $self->_set_changed;
1113 sub update_password {
1114 my $self = shift;
1115 my ($pwd) = @_;
1117 $self->{crypt} = scrypt_sha1($pwd);
1118 $self->_group_update;
1121 # You can explicitly do this just on a ghost() repository too.
1122 sub delete {
1123 my $self = shift;
1125 if (-d $self->{path}) {
1126 system('rm', '-rf', $self->{path}) == 0
1127 or die "rm -rf $self->{path} failed: $?";
1129 # attempt to clean up any empty fork directories by removing them
1130 my @pelems = split('/', $self->{name});
1131 while (@pelems > 1) {
1132 pop @pelems;
1133 # okay to fail
1134 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1136 $self->_group_remove;
1137 $self->_update_index;
1138 $self->_set_forkchange(1);
1143 # If the project's directory actually exists archive it before deleting it
1144 # Return full path to archived project ("" if none)
1145 sub archive_and_delete {
1146 my $self = shift;
1148 unless (-d $self->{path}) {
1149 $self->delete;
1150 return "";
1153 # archive the project before deletion
1154 use POSIX qw(strftime);
1155 my $destdir = $self->{base_path};
1156 $destdir =~ s,(?<=[^/])/+$,,;
1157 $destdir .= "/_recyclebin/";
1158 $destdir .= $1 if $self->{name} =~ m,^(.*/)[^/]+$,;
1159 my $destbase = $self->{name};
1160 $destbase = $1 if $destbase =~ m,^.*/([^/]+)$,;
1161 my $oldmask = umask();
1162 umask($oldmask & ~0070);
1163 system('mkdir', '-p', $destdir) == 0 && -d $destdir
1164 or die "mkdir -p \"$destdir\" failed: $?";
1165 umask($oldmask);
1166 my $suffix = '';
1167 if (-e "$destdir$destbase.git") {
1168 $suffix = 1;
1169 while (-e "$destdir$destbase~$suffix.git") {
1170 ++$suffix;
1171 last if $suffix >= 10000; # don't get too carried away
1173 $suffix = '~'.$suffix;
1175 not -e "$destdir$destbase$suffix.git"
1176 or die "Unable to compute suitable archive path";
1177 system('mv', $self->{path}, "$destdir$destbase$suffix.git") == 0
1178 or die "mv \"$self->{path}\" \"$destdir$destbase$suffix.git\" failed: $?";
1179 if (!$self->{mirror} && @{$self->{users}}) {
1180 # Remember the user list at recycle time
1181 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1182 'config', 'girocco.recycleusers', join(",", @{$self->{users}}));
1184 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1185 my $recycletime = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1186 # We ought to do something if this fails, but the project has already been moved
1187 # so there's really nothing to be done at this point.
1188 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1189 'config', 'girocco.recycletime', $recycletime);
1191 $self->delete;
1192 return $destdir.$destbase.$suffix.".git";
1195 sub _contains_files {
1196 my $dir = shift;
1197 (-d $dir) or return 0;
1198 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1199 while (my $entry = readdir($dh)) {
1200 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1201 closedir($dh), return 1
1202 if -f "$dir/$entry" ||
1203 -d "$dir/$entry" && _contains_files("$dir/$entry");
1205 closedir($dh);
1206 return 0;
1209 sub has_forks {
1210 my $self = shift;
1212 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1215 # Returns an array of 0 or more array refs, one for each bundle:
1216 # ->[0]: bundle creation time (seconds since epoch)
1217 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1218 # ->[2]: bundle size in bytes
1219 sub bundles {
1220 my $self = shift;
1221 use Time::Local;
1223 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1224 my @blist = ();
1225 if (-d $self->{path}.'/bundles') {{
1226 my $prefix = $self->{name};
1227 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1228 opendir(my $dh, $self->{path}.'/bundles') or last;
1229 while (my $bfile = readdir($dh)) {
1230 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1231 my $ctime = eval {timegm(
1232 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1233 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4)-1900)};
1234 next unless $ctime;
1235 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1236 my $f1 = <$bh>;
1237 my $f2 = <$bh>;
1238 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1239 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1240 close($bh);
1241 next unless $f1 && $f2 && $f1 ne $f2;
1242 chomp $f1;
1243 chomp $f2;
1244 next unless -e $f1 && -e $f2;
1245 my $s1 = -s $f1 || 0;
1246 my $s2 = -s $f2 || 0;
1247 next unless $s1 || $s2;
1248 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1250 closedir($dh);
1252 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1253 my %seen = ();
1254 my @result = ();
1255 foreach my $bndl (@blist) {
1256 next if $seen{$bndl->[1]};
1257 $seen{$bndl->[1]} = 1;
1258 push(@result, $bndl);
1260 $self->{bundles} = \@result;
1261 return @result;
1264 sub has_alternates {
1265 my $self = shift;
1266 return -s $self->{path}.'/objects/info/alternates' ? 1 : 0;
1269 sub has_bundle {
1270 my $self = shift;
1272 return scalar($self->bundles);
1275 # returns true if any of the notify fields are non-empty
1276 sub has_notify {
1277 my $self = shift;
1278 # We do not ckeck notifycia since it's defunct
1279 return $self->{'notifymail'} || $self->{'notifytag'} || $self->{'notifyjson'};
1282 sub is_empty {
1283 # A project is considered empty if the git repository does not
1284 # have any refs. This means packed-refs does not exist or is
1285 # empty or only has lines starting with '#' AND there are no
1286 # files in the refs subdirectory hierarchy (no matter how deep).
1288 my $self = shift;
1290 (-d $self->{path}) or return 0;
1291 if (-e $self->{path}.'/packed-refs') {
1292 open(my $pr, '<', $self->{path}.'/packed-refs')
1293 or die "open $self->{path}./packed-refs failed: $!";
1294 my $foundref = 0;
1295 while (my $ref = <$pr>) {
1296 next if $ref =~ /^#/;
1297 $foundref = 1;
1298 last;
1300 close($pr);
1301 return 0 if $foundref;
1303 (-d $self->{path}.'/refs') or return 1;
1304 return !_contains_files($self->{path}.'/refs');
1307 # returns array:
1308 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1309 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1310 # Both values (if not undef) are seconds since epoch
1311 # Result only considers lastgc and min_gc_interval nothing else
1312 sub next_gc {
1313 my $self = shift;
1314 my $lastgcepoch = parse_any_date($self->{lastgc});
1315 return (undef, undef) unless defined $lastgcepoch;
1316 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1317 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1318 $Girocco::Config::min_mirror_interval));
1321 # returns boolean (0 or 1)
1322 # Attempts to determine whether or not a gc (and corresponding build
1323 # of a .bitmap/.bndl file) will actually take place at the next_gc
1324 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1325 # end up being built depends on whether or not the local object graph
1326 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1327 # is not possible because the object graph will be incomplete,
1328 # but it *is* possible that even though the repository has_alternates,
1329 # it does not actually borrow any objects so a .bitmap/.bndl will build
1330 # in spite of the presence of alternates -- but this is expected to be rare.
1331 # The result is a best guess and false return value is not an absolute
1332 # guarantee that gc will not take place at the next interval, but it probably
1333 # will not if nothing changes in the meantime.
1334 sub needs_gc {
1335 my $self = shift;
1336 my $lgc = parse_any_date($self->{lastgc});
1337 my $lrecv = parse_any_date($self->{lastreceive});
1338 my $lpgc = parse_any_date($self->{lastparentgc});
1339 return 1 unless defined($lgc) && defined($lrecv);
1340 if ($self->has_alternates) {
1341 return 1 unless defined($lpgc);
1342 return 1 unless $lpgc < $lgc;
1344 return 1 unless $lrecv < $lgc;
1345 # We don't try running any "is_dirty" check, so if somehow the
1346 # repository became dirty without updating lastreceive we might
1347 # incorrectly return false instead of true.
1348 return 0;
1351 sub delete_ctag {
1352 my $self = shift;
1353 my ($ctag) = @_;
1355 # sanity check, disallow filenames starting with . .. or /
1356 unlink($self->{path}.'/ctags/'.$ctag)
1357 unless !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1360 # returns new tag count value on success (will always be >= 1) otherwise undef
1361 sub add_ctag {
1362 my $self = shift;
1363 my $ctag = valid_tag(shift);
1364 my $nochanged = shift;
1366 # sanity check, disallow filenames starting with . .. or /
1367 return undef if !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1369 my $val = 0;
1370 my $ct;
1371 if (open $ct, '<', $self->{path}."/ctags/$ctag") {
1372 my $count = <$ct>;
1373 close $ct;
1374 defined $count or $count = '';
1375 chomp $count;
1376 $val = $count =~ /^[1-9]\d*$/ ? $count : 1;
1378 ++$val;
1379 my $oldmask = umask();
1380 umask($oldmask & ~0060);
1381 open $ct, '>', $self->{path}."/ctags/$ctag" and print $ct $val."\n" and close $ct;
1382 $self->_set_changed unless $nochanged;
1383 $self->_set_forkchange unless $nochanged;
1384 umask($oldmask);
1385 return $val;
1388 sub get_ctag_names {
1389 my $self = shift;
1390 my @ctags = ();
1391 opendir(my $dh, $self->{path}.'/ctags')
1392 or return @ctags;
1393 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1394 closedir($dh);
1395 return sort({lc($a) cmp lc($b)} @ctags);
1398 sub get_heads {
1399 my $self = shift;
1400 my $fh;
1401 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1402 defined($heads) or $heads = '';
1403 chomp $heads;
1404 my @res = ();
1405 foreach (split(/\n/, $heads)) {
1406 chomp;
1407 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1408 push @res, $1;
1410 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1411 @res;
1414 sub get_HEAD {
1415 my $self = shift;
1416 my $HEAD = read_HEAD_symref($self->{path});
1417 defined($HEAD) or $HEAD = '';
1418 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
1419 return $1;
1422 sub set_HEAD {
1423 my $self = shift;
1424 my $newHEAD = shift;
1425 # Cursory checks only -- if you want to break your HEAD, be my guest
1426 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
1427 die "grossly invalid new HEAD: $newHEAD";
1429 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1430 die "could not set HEAD" if ($? >> 8);
1431 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1432 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1435 sub gen_auth {
1436 my $self = shift;
1437 my ($type) = @_;
1438 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1440 $self->{authtype} = $type;
1442 no warnings;
1443 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1445 my $expire = time + 24 * 3600;
1446 my $propval = "# ${type}AUTH $self->{auth} $expire";
1447 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1448 $self->{auth};
1451 sub del_auth {
1452 my $self = shift;
1454 delete $self->{auth};
1455 delete $self->{authtype};
1456 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1459 sub remove_user {
1460 my $self = shift;
1461 my ($username) = @_;
1463 my $before_count = @{$self->{users}};
1464 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1465 return @{$self->{users}} != $before_count;
1468 ### static methods
1470 sub get_forkee_name {
1471 local $_ = $_[0];
1472 (m#^(.*)/.*?$#)[0]; #
1475 sub get_forkee_path {
1476 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1477 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1478 -d $forkee ? $forkee : '';
1481 # Ultimately the full project/fork name could end up being part of a Git ref name
1482 # when a project's forks are combined into one giant repository for efficiency.
1483 # That means that the project/fork name must satisfy the Git ref name requirements:
1485 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1486 # 2. The character with an ASCII value of 0x7F is not allowed
1487 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1488 # 4. The character '/' is a separator and is not allowed within a name
1489 # 5. The name may not start with '.' or end with '.'
1490 # 6. The name may not end with '.lock'
1491 # 7. The name may not contain the '..' sequence
1492 # 8. The name may not contain the '@{' sequence
1493 # 9. If multiple components are used (separated by '/'), no empty '' components
1495 # We also prohibit a trailing '.git' on any path component and futher restrict
1496 # the allowed characters to alphanumeric and [+._-] where names must start with
1497 # an alphanumeric.
1499 sub _valid_name_characters {
1500 local $_ = $_[0];
1501 (not m#^[/+._-]#)
1502 and (not m#//#)
1503 and (not m#\.\.#)
1504 and (not m#/[+._-]#)
1505 and (not m#\./#)
1506 and (not m#\.$#)
1507 and (not m#\.git/#i)
1508 and (not m#\.git$#i)
1509 and (not m#\.idx/#i)
1510 and (not m#\.idx$#i)
1511 and (not m#\.lock/#i)
1512 and (not m#\.lock$#i)
1513 and (not m#\.pack/#i)
1514 and (not m#\.pack$#i)
1515 and (not m#\.bundle/#i)
1516 and (not m#\.bundle$#i)
1517 and (not m#/$#)
1518 and (not m/^[a-fA-F0-9]{38}$/)
1519 and m#^[a-zA-Z0-9/+._-]+$#
1520 and !has_reserved_suffix($_, $_[1], $_[2]);
1523 # $_[0] => prospective project name (WITHOUT trailing .git)
1524 # $_[1] => true to allow orphans (i.e. two-or-more-level-deep projects without a parent)
1525 # (the directory in which the orphan will be created must, however, already exist)
1526 # $_[2] => true to allow orphans w/o needed directory if $_[1] also true (like mkdir -p)
1527 sub valid_name {
1528 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1529 local $_ = $_[0];
1530 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1531 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1532 and ((not m#/#) or -d get_forkee_path($_) or ($_[1] and ($_[2] or -d $Girocco::Config::reporoot.'/'.get_forkee_name($_))))
1533 and (! -f $Girocco::Config::reporoot."/$_.git");
1536 # It's possible that some forks have been kept but the forkee is gone.
1537 # In this case the standard valid_name check is too strict.
1538 sub does_exist {
1539 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1540 my ($name, $nodie) = @_;
1541 my $okay = (
1542 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1543 and ((not $name =~ m#/#)
1544 or -d get_forkee_path($name)
1545 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1546 (!$okay && $nodie) and return undef;
1547 !$okay and die "tried to query for project with invalid name $name!";
1548 (-d $Girocco::Config::reporoot."/$name.git");
1551 sub get_full_list {
1552 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1553 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1554 close $fd;
1555 @projects;