hooks: add pre-auto-gc hook
[girocco/readme.git] / Girocco / Project.pm
blob42afeb29578b3f4c312671ba5323dae4313ebd09
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 $self->_cleanup_readme;
311 delete $self->{configfilehash};
314 sub _set_bangagain {
315 my $self = shift;
316 my $fd;
317 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
318 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
319 if (open($fd, '>', $self->_bangagain_path)) {
320 close $fd;
321 chmod(0664, $self->_bangagain_path);
326 sub _properties_save {
327 my $self = shift;
328 delete $self->{configfilehash};
329 foreach my $prop (keys %propmap) {
330 $self->_property_fput($prop, $self->{$prop}, 1);
332 $self->_set_bangagain;
335 sub _nofetch_path {
336 my $self = shift;
337 $self->_property_path('.nofetch');
340 sub _nofetch {
341 my $self = shift;
342 my ($nofetch) = @_;
343 my $nf = $self->_nofetch_path;
344 if ($nofetch) {
345 open my $x, '>', $nf or die "nofetch failed: $!";
346 close $x;
347 } else {
348 unlink $nf or die "yesfetch failed: $!";
352 sub _banged_path {
353 my $self = shift;
354 $self->_property_path('.banged');
357 sub _bangagain_path {
358 my $self = shift;
359 $self->_property_path('.bangagain');
362 sub _gcp_path {
363 my $self = shift;
364 $self->_property_path('.gc_in_progress');
367 sub _clonelog_path {
368 my $self = shift;
369 $self->_property_path('.clonelog');
372 sub _clonefail_path {
373 my $self = shift;
374 $self->_property_path('.clone_failed');
377 sub _clonep_path {
378 my $self = shift;
379 $self->_property_path('.clone_in_progress');
382 sub _clonep {
383 my $self = shift;
384 my ($nofetch) = @_;
385 my $np = $self->_clonep_path;
386 if ($nofetch) {
387 open my $x, '>', $np or die "clonep failed: $!";
388 close $x;
389 } else {
390 unlink $np or die "clonef failed: $!";
393 sub _alternates_setup {
394 use POSIX qw(:fcntl_h);
395 my $self = shift;
396 return unless $self->{name} =~ m#/#;
397 my $forkee_name = get_forkee_name($self->{name});
398 my $forkee_path = get_forkee_path($self->{name});
399 return unless -d $forkee_path;
400 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
401 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
402 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
403 mkdir $self->{path}.'/objects/pack'; chmod 02775, $self->{path}.'/objects/pack';
405 # If somehow either our objects/pack or the prospective alternate's pack
406 # directory does not exist decline to set up any alternates
407 my $altpath = "$forkee_path/objects";
408 -d $self->{path}.'/objects/pack' && -d $altpath.'/pack' or return
410 # If our objects/pack and the prospective alternate's pack directory
411 # do not share the same device then decline to set up any alternates
412 my ($selfdev) = stat($self->{path}.'/objects/pack');
413 my ($altdev) = stat($altpath.'/pack');
414 defined($selfdev) && defined($altdev) && $selfdev ne "" && $altdev ne "" && $selfdev == $altdev or return;
416 # We set up both alternates and http_alternates since we cannot use
417 # relative path in alternates - that doesn't work recursively.
419 my $filename = $self->{path}.'/objects/info/alternates';
420 open my $x, '>', $filename or die "alternates failed: $!";
421 print $x "$altpath\n";
422 close $x;
423 chmod 0664, $filename or warn "cannot chmod $filename: $!";
425 if ($Girocco::Config::httppullurl) {
426 $filename = $self->{path}.'/objects/info/http-alternates';
427 open my $x, '>', $filename or die "http-alternates failed: $!";
428 my $upfork = $forkee_name;
429 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
430 close $x;
431 chmod 0664, $filename or warn "cannot chmod $filename: $!";
434 # copy lastactivity from the parent project
435 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
436 my $activity = <$x>;
437 close $x;
438 last unless $activity;
439 open $x, '>', $self->{path}.'/info/lastactivity' or last;
440 print $x $activity;
441 close $x;
442 chomp $activity;
443 $self->{'lastactivity'} = $activity;
446 # copy refs from parent project
447 my $dupout;
448 open $dupout, '>&1' or
449 die "could not dup STDOUT_FILENO: $!";
450 my $packedrefsfd = POSIX::open("$self->{path}/packed-refs", O_WRONLY|O_TRUNC|O_CREAT, 0664);
451 defined($packedrefsfd) && $packedrefsfd >= 0 or die "could not open fork's packed-refs file for writing: $!";
452 POSIX::dup2($packedrefsfd, 1) or
453 die "could not dup2 STDOUT_FILENO: $!";
454 POSIX::close($packedrefsfd);
455 my $result = system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
456 my $resultstr = $!;
457 POSIX::dup2(fileno($dupout), 1);
458 close($dupout);
459 $result == 0 or die "could not create fork's packed-refs file data: $resultstr";
460 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
462 # initialize HEAD
463 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
464 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
465 chomp $HEAD;
466 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
467 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
470 sub _set_changed {
471 my $self = shift;
472 my $fd;
473 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
476 sub _set_forkchange {
477 my $self = shift;
478 my $changedtoo = shift;
479 return unless $self->{name} =~ m#/#;
480 my $forkee_path = get_forkee_path($self->{name});
481 return unless -d $forkee_path;
482 # mark forkee as changed
483 my $fd;
484 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
485 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
486 return if -e $forkee_path.'/htmlcache/summary.forkchange';
487 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
490 sub _ctags_setup {
491 my $self = shift;
492 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
493 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
496 sub _group_add {
497 my $self = shift;
498 my ($xtra) = @_;
499 $xtra .= join(',', @{$self->{users}});
500 my $crypt = $self->{crypt};
501 defined($crypt) or $crypt = 'unknown';
502 filedb_atomic_append(jailed_file('/etc/group'),
503 join(':', $self->{name}, $crypt, '\i', $xtra));
506 sub _group_update {
507 my $self = shift;
508 my $xtra = join(',', @{$self->{users}});
509 filedb_atomic_edit(jailed_file('/etc/group'),
510 sub {
511 $_ = $_[0];
512 chomp;
513 if ($self->{name} eq (split /:/)[0]) {
514 # preserve readonly flag
515 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
516 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
517 } else {
518 return "$_\n";
524 sub _group_remove {
525 my $self = shift;
526 filedb_atomic_edit(jailed_file('/etc/group'),
527 sub {
528 $self->{name} ne (split /:/)[0] and return $_;
533 sub _hook_path {
534 my $self = shift;
535 my ($name) = @_;
536 $self->{path}.'/hooks/'.$name;
539 sub _hook_install {
540 my $self = shift;
541 my ($name) = @_;
542 my $hooksdir = $self->{path}.'/hooks';
543 my $oldmask = umask();
544 umask($oldmask & ~0070);
545 -d $hooksdir or mkdir $hooksdir or
546 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
547 umask($oldmask);
548 my $globalhooks = $Girocco::Config::reporoot . "/_global/hooks";
549 -f "$globalhooks/$name" && -r _ or die "cannot find hook $name: $!";
550 ! -e $self->_hook_path($name) || unlink $self->_hook_path($name) && ! -e $self->_hook_path($name) or
551 die "hooks directory contains unremovable pre-existing hook $name: $!";
552 symlink("$globalhooks/$name", $self->_hook_path($name)) or
553 die "cannot create hook $name symlink: $!";
556 sub _hooks_install {
557 my $self = shift;
558 foreach my $hook ('pre-auto-gc', 'pre-receive', 'post-receive', 'update') {
559 $self->_hook_install($hook);
563 # private constructor, do not use
564 sub _new {
565 my $class = shift;
566 my ($name, $base_path, $path, $orphan, $optp) = @_;
567 does_exist($name,1) || valid_name($name, $orphan, $optp) or die "refusing to create project with invalid name ($name)!";
568 $path ||= "$base_path/$name.git";
569 my $proj = { name => $name, base_path => $base_path, path => $path };
571 bless $proj, $class;
574 # public constructor #0
575 # creates a virtual project not connected to disk image
576 # you can conjure() it later to disk
577 sub ghost {
578 my $class = shift;
579 my ($name, $mirror, $orphan, $optp) = @_;
580 my $self = $class->_new($name, $Girocco::Config::reporoot, undef, $orphan, $optp);
581 $self->{users} = [];
582 $self->{mirror} = $mirror;
583 $self->{email} = $self->{orig_email} = '';
584 $self;
587 # public constructor #1
588 sub load {
589 my $class = shift;
590 my $name = shift || '';
592 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
593 my $r = qr/^\Q$name\E:/;
594 foreach (grep /$r/, <$fd>) {
595 chomp;
597 my $self = $class->_new($name, $Girocco::Config::reporoot);
598 (-d $self->{path} && $self->_readlocalconfigfile(1))
599 or die "invalid path (".$self->{path}.") for project ".$self->{name};
601 my $ulist;
602 (undef, $self->{crypt}, $self->{gid}, $ulist) = split /:/;
603 $ulist ||= '';
604 $self->{users} = [split /,/, $ulist];
605 $self->{HEAD} = $self->get_HEAD;
606 $self->{orig_HEAD} = $self->{HEAD};
607 $self->{orig_users} = [@{$self->{users}}];
608 $self->{mirror} = ! -e $self->_nofetch_path;
609 $self->{banged} = -e $self->_banged_path if $self->{mirror};
610 $self->{gc_in_progress} = -e $self->_gcp_path;
611 $self->{clone_in_progress} = -e $self->_clonep_path;
612 $self->{clone_logged} = -e $self->_clonelog_path;
613 $self->{clone_failed} = -e $self->_clonefail_path;
614 $self->{ccrypt} = $self->{crypt};
616 $self->_properties_load;
617 $self->{orig_email} = $self->{email};
618 $self->{loaded} = 1; # indicates self was loaded from etc/group file
619 close $fd;
620 return $self;
622 close $fd;
623 undef;
626 # $proj may not be in sane state if this returns false!
627 # fields listed in %$metadata_fields that are NOT also
628 # in @Girocco::Config::project_fields are totally ignored!
629 sub cgi_fill {
630 my $self = shift;
631 my ($gcgi) = @_;
632 my $cgi = $gcgi->cgi;
633 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
634 my $field_enabled = sub {
635 !exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]})};
637 my $pwd = $cgi->param('pwd');
638 my $pwd2 = $cgi->param('pwd2');
639 # in case passwords are disabled
640 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd2 = '';
641 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
642 $gcgi->err("Empty passwords are not permitted.");
644 if ($pwd ne '' or not $self->{crypt}) {
645 $self->{crypt} = scrypt_sha1($pwd);
647 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
648 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
651 $self->{cpwd} = $cgi->param('cpwd');
653 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
654 my $newtype = $forkee ? 'fork' : 'project';
655 length($project) <= 64
656 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
658 if ($Girocco::Config::project_owners eq 'email') {
659 $self->{email} = $gcgi->wparam('email');
660 valid_email($self->{email})
661 or $gcgi->err("Your email sure looks weird...?");
662 length($self->{email}) <= 96
663 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
666 # No setting the url unless we're either new or an existing mirror!
667 unless ($self->{loaded} && !$self->{mirror}) {
668 $self->{url} = $gcgi->wparam('url') ;
669 if ($field_enabled->('cleanmirror')) {
670 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
673 # Always validate the url if we're an existing mirror
674 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
675 # Always allow the url to be left unchanged without validation when editing
676 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
677 valid_repo_url($self->{url})
678 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
679 if ($Girocco::Config::restrict_mirror_hosts) {
680 my $mh = extract_url_hostname($self->{url});
681 is_dns_hostname($mh)
682 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
683 !is_our_hostname($mh)
684 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
688 if ($field_enabled->('desc')) {
689 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
690 length($self->{desc}) <= 1024
691 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
694 if ($field_enabled->('README')) {
695 $self->{README} = to_utf8($gcgi->wparam('README'), 1);
696 $self->_cleanup_readme;
697 length($self->{README}) <= 8192
698 or $gcgi->err("README length &gt; 8kb!");
699 my ($cnt, $err) = (0);
700 ($cnt, $err) = $self->_lint_readme if $gcgi->ok && $Girocco::Config::xmllint_readme;
701 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
704 if ($field_enabled->('hp')) {
705 $self->{hp} = $gcgi->wparam('hp');
706 if ($self->{hp}) {
707 valid_web_url($self->{hp})
708 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
712 # No mucking about with users unless we're a push project
713 if (($self->{loaded} && !$self->{mirror}) ||
714 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
715 my %users = ();
716 my @users = ();
717 foreach my $user ($cgi->multi_param('user')) {
718 if (!exists($users{$user})) {
719 $users{$user} = 1;
720 push(@users, $user) if Girocco::User::does_exist($user, 1);
723 $self->{users} = \@users;
726 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
727 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
728 my $newhead;
729 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
730 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
731 if ($newhead eq $self->{orig_HEAD} ||
732 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
733 $self->{HEAD} = $newhead;
734 } else {
735 $gcgi->err("Invalid default branch (no such ref)");
739 # schedule deletion of tags (will be committed by update() after auth)
740 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
742 if ($field_enabled->('notifymail')) {
743 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
744 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
745 $self->{notifymail} = $newaddrs;
746 } else {
747 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
749 if ($field_enabled->('reverseorder')) {
750 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
752 if ($field_enabled->('summaryonly')) {
753 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
757 if ($field_enabled->('notifytag')) {
758 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
759 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
760 $self->{notifytag} = $newaddrs;
761 } else {
762 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
766 if ($field_enabled->('notifyjson')) {
767 $self->{notifyjson} = $gcgi->wparam('notifyjson');
768 if ($self->{notifyjson}) {
769 valid_web_url($self->{notifyjson})
770 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
774 if ($field_enabled->('notifycia')) {
775 $self->{notifycia} = $gcgi->wparam('notifycia');
776 if ($self->{notifycia}) {
777 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
778 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
782 if ($cgi->param('setstatusupdates')) {
783 my $val = $gcgi->wparam('statusupdates') || '0';
784 $self->{statusupdates} = $val ? 1 : 0;
787 not $gcgi->err_check;
790 sub form_defaults {
791 my $self = shift;
793 name => $self->{name},
794 email => $self->{email},
795 url => $self->{url},
796 cleanmirror => $self->{cleanmirror},
797 desc => html_esc($self->{desc}),
798 README => html_esc($self->{README}),
799 hp => $self->{hp},
800 users => $self->{users},
801 notifymail => html_esc($self->{notifymail}),
802 reverseorder => $self->{reverseorder},
803 summaryonly => $self->{summaryonly},
804 notifytag => html_esc($self->{notifytag}),
805 notifyjson => html_esc($self->{notifyjson}),
806 notifycia => html_esc($self->{notifycia}),
810 # return true if $enc_passwd is a match for $plain_passwd
811 my $_check_passwd_match = sub {
812 my $enc_passwd = shift;
813 my $plain_passwd = shift;
814 defined($enc_passwd) or $enc_passwd = '';
815 defined($plain_passwd) or $plain_passwd = '';
816 # $enc_passwd may be crypt or crypt_sha1
817 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
818 # It's using sha1-crypt
819 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
820 } else {
821 # It's using crypt
822 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
826 sub authenticate {
827 my $self = shift;
828 my ($gcgi) = @_;
830 $self->{ccrypt} or die "Can't authenticate against a project with no password";
831 defined($self->{cpwd}) or $self->{cpwd} = '';
832 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
833 $gcgi->err("Your admin password does not match!");
834 return 0;
836 return 1;
839 # return true if the password from the file is empty or consists of all the same
840 # character. However, if the project was NOT loaded from the group file
841 # (!self->{loaded}) then the password is never locked.
842 # This function does NOT check $Girocco::Config::project_passwords, the caller
843 # is responsible for doing so if desired. Same for $self->{email}.
844 sub is_password_locked {
845 my $self = shift;
847 $self->{loaded} or return 0;
848 my $testcrypt = $self->{ccrypt}; # The value from the group file
849 defined($testcrypt) or $testcrypt = '';
850 $testcrypt ne '' or return 1; # No password at all
851 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
852 return 0; # Not locked
855 sub _setup {
856 use POSIX qw(strftime);
857 my $self = shift;
858 my ($pushers) = @_;
859 my $fd;
861 defined($self->{path}) && $self->{path} ne "" or die "invalid setup call";
862 $self->_mkdir_forkees unless $self->{adopt};
864 my $gid;
865 $self->{adopt} || mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
866 -d $self->{path} or die "unable to setup nonexistent $self->{path}";
867 if ($Girocco::Config::owning_group) {
868 $gid = scalar(getgrnam($Girocco::Config::owning_group));
869 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
870 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
871 } else {
872 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
874 delete $ENV{GIT_OBJECT_DIRECTORY};
875 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
876 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
877 or die "git init $self->{path} failed: $?";
878 # we don't need these two, remove them (they will normally be created empty) if they exist
879 rmdir $self->{path}."/branches";
880 rmdir $self->{path}."/remotes";
881 -d $self->{path}."/info" or mkdir $self->{path}."/info"
882 or die "info directory does not exist and unable to create it: $!";
883 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
884 or die "hooks directory does not exist and unable to create it: $!";
885 # clean out any kruft that may have come in from the initial template directory
886 foreach my $cleandir (qw(hooks info)) {
887 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
888 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
889 closedir $hooksdir;
892 if ($Girocco::Config::owning_group) {
893 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
895 # hooks never world writable
896 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
897 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.compression', '5') == 0
898 or die "setting core.compression failed: $?";
899 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
900 or die "disabling core.logAllRefUpdates failed: $?";
901 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
902 or die "disabling core.ignoreCase failed: $?";
903 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.hooksPath', $Girocco::Config::reporoot . "/_global/hooks") == 0
904 or die "setting core.hooksPath failed: $?";
905 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'extensions.preciousObjects', 'true') == 0
906 or die "setting extensions.preciousObjects failed: $?";
907 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
908 or die "enabling transfer.fsckObjects failed: $?";
909 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.unpackLimit', '1') == 0
910 or die "setting transfer.unpackLimit failed: $?";
911 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
912 or die "disabling receive.denyNonFastForwards failed: $?";
913 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
914 or die "disabling receive.denyDeleteCurrent failed: $?";
915 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
916 or die "disabling gc.auto failed: $?";
917 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
918 or die "disabling receive.autogc failed: $?";
919 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
920 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
921 or die "enabling receive.updateServerInfo failed: $?";
922 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
923 or die "enabling repack.writeBitmaps failed: $?";
924 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
925 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
926 or die "setting girocco.creationtime failed: $?";
927 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
928 or die "htmlcache directory does not exist and unable to create it: $!";
929 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
930 or die "bundles directory does not exist and unable to create it: $!";
931 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
932 or die "reflogs directory does not exist and unable to create it: $!";
933 foreach my $file (qw(info/lastactivity .delaygc)) {
934 if (open $fd, '>', $self->{path}."/".$file) {
935 close $fd;
936 chmod 0664, $self->{path}."/".$file;
940 # /info must have right permissions,
941 # and git init didn't do it for some reason.
942 # config must have correct permissions.
943 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
944 # also make sure /refs, /objects and /htmlcache are correct too.
945 my ($dmode, $dmodestr, $fmode, $fmodestr);
946 if ($Girocco::Config::owning_group) {
947 ($dmode, $dmodestr) = (02775, '02775');
948 ($fmode, $fmodestr) = (0664, '0664');
949 } else {
950 ($dmode, $dmodestr) = (02777, '02777');
951 ($fmode, $fmodestr) = (0666, '0666');
953 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
954 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
956 foreach my $file (qw(config)) {
957 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
959 # these ones are probably not strictly required but are nice to have
960 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
961 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
962 chmod($dmode, $self->{path}."/$dir");
965 $self->_properties_save;
966 $self->_alternates_setup unless $self->{noalternates} || $self->{adopt};
967 $self->_ctags_setup;
968 $self->_group_remove;
969 $self->_group_add($pushers);
970 $self->_hooks_install;
971 $self->_update_index;
972 $self->_set_changed;
973 $self->_set_forkchange(1);
976 sub premirror {
977 my $self = shift;
979 delete $self->{adopt};
980 $self->_setup(':');
981 $self->_clonep(1);
982 $self->perm_initialize;
985 sub conjure {
986 my $self = shift;
988 delete $self->{adopt};
989 $self->_setup;
990 $self->_nofetch(1);
991 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
992 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
993 or die "create-personal-mob-area $self->{name} failed";
995 $self->perm_initialize;
998 sub clone {
999 my $self = shift;
1001 unlink ($self->_clonefail_path()); # Ignore EEXIST error
1002 unlink ($self->_clonelog_path()); # Ignore EEXIST error
1004 use IO::Socket;
1005 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
1006 select((select($sock),$|=1)[0]);
1007 $sock->print("clone ".$self->{name}."\n");
1008 # Just ignore reply, we are going to succeed anyway and the I/O
1009 # would apparently get quite hairy.
1010 $sock->flush();
1011 sleep 2; # *cough*
1012 $sock->close();
1015 # call this after ghost instead of conjure or premirror+clone to adopt a pre-existing Git dir
1016 # ghost must be called with the proper value of $mirror for the to-be-adopted project
1017 # for mirrors the $proj->{url} needs to be set and for push projects the $proj->{users} array ref
1018 sub adopt {
1019 my $self = shift;
1020 my $name = $self->{name};
1022 # Sanity check first
1023 defined($name) && $name ne "" && !$self->{loaded} or return undef;
1024 does_exist($name, 1) or return undef;
1025 defined($self->{path}) && $self->{path} eq $Girocco::Config::reporoot."/$name.git" or return undef;
1026 defined($self->{base_path}) && $self->{base_path} eq $Girocco::Config::reporoot or return undef;
1027 defined($self->{email}) && defined($self->{orig_email}) && defined($self->{mirror}) && ref($self->{users}) eq 'ARRAY'
1028 or return undef;
1029 !defined(Girocco::Project->load($name)) or return undef;
1030 is_git_dir($self->{path}) or return undef;
1031 my $config = read_config_file_hash($self->{path}."/config");
1032 defined($config) && _boolval($config->{"core.bare"}) or die "refusing to adopt non-bare repository";
1033 defined(read_HEAD_symref($self->{path})) or die "refusing to adopt non-symref HEAD repository";
1035 # Adopt the project by creating a new $chroot/etc/group entry and setting up anything that's missing
1036 $self->_nofetch(!$self->{mirror});
1037 $self->{adopt} = 1;
1038 $self->_setup($self->{mirror} ? ":" : "");
1039 delete $self->{adopt};
1040 if (!$self->{mirror} && $Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1041 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1042 or die "create-personal-mob-area $self->{name} failed";
1044 my $result = $self->perm_initialize;
1045 unlink("$self->{path}/.delaygc") unless $self->is_empty;
1046 # Pick up any pre-existing settings
1047 my $p = Girocco::Project->load($name);
1048 %$self = %$p if defined($p) && $p->{loaded};
1049 $result;
1052 sub _update_users {
1053 my $self = shift;
1055 $self->_group_update;
1056 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
1057 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
1058 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
1059 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
1062 sub update {
1063 my $self = shift;
1065 $self->_properties_save;
1066 $self->_update_users;
1068 if (exists($self->{tags_to_delete})) {
1069 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1072 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1074 $self->_update_index if $self->{email} ne $self->{orig_email};
1075 $self->{orig_email} = $self->{email};
1076 $self->_set_changed;
1081 sub update_password {
1082 my $self = shift;
1083 my ($pwd) = @_;
1085 $self->{crypt} = scrypt_sha1($pwd);
1086 $self->_group_update;
1089 # You can explicitly do this just on a ghost() repository too.
1090 sub delete {
1091 my $self = shift;
1093 if (-d $self->{path}) {
1094 system('rm', '-rf', $self->{path}) == 0
1095 or die "rm -rf $self->{path} failed: $?";
1097 # attempt to clean up any empty fork directories by removing them
1098 my @pelems = split('/', $self->{name});
1099 while (@pelems > 1) {
1100 pop @pelems;
1101 # okay to fail
1102 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1104 $self->_group_remove;
1105 $self->_update_index;
1106 $self->_set_forkchange(1);
1111 # If the project's directory actually exists archive it before deleting it
1112 # Return full path to archived project ("" if none)
1113 sub archive_and_delete {
1114 my $self = shift;
1116 unless (-d $self->{path}) {
1117 $self->delete;
1118 return "";
1121 # archive the project before deletion
1122 use POSIX qw(strftime);
1123 my $destdir = $self->{base_path};
1124 $destdir =~ s,(?<=[^/])/+$,,;
1125 $destdir .= "/_recyclebin/";
1126 $destdir .= $1 if $self->{name} =~ m,^(.*/)[^/]+$,;
1127 my $destbase = $self->{name};
1128 $destbase = $1 if $destbase =~ m,^.*/([^/]+)$,;
1129 my $oldmask = umask();
1130 umask($oldmask & ~0070);
1131 system('mkdir', '-p', $destdir) == 0 && -d $destdir
1132 or die "mkdir -p \"$destdir\" failed: $?";
1133 umask($oldmask);
1134 my $suffix = '';
1135 if (-e "$destdir$destbase.git") {
1136 $suffix = 1;
1137 while (-e "$destdir$destbase~$suffix.git") {
1138 ++$suffix;
1139 last if $suffix >= 10000; # don't get too carried away
1141 $suffix = '~'.$suffix;
1143 not -e "$destdir$destbase$suffix.git"
1144 or die "Unable to compute suitable archive path";
1145 system('mv', $self->{path}, "$destdir$destbase$suffix.git") == 0
1146 or die "mv \"$self->{path}\" \"$destdir$destbase$suffix.git\" failed: $?";
1147 if (!$self->{mirror} && @{$self->{users}}) {
1148 # Remember the user list at recycle time
1149 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1150 'config', 'girocco.recycleusers', join(",", @{$self->{users}}));
1152 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1153 my $recycletime = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1154 # We ought to do something if this fails, but the project has already been moved
1155 # so there's really nothing to be done at this point.
1156 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1157 'config', 'girocco.recycletime', $recycletime);
1159 $self->delete;
1160 return $destdir.$destbase.$suffix.".git";
1163 sub _contains_files {
1164 my $dir = shift;
1165 (-d $dir) or return 0;
1166 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1167 while (my $entry = readdir($dh)) {
1168 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1169 closedir($dh), return 1
1170 if -f "$dir/$entry" ||
1171 -d "$dir/$entry" && _contains_files("$dir/$entry");
1173 closedir($dh);
1174 return 0;
1177 sub has_forks {
1178 my $self = shift;
1180 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1183 # Returns an array of 0 or more array refs, one for each bundle:
1184 # ->[0]: bundle creation time (seconds since epoch)
1185 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1186 # ->[2]: bundle size in bytes
1187 sub bundles {
1188 my $self = shift;
1189 use Time::Local;
1191 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1192 my @blist = ();
1193 if (-d $self->{path}.'/bundles') {{
1194 my $prefix = $self->{name};
1195 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1196 opendir(my $dh, $self->{path}.'/bundles') or last;
1197 while (my $bfile = readdir($dh)) {
1198 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1199 my $ctime = eval {timegm(
1200 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1201 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4)-1900)};
1202 next unless $ctime;
1203 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1204 my $f1 = <$bh>;
1205 my $f2 = <$bh>;
1206 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1207 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1208 close($bh);
1209 next unless $f1 && $f2 && $f1 ne $f2;
1210 chomp $f1;
1211 chomp $f2;
1212 next unless -e $f1 && -e $f2;
1213 my $s1 = -s $f1 || 0;
1214 my $s2 = -s $f2 || 0;
1215 next unless $s1 || $s2;
1216 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1218 closedir($dh);
1220 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1221 my %seen = ();
1222 my @result = ();
1223 foreach my $bndl (@blist) {
1224 next if $seen{$bndl->[1]};
1225 $seen{$bndl->[1]} = 1;
1226 push(@result, $bndl);
1228 $self->{bundles} = \@result;
1229 return @result;
1232 sub has_alternates {
1233 my $self = shift;
1234 return -s $self->{path}.'/objects/info/alternates' ? 1 : 0;
1237 sub has_bundle {
1238 my $self = shift;
1240 return scalar($self->bundles);
1243 # returns true if any of the notify fields are non-empty
1244 sub has_notify {
1245 my $self = shift;
1246 # We do not ckeck notifycia since it's defunct
1247 return $self->{'notifymail'} || $self->{'notifytag'} || $self->{'notifyjson'};
1250 sub is_empty {
1251 # A project is considered empty if the git repository does not
1252 # have any refs. This means packed-refs does not exist or is
1253 # empty or only has lines starting with '#' AND there are no
1254 # files in the refs subdirectory hierarchy (no matter how deep).
1256 my $self = shift;
1258 (-d $self->{path}) or return 0;
1259 if (-e $self->{path}.'/packed-refs') {
1260 open(my $pr, '<', $self->{path}.'/packed-refs')
1261 or die "open $self->{path}./packed-refs failed: $!";
1262 my $foundref = 0;
1263 while (my $ref = <$pr>) {
1264 next if $ref =~ /^#/;
1265 $foundref = 1;
1266 last;
1268 close($pr);
1269 return 0 if $foundref;
1271 (-d $self->{path}.'/refs') or return 1;
1272 return !_contains_files($self->{path}.'/refs');
1275 # returns array:
1276 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1277 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1278 # Both values (if not undef) are seconds since epoch
1279 # Result only considers lastgc and min_gc_interval nothing else
1280 sub next_gc {
1281 my $self = shift;
1282 my $lastgcepoch = parse_any_date($self->{lastgc});
1283 return (undef, undef) unless defined $lastgcepoch;
1284 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1285 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1286 $Girocco::Config::min_mirror_interval));
1289 # returns boolean (0 or 1)
1290 # Attempts to determine whether or not a gc (and corresponding build
1291 # of a .bitmap/.bndl file) will actually take place at the next_gc
1292 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1293 # end up being built depends on whether or not the local object graph
1294 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1295 # is not possible because the object graph will be incomplete,
1296 # but it *is* possible that even though the repository has_alternates,
1297 # it does not actually borrow any objects so a .bitmap/.bndl will build
1298 # in spite of the presence of alternates -- but this is expected to be rare.
1299 # The result is a best guess and false return value is not an absolute
1300 # guarantee that gc will not take place at the next interval, but it probably
1301 # will not if nothing changes in the meantime.
1302 sub needs_gc {
1303 my $self = shift;
1304 my $lgc = parse_any_date($self->{lastgc});
1305 my $lrecv = parse_any_date($self->{lastreceive});
1306 my $lpgc = parse_any_date($self->{lastparentgc});
1307 return 1 unless defined($lgc) && defined($lrecv);
1308 if ($self->has_alternates) {
1309 return 1 unless defined($lpgc);
1310 return 1 unless $lpgc < $lgc;
1312 return 1 unless $lrecv < $lgc;
1313 # We don't try running any "is_dirty" check, so if somehow the
1314 # repository became dirty without updating lastreceive we might
1315 # incorrectly return false instead of true.
1316 return 0;
1319 sub delete_ctag {
1320 my $self = shift;
1321 my ($ctag) = @_;
1323 # sanity check, disallow filenames starting with . .. or /
1324 unlink($self->{path}.'/ctags/'.$ctag)
1325 unless !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1328 # returns new tag count value on success (will always be >= 1) otherwise undef
1329 sub add_ctag {
1330 my $self = shift;
1331 my $ctag = valid_tag(shift);
1332 my $nochanged = shift;
1334 # sanity check, disallow filenames starting with . .. or /
1335 return undef if !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1337 my $val = 0;
1338 my $ct;
1339 if (open $ct, '<', $self->{path}."/ctags/$ctag") {
1340 my $count = <$ct>;
1341 close $ct;
1342 defined $count or $count = '';
1343 chomp $count;
1344 $val = $count =~ /^[1-9]\d*$/ ? $count : 1;
1346 ++$val;
1347 my $oldmask = umask();
1348 umask($oldmask & ~0060);
1349 open $ct, '>', $self->{path}."/ctags/$ctag" and print $ct $val."\n" and close $ct;
1350 $self->_set_changed unless $nochanged;
1351 $self->_set_forkchange unless $nochanged;
1352 umask($oldmask);
1353 return $val;
1356 sub get_ctag_names {
1357 my $self = shift;
1358 my @ctags = ();
1359 opendir(my $dh, $self->{path}.'/ctags')
1360 or return @ctags;
1361 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1362 closedir($dh);
1363 return sort({lc($a) cmp lc($b)} @ctags);
1366 sub get_heads {
1367 my $self = shift;
1368 my $fh;
1369 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1370 defined($heads) or $heads = '';
1371 chomp $heads;
1372 my @res = ();
1373 foreach (split(/\n/, $heads)) {
1374 chomp;
1375 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1376 push @res, $1;
1378 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1379 @res;
1382 sub get_HEAD {
1383 my $self = shift;
1384 my $HEAD = read_HEAD_symref($self->{path});
1385 defined($HEAD) or $HEAD = '';
1386 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
1387 return $1;
1390 sub set_HEAD {
1391 my $self = shift;
1392 my $newHEAD = shift;
1393 # Cursory checks only -- if you want to break your HEAD, be my guest
1394 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
1395 die "grossly invalid new HEAD: $newHEAD";
1397 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1398 die "could not set HEAD" if ($? >> 8);
1399 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1400 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1403 sub gen_auth {
1404 my $self = shift;
1405 my ($type) = @_;
1406 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1408 $self->{authtype} = $type;
1410 no warnings;
1411 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1413 my $expire = time + 24 * 3600;
1414 my $propval = "# ${type}AUTH $self->{auth} $expire";
1415 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1416 $self->{auth};
1419 sub del_auth {
1420 my $self = shift;
1422 delete $self->{auth};
1423 delete $self->{authtype};
1424 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1427 sub remove_user {
1428 my $self = shift;
1429 my ($username) = @_;
1431 my $before_count = @{$self->{users}};
1432 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1433 return @{$self->{users}} != $before_count;
1436 ### static methods
1438 sub get_forkee_name {
1439 local $_ = $_[0];
1440 (m#^(.*)/.*?$#)[0]; #
1443 sub get_forkee_path {
1444 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1445 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1446 -d $forkee ? $forkee : '';
1449 # Ultimately the full project/fork name could end up being part of a Git ref name
1450 # when a project's forks are combined into one giant repository for efficiency.
1451 # That means that the project/fork name must satisfy the Git ref name requirements:
1453 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1454 # 2. The character with an ASCII value of 0x7F is not allowed
1455 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1456 # 4. The character '/' is a separator and is not allowed within a name
1457 # 5. The name may not start with '.' or end with '.'
1458 # 6. The name may not end with '.lock'
1459 # 7. The name may not contain the '..' sequence
1460 # 8. The name may not contain the '@{' sequence
1461 # 9. If multiple components are used (separated by '/'), no empty '' components
1463 # We also prohibit a trailing '.git' on any path component and futher restrict
1464 # the allowed characters to alphanumeric and [+._-] where names must start with
1465 # an alphanumeric.
1467 sub _valid_name_characters {
1468 local $_ = $_[0];
1469 (not m#^[/+._-]#)
1470 and (not m#//#)
1471 and (not m#\.\.#)
1472 and (not m#/[+._-]#)
1473 and (not m#\./#)
1474 and (not m#\.$#)
1475 and (not m#\.git/#i)
1476 and (not m#\.git$#i)
1477 and (not m#\.idx/#i)
1478 and (not m#\.idx$#i)
1479 and (not m#\.lock/#i)
1480 and (not m#\.lock$#i)
1481 and (not m#\.pack/#i)
1482 and (not m#\.pack$#i)
1483 and (not m#\.bundle/#i)
1484 and (not m#\.bundle$#i)
1485 and (not m#/$#)
1486 and (not m/^[a-fA-F0-9]{38}$/)
1487 and m#^[a-zA-Z0-9/+._-]+$#
1488 and !has_reserved_suffix($_, $_[1], $_[2]);
1491 # $_[0] => prospective project name (WITHOUT trailing .git)
1492 # $_[1] => true to allow orphans (i.e. two-or-more-level-deep projects without a parent)
1493 # (the directory in which the orphan will be created must, however, already exist)
1494 # $_[2] => true to allow orphans w/o needed directory if $_[1] also true (like mkdir -p)
1495 sub valid_name {
1496 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1497 local $_ = $_[0];
1498 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1499 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1500 and ((not m#/#) or -d get_forkee_path($_) or ($_[1] and ($_[2] or -d $Girocco::Config::reporoot.'/'.get_forkee_name($_))))
1501 and (! -f $Girocco::Config::reporoot."/$_.git");
1504 # It's possible that some forks have been kept but the forkee is gone.
1505 # In this case the standard valid_name check is too strict.
1506 sub does_exist {
1507 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1508 my ($name, $nodie) = @_;
1509 my $okay = (
1510 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1511 and ((not $name =~ m#/#)
1512 or -d get_forkee_path($name)
1513 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1514 (!$okay && $nodie) and return undef;
1515 !$okay and die "tried to query for project with invalid name $name!";
1516 (-d $Girocco::Config::reporoot."/$name.git");
1519 sub get_full_list {
1520 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1521 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1522 close $fd;
1523 @projects;