post-commit: always touch htmlcache/changed
[girocco/mitgedanken.git] / Girocco / Project.pm
blob157b88912fd5758f374062f9094cd960a36e6dc8
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 notifyhook => '%girocco.notifyhook:undef',
109 origurl => ':baseurl',
112 our %propmapromirror = (
113 bangcount => '%girocco.bang.count',
114 bangfirstfail => '%girocco.bang.firstfail',
115 bangmessagesent => '!girocco.bang.messagesent',
116 showpush => '!showpush',
119 # Projects with any of these names will be disallowed to avoid possible
120 # collisions with cgi script paths or chroot paths
121 # NOTE: names are checked after using lc on them, so all entries MUST be lowercase
122 our %reservedprojectnames = (
123 admin => 1, # /admin/ links
124 alternates => 1, # .git/objects/info/alternates
125 b => 1, # /b/ -> bundle.cgi
126 blog => 1, # /blog/ links
127 c => 1, # /c/ -> cgit
128 'git-receive-pack' => 1, # smart HTTP
129 'git-upload-archive' => 1, # smart HTTP
130 'git-upload-pack' => 1, # smart HTTP
131 h => 1, # /h/ -> html.cgi
132 head => 1, # .git/HEAD
133 'http-alternates' => 1, # .git/objects/info/http-alternates
134 info => 1, # .git/info
135 objects => 1, # .git/objects
136 packs => 1, # .git/objects/info/packs
137 r => 1, # /r/ -> git http
138 refs => 1, # .git/refs
139 w => 1, # /w/ -> gitweb
140 wiki => 1, # /wiki/ links
141 srv => 1, # /srv/git/ -> chroot ssh git repositories
144 sub _update_index {
145 my $self = shift;
146 system("$Girocco::Config::basedir/gitweb/genindex.sh", $self->{name});
149 sub _readlocalconfigfile {
150 my $self = shift;
151 my $undefonerr = shift || 0;
152 delete $self->{configfilehash};
153 my $confighash = read_config_file_hash($self->{path} . "/config");
154 my $result = 1;
155 defined($confighash) || $undefonerr or $result = 0, $confighash = {};
156 return undef unless defined($confighash);
157 $self->{configfilehash} = $confighash;
158 return $result;
161 # @_[0]: argument to convert to boolean result (0 or 1)
162 # @_[1]: value to use if argument is undef (default is 0)
163 # Returns 0 or 1
164 sub _boolval {
165 my ($val, $def) = @_;
166 defined($def) or $def = 0;
167 defined($val) or $val = $def;
168 $val =~ s/\s+//gs;
169 $val = lc($val);
170 return 0 if $val eq '' || $val eq 'false' || $val eq 'off' || $val eq 'no' || $val =~ /^[-+]?0+$/;
171 return 1;
174 sub _property_path {
175 my $self = shift;
176 my ($name) = @_;
177 $self->{path}.'/'.$name;
180 sub _property_fget {
181 my $self = shift;
182 my ($name, $nodef) = @_;
183 my $pname = $propmap{$name};
184 $pname = $propmapro{$name} unless $pname;
185 $pname = $propmapromirror{$name} unless $pname;
186 $pname or die "unknown property: $name";
187 if ($pname =~ /^([:%!])([^:]+)(:.*)?$/) {
188 my ($where, $pname, $defval) = ($1, lc($2), substr(($3||":"),1));
189 $defval = undef if $defval eq "undef";
190 $defval = '' if $nodef;
191 $self->_readlocalconfigfile
192 unless ref($self->{configfilehash}) eq 'HASH';
193 $pname = "gitweb." . $pname if $where eq ':' or $where eq '!' && $pname !~ /[.]/;
194 my $val = $self->{configfilehash}->{$pname};
195 defined($val) or $val = $defval;
196 chomp $val if defined($val);
197 $val = _boolval($val, $defval) if $where eq '!';
198 return $nodef && !exists($self->{configfilehash}->{$pname}) ? undef : $val;
201 open my $p, '<', $self->_property_path($pname) or return undef;
202 my @value = <$p>;
203 close $p;
204 my $value = join('', @value); chomp $value;
205 $value;
208 sub _prop_is_same {
209 my $self = shift;
210 my ($name, $value) = @_;
211 my $existing = $self->_property_fget($name, 1);
212 defined($value) or $value = '';
213 return defined($existing) && $existing eq $value;
216 sub _property_fput {
217 my $self = shift;
218 my ($name, $value, $nosetsame) = @_;
219 my $pname = $propmap{$name};
220 $pname or die "unknown property: $name";
221 my $defval = '';
222 ($pname, $defval) = ($1, substr(($2||":"),1)) if $pname =~ /^([:%!][^:]+)(:.*)?$/;
223 defined($value) or $value = $defval;
224 if ($pname =~ s/^://) {
225 return if $nosetsame && $self->_prop_is_same($name, $value);
226 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
227 return;
228 } elsif ($pname =~ s/^%//) {
229 return if $nosetsame && $self->_prop_is_same($name, $value);
230 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
231 return;
232 } elsif ($pname =~ s/^!//) {
233 $pname = "gitweb." . $pname unless $pname =~ /[.]/;
234 $value = _boolval($value, $defval);
235 return if $nosetsame && $self->_prop_is_same($name, $value);
236 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool', $pname, $value);
237 return;
240 my $P = lock_file($self->_property_path($pname));
241 chomp $value;
242 $value ne '' and print $P "$value\n";
243 close $P;
244 unlock_file($self->_property_path($pname));
247 sub _cleanup_readme {
248 my $self = shift;
249 defined($self->{README}) or $self->{README} = '';
250 $self->{README} =~ s/\r\n?/\n/gs;
251 $self->{README} =~ s/^\s+//s;
252 $self->{README} =~ s/\s+$//s;
253 $self->{README} eq '' or $self->{README} .= "\n";
256 sub _lint_readme {
257 my $self = shift;
258 my $htmlfrag = shift;
259 defined($htmlfrag) or $htmlfrag = 1;
260 return 0 unless defined($self->{README}) && $self->{README} ne '';
261 my $test = '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>';
262 $test .= $self->{README};
263 $test .= '</div></body></html>';
264 my ($code, $errors) = capture_command(2, $test, 'xmllint', '--nonet',
265 '--noout', '--nowarning', '-');
266 return 0 unless $code;
267 my $cnt = 0;
268 my @errs = ();
269 for my $line (split(/\n+/, $errors)) {
270 $line = html_esc($line) if $htmlfrag;
271 $line =~ s/ /\&#160;/gs if $htmlfrag;
272 ++$cnt, $line = 'README'.$1 if $line =~ /^-(:\d+:.*)$/;
273 if ($htmlfrag) {
274 push @errs, '<tt>' . $line . '</tt>';
275 } else {
276 push @errs, $line . "\n";
279 if ($htmlfrag) {
280 return ($cnt, join("<br />\n", @errs));
281 } else {
282 return ($cnt, join("", @errs));
286 sub _properties_load {
287 my $self = shift;
288 my $setprop = sub {
289 my $propval = $self->_property_fget($_);
290 defined($propval) and $self->{$_} = $propval;
292 &$setprop foreach keys %propmap;
293 &$setprop foreach keys %propmapro;
294 do {&$setprop foreach keys %propmapromirror} if $self->{mirror};
295 $self->_readlocalconfigfile
296 unless ref($self->{configfilehash}) eq 'HASH';
297 delete $self->{auth};
298 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
299 defined($val) or $val = '';
300 chomp $val;
301 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
302 my $expire = $3;
303 if (time < $expire) {
304 $self->{authtype} = $1;
305 $self->{auth} = $2;
308 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
309 if (defined($self->{configfilehash}->{'girocco.autogchack'})) {
310 $self->{autogchack} = _boolval($self->{configfilehash}->{'girocco.autogchack'});
313 $self->_cleanup_readme;
314 delete $self->{configfilehash};
317 sub _set_bangagain {
318 my $self = shift;
319 my $fd;
320 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
321 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
322 if (open($fd, '>', $self->_bangagain_path)) {
323 close $fd;
324 chmod(0664, $self->_bangagain_path);
329 sub _properties_save {
330 my $self = shift;
331 delete $self->{configfilehash};
332 foreach my $prop (keys %propmap) {
333 $self->_property_fput($prop, $self->{$prop}, 1);
335 $self->_set_bangagain;
338 sub _nofetch_path {
339 my $self = shift;
340 $self->_property_path('.nofetch');
343 sub _nofetch {
344 my $self = shift;
345 my ($nofetch) = @_;
346 my $nf = $self->_nofetch_path;
347 if ($nofetch) {
348 open my $x, '>', $nf or die "nofetch failed: $!";
349 close $x;
350 } else {
351 ! -e $nf or unlink $nf or die "yesfetch failed: $!";
355 sub _banged_path {
356 my $self = shift;
357 $self->_property_path('.banged');
360 sub _bangagain_path {
361 my $self = shift;
362 $self->_property_path('.bangagain');
365 sub _gcp_path {
366 my $self = shift;
367 $self->_property_path('.gc_in_progress');
370 sub _clonelog_path {
371 my $self = shift;
372 $self->_property_path('.clonelog');
375 sub _clonefail_path {
376 my $self = shift;
377 $self->_property_path('.clone_failed');
380 sub _clonep_path {
381 my $self = shift;
382 $self->_property_path('.clone_in_progress');
385 sub _clonep {
386 my $self = shift;
387 my ($nofetch) = @_;
388 my $np = $self->_clonep_path;
389 if ($nofetch) {
390 open my $x, '>', $np or die "clonep failed: $!";
391 close $x;
392 } else {
393 unlink $np or die "clonef failed: $!";
396 sub _alternates_setup {
397 use POSIX qw(:fcntl_h);
398 my $self = shift;
399 return unless $self->{name} =~ m#/#;
400 my $forkee_name = get_forkee_name($self->{name});
401 my $forkee_path = get_forkee_path($self->{name});
402 return unless -d $forkee_path;
403 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
404 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
405 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
406 mkdir $self->{path}.'/objects/pack'; chmod 02775, $self->{path}.'/objects/pack';
408 # If somehow either our objects/pack or the prospective alternate's pack
409 # directory does not exist decline to set up any alternates
410 my $altpath = "$forkee_path/objects";
411 -d $self->{path}.'/objects/pack' && -d $altpath.'/pack' or return;
413 # If our objects/pack and the prospective alternate's pack directory
414 # do not share the same device then decline to set up any alternates
415 my ($selfdev) = stat($self->{path}.'/objects/pack');
416 my ($altdev) = stat($altpath.'/pack');
417 defined($selfdev) && defined($altdev) && $selfdev ne "" && $altdev ne "" && $selfdev == $altdev or return;
419 # We set up both alternates and http_alternates since we cannot use
420 # relative path in alternates - that doesn't work recursively.
422 my $filename = $self->{path}.'/objects/info/alternates';
423 open my $x, '>', $filename or die "alternates failed: $!";
424 print $x "$altpath\n";
425 close $x;
426 chmod 0664, $filename or warn "cannot chmod $filename: $!";
428 if ($Girocco::Config::httppullurl) {
429 $filename = $self->{path}.'/objects/info/http-alternates';
430 open my $x, '>', $filename or die "http-alternates failed: $!";
431 my $upfork = $forkee_name;
432 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
433 close $x;
434 chmod 0664, $filename or warn "cannot chmod $filename: $!";
437 # copy lastactivity from the parent project
438 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
439 my $activity = <$x>;
440 close $x;
441 last unless $activity;
442 open $x, '>', $self->{path}.'/info/lastactivity' or last;
443 print $x $activity;
444 close $x;
445 chomp $activity;
446 $self->{'lastactivity'} = $activity;
449 # copy refs from parent project
450 my $dupout;
451 open $dupout, '>&1' or
452 die "could not dup STDOUT_FILENO: $!";
453 my $packedrefsfd = POSIX::open("$self->{path}/packed-refs", O_WRONLY|O_TRUNC|O_CREAT, 0664);
454 defined($packedrefsfd) && $packedrefsfd >= 0 or die "could not open fork's packed-refs file for writing: $!";
455 POSIX::dup2($packedrefsfd, 1) or
456 die "could not dup2 STDOUT_FILENO: $!";
457 POSIX::close($packedrefsfd);
458 my $result = system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
459 my $resultstr = $!;
460 POSIX::dup2(fileno($dupout), 1);
461 close($dupout);
462 $result == 0 or die "could not create fork's packed-refs file data: $resultstr";
463 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
465 # initialize HEAD
466 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
467 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
468 chomp $HEAD;
469 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
470 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
473 sub _set_changed {
474 my $self = shift;
475 my $fd;
476 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
479 sub _set_forkchange {
480 my $self = shift;
481 my $changedtoo = shift;
482 return unless $self->{name} =~ m#/#;
483 my $forkee_path = get_forkee_path($self->{name});
484 return unless -d $forkee_path;
485 # mark forkee as changed
486 my $fd;
487 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
488 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
489 return if -e $forkee_path.'/htmlcache/summary.forkchange';
490 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
493 sub _ctags_setup {
494 my $self = shift;
495 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
496 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
499 sub _group_add {
500 my $self = shift;
501 my ($xtra) = @_;
502 $xtra .= join(',', @{$self->{users}});
503 my $crypt = $self->{crypt};
504 defined($crypt) or $crypt = 'unknown';
505 filedb_atomic_append(jailed_file('/etc/group'),
506 join(':', $self->{name}, $crypt, '\i', $xtra));
509 sub _group_update {
510 my $self = shift;
511 my $xtra = join(',', @{$self->{users}});
512 filedb_atomic_edit(jailed_file('/etc/group'),
513 sub {
514 $_ = $_[0];
515 chomp;
516 if ($self->{name} eq (split /:/)[0]) {
517 # preserve readonly flag
518 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
519 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
520 } else {
521 return "$_\n";
527 sub _group_remove {
528 my $self = shift;
529 filedb_atomic_edit(jailed_file('/etc/group'),
530 sub {
531 $self->{name} ne (split /:/)[0] and return $_;
536 sub _hook_path {
537 my $self = shift;
538 my ($name) = @_;
539 $self->{path}.'/hooks/'.$name;
542 sub _hook_install {
543 my $self = shift;
544 my ($name) = @_;
545 my $hooksdir = $self->{path}.'/hooks';
546 my $oldmask = umask();
547 umask($oldmask & ~0070);
548 -d $hooksdir or mkdir $hooksdir or
549 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
550 umask($oldmask);
551 my $globalhooks = $Girocco::Config::reporoot . "/_global/hooks";
552 -f "$globalhooks/$name" && -r _ or die "cannot find hook $name: $!";
553 ! -e $self->_hook_path($name) || unlink $self->_hook_path($name) && ! -e $self->_hook_path($name) or
554 die "hooks directory contains unremovable pre-existing hook $name: $!";
555 symlink("$globalhooks/$name", $self->_hook_path($name)) or
556 die "cannot create hook $name symlink: $!";
559 sub _hooks_install {
560 my $self = shift;
561 foreach my $hook ('pre-auto-gc', 'pre-receive', 'post-commit', 'post-receive', 'update') {
562 $self->_hook_install($hook);
566 # private constructor, do not use
567 sub _new {
568 my $class = shift;
569 my ($name, $base_path, $path, $orphan, $optp) = @_;
570 does_exist($name,1) || valid_name($name, $orphan, $optp) or die "refusing to create project with invalid name ($name)!";
571 $path ||= "$base_path/$name.git";
572 my $proj = { name => $name, base_path => $base_path, path => $path };
574 bless $proj, $class;
577 # public constructor #0
578 # creates a virtual project not connected to disk image
579 # you can conjure() it later to disk
580 sub ghost {
581 my $class = shift;
582 my ($name, $mirror, $orphan, $optp) = @_;
583 my $self = $class->_new($name, $Girocco::Config::reporoot, undef, $orphan, $optp);
584 $self->{users} = [];
585 $self->{mirror} = $mirror;
586 $self->{email} = $self->{orig_email} = '';
587 $self;
590 # public constructor #1
591 sub load {
592 my $class = shift;
593 my $name = shift || '';
595 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
596 my $r = qr/^\Q$name\E:/;
597 foreach (grep /$r/, <$fd>) {
598 chomp;
600 my $self = $class->_new($name, $Girocco::Config::reporoot);
601 (-d $self->{path} && $self->_readlocalconfigfile(1))
602 or die "invalid path (".$self->{path}.") for project ".$self->{name};
604 my $ulist;
605 (undef, $self->{crypt}, $self->{gid}, $ulist) = split /:/;
606 $ulist ||= '';
607 $self->{users} = [split /,/, $ulist];
608 $self->{HEAD} = $self->get_HEAD;
609 $self->{orig_HEAD} = $self->{HEAD};
610 $self->{orig_users} = [@{$self->{users}}];
611 $self->{mirror} = ! -e $self->_nofetch_path;
612 $self->{banged} = -e $self->_banged_path if $self->{mirror};
613 $self->{gc_in_progress} = -e $self->_gcp_path;
614 $self->{clone_in_progress} = -e $self->_clonep_path;
615 $self->{clone_logged} = -e $self->_clonelog_path;
616 $self->{clone_failed} = -e $self->_clonefail_path;
617 $self->{ccrypt} = $self->{crypt};
619 $self->_properties_load;
620 $self->{orig_email} = $self->{email};
621 $self->{loaded} = 1; # indicates self was loaded from etc/group file
622 close $fd;
623 return $self;
625 close $fd;
626 undef;
629 # $proj may not be in sane state if this returns false!
630 # fields listed in %$metadata_fields that are NOT also
631 # in @Girocco::Config::project_fields are totally ignored!
632 sub cgi_fill {
633 my $self = shift;
634 my ($gcgi) = @_;
635 my $cgi = $gcgi->cgi;
636 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
637 my $field_enabled = sub {
638 !exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]})};
640 my $pwd = $cgi->param('pwd');
641 my $pwd2 = $cgi->param('pwd2');
642 # in case passwords are disabled
643 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd2 = '';
644 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
645 $gcgi->err("Empty passwords are not permitted.");
647 if ($pwd ne '' or not $self->{crypt}) {
648 $self->{crypt} = scrypt_sha1($pwd);
650 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
651 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
654 $self->{cpwd} = $cgi->param('cpwd');
656 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
657 my $newtype = $forkee ? 'fork' : 'project';
658 length($project) <= 64
659 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
661 if ($Girocco::Config::project_owners eq 'email') {
662 $self->{email} = $gcgi->wparam('email');
663 valid_email($self->{email})
664 or $gcgi->err("Your email sure looks weird...?");
665 length($self->{email}) <= 96
666 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
669 # No setting the url unless we're either new or an existing mirror!
670 unless ($self->{loaded} && !$self->{mirror}) {
671 $self->{url} = $gcgi->wparam('url') ;
672 if ($field_enabled->('cleanmirror')) {
673 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
676 # Always validate the url if we're an existing mirror
677 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
678 # Always allow the url to be left unchanged without validation when editing
679 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
680 valid_repo_url($self->{url})
681 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
682 if ($Girocco::Config::restrict_mirror_hosts) {
683 my $mh = extract_url_hostname($self->{url});
684 is_dns_hostname($mh)
685 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
686 !is_our_hostname($mh)
687 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
691 if ($field_enabled->('desc')) {
692 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
693 length($self->{desc}) <= 1024
694 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
697 if ($field_enabled->('README')) {
698 $self->{README} = to_utf8($gcgi->wparam('README'), 1);
699 $self->_cleanup_readme;
700 length($self->{README}) <= 8192
701 or $gcgi->err("README length &gt; 8kb!");
702 my ($cnt, $err) = (0);
703 ($cnt, $err) = $self->_lint_readme if $gcgi->ok && $Girocco::Config::xmllint_readme;
704 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
707 if ($field_enabled->('hp')) {
708 $self->{hp} = $gcgi->wparam('hp');
709 if ($self->{hp}) {
710 valid_web_url($self->{hp})
711 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
715 # No mucking about with users unless we're a push project
716 if (($self->{loaded} && !$self->{mirror}) ||
717 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
718 my %users = ();
719 my @users = ();
720 foreach my $user ($cgi->multi_param('user')) {
721 if (!exists($users{$user})) {
722 $users{$user} = 1;
723 push(@users, $user) if Girocco::User::does_exist($user, 1);
726 $self->{users} = \@users;
729 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
730 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
731 my $newhead;
732 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
733 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
734 if ($newhead eq $self->{orig_HEAD} ||
735 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
736 $self->{HEAD} = $newhead;
737 } else {
738 $gcgi->err("Invalid default branch (no such ref)");
742 # schedule deletion of tags (will be committed by update() after auth)
743 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
745 if ($field_enabled->('notifymail')) {
746 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
747 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
748 $self->{notifymail} = $newaddrs;
749 } else {
750 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
752 if ($field_enabled->('reverseorder')) {
753 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
755 if ($field_enabled->('summaryonly')) {
756 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
760 if ($field_enabled->('notifytag')) {
761 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
762 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
763 $self->{notifytag} = $newaddrs;
764 } else {
765 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
769 if ($field_enabled->('notifyjson')) {
770 $self->{notifyjson} = $gcgi->wparam('notifyjson');
771 if ($self->{notifyjson}) {
772 valid_web_url($self->{notifyjson})
773 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
777 if ($field_enabled->('notifycia')) {
778 $self->{notifycia} = $gcgi->wparam('notifycia');
779 if ($self->{notifycia}) {
780 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
781 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
785 if ($cgi->param('setstatusupdates')) {
786 my $val = $gcgi->wparam('statusupdates') || '0';
787 $self->{statusupdates} = $val ? 1 : 0;
790 not $gcgi->err_check;
793 sub form_defaults {
794 my $self = shift;
796 name => $self->{name},
797 email => $self->{email},
798 url => $self->{url},
799 cleanmirror => $self->{cleanmirror},
800 desc => html_esc($self->{desc}),
801 README => html_esc($self->{README}),
802 hp => $self->{hp},
803 users => $self->{users},
804 notifymail => html_esc($self->{notifymail}),
805 reverseorder => $self->{reverseorder},
806 summaryonly => $self->{summaryonly},
807 notifytag => html_esc($self->{notifytag}),
808 notifyjson => html_esc($self->{notifyjson}),
809 notifycia => html_esc($self->{notifycia}),
813 # return true if $enc_passwd is a match for $plain_passwd
814 my $_check_passwd_match = sub {
815 my $enc_passwd = shift;
816 my $plain_passwd = shift;
817 defined($enc_passwd) or $enc_passwd = '';
818 defined($plain_passwd) or $plain_passwd = '';
819 # $enc_passwd may be crypt or crypt_sha1
820 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
821 # It's using sha1-crypt
822 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
823 } else {
824 # It's using crypt
825 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
829 sub authenticate {
830 my $self = shift;
831 my ($gcgi) = @_;
833 $self->{ccrypt} or die "Can't authenticate against a project with no password";
834 defined($self->{cpwd}) or $self->{cpwd} = '';
835 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
836 $gcgi->err("Your admin password does not match!");
837 return 0;
839 return 1;
842 # return true if the password from the file is empty or consists of all the same
843 # character. However, if the project was NOT loaded from the group file
844 # (!self->{loaded}) then the password is never locked.
845 # This function does NOT check $Girocco::Config::project_passwords, the caller
846 # is responsible for doing so if desired. Same for $self->{email}.
847 sub is_password_locked {
848 my $self = shift;
850 $self->{loaded} or return 0;
851 my $testcrypt = $self->{ccrypt}; # The value from the group file
852 defined($testcrypt) or $testcrypt = '';
853 $testcrypt ne '' or return 1; # No password at all
854 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
855 return 0; # Not locked
858 sub _setup {
859 use POSIX qw(strftime);
860 my $self = shift;
861 my ($pushers) = @_;
862 my $fd;
864 defined($self->{path}) && $self->{path} ne "" or die "invalid setup call";
865 $self->_mkdir_forkees unless $self->{adopt};
867 my $gid;
868 $self->{adopt} || mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
869 -d $self->{path} or die "unable to setup nonexistent $self->{path}";
870 if ($Girocco::Config::owning_group) {
871 $gid = scalar(getgrnam($Girocco::Config::owning_group));
872 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
873 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
874 } else {
875 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
877 delete $ENV{GIT_OBJECT_DIRECTORY};
878 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
879 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
880 or die "git init $self->{path} failed: $?";
881 # we don't need these two, remove them (they will normally be created empty) if they exist
882 rmdir $self->{path}."/branches";
883 rmdir $self->{path}."/remotes";
884 -d $self->{path}."/info" or mkdir $self->{path}."/info"
885 or die "info directory does not exist and unable to create it: $!";
886 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
887 or die "hooks directory does not exist and unable to create it: $!";
888 # clean out any kruft that may have come in from the initial template directory
889 foreach my $cleandir (qw(hooks info)) {
890 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
891 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
892 closedir $hooksdir;
895 if ($Girocco::Config::owning_group) {
896 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
898 # hooks never world writable
899 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
900 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.compression', '5') == 0
901 or die "setting core.compression failed: $?";
902 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
903 or die "disabling core.logAllRefUpdates failed: $?";
904 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
905 or die "disabling core.ignoreCase failed: $?";
906 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.hooksPath',
907 ($Girocco::Config::localhooks ? $self->{path}."/hooks" : $Girocco::Config::reporoot . "/_global/hooks")) == 0
908 or die "setting core.hooksPath failed: $?";
909 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'extensions.preciousObjects', 'true') == 0
910 or die "setting extensions.preciousObjects failed: $?";
911 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
912 or die "enabling transfer.fsckObjects failed: $?";
913 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.unpackLimit', '1') == 0
914 or die "setting transfer.unpackLimit failed: $?";
915 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.fsckObjects', 'true') == 0
916 or die "enabling receive.fsckObjects 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', 'receive.autogc', '0') == 0
922 or die "disabling receive.autogc failed: $?";
923 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
924 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
925 or die "enabling receive.updateServerInfo failed: $?";
926 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
927 or die "enabling repack.writeBitmaps failed: $?";
928 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
929 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
930 or die "setting girocco.creationtime failed: $?";
931 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
932 or die "htmlcache directory does not exist and unable to create it: $!";
933 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
934 or die "bundles directory does not exist and unable to create it: $!";
935 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
936 or die "reflogs directory does not exist and unable to create it: $!";
937 foreach my $file (qw(info/lastactivity .delaygc)) {
938 if (open $fd, '>', $self->{path}."/".$file) {
939 close $fd;
940 chmod 0664, $self->{path}."/".$file;
944 # /info must have right permissions,
945 # and git init didn't do it for some reason.
946 # config must have correct permissions.
947 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
948 # also make sure /refs, /objects and /htmlcache are correct too.
949 my ($dmode, $dmodestr, $fmode, $fmodestr);
950 if ($Girocco::Config::owning_group) {
951 ($dmode, $dmodestr) = (02775, '02775');
952 ($fmode, $fmodestr) = (0664, '0664');
953 } else {
954 ($dmode, $dmodestr) = (02777, '02777');
955 ($fmode, $fmodestr) = (0666, '0666');
957 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
958 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
960 foreach my $file (qw(config)) {
961 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
963 # these ones are probably not strictly required but are nice to have
964 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
965 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
966 chmod($dmode, $self->{path}."/$dir");
968 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::htmlcache_owning_group) {
969 my $htmlgid = scalar(getgrnam($Girocco::Config::htmlcache_owning_group));
970 if (defined($htmlgid) && $htmlgid ne $gid) {
971 chown(-1, $htmlgid, $self->{path}."/htmlcache") or die "chgrp $htmlgid $self->{path}/htmlcache failed: $!";
972 chmod($dmode, $self->{path}."/htmlcache") or die "chmod $dmodestr $self->{path}/htmlcache failed: $!";
975 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::ctags_owning_group) {
976 my $ctagsgid = scalar(getgrnam($Girocco::Config::ctags_owning_group));
977 if (defined($ctagsgid) && $ctagsgid ne $gid) {
978 chown(-1, $ctagsgid, $self->{path}."/ctags") or die "chgrp $ctagsgid $self->{path}/ctags failed: $!";
979 chmod($dmode, $self->{path}."/ctags") or die "chmod $dmodestr $self->{path}/ctags failed: $!";
983 $self->_properties_save;
984 $self->_alternates_setup unless $self->{noalternates} || $self->{adopt};
985 $self->_ctags_setup;
986 $self->_group_remove;
987 $self->_group_add($pushers);
988 $self->_hooks_install;
989 $self->_update_index;
990 $self->_set_changed;
991 $self->_set_forkchange(1);
994 sub premirror {
995 my $self = shift;
997 delete $self->{adopt};
998 $self->_setup(':');
999 $self->_clonep(1);
1000 if ($Girocco::Config::autogchack) {
1001 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1002 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1004 $self->perm_initialize;
1007 sub conjure {
1008 my $self = shift;
1010 delete $self->{adopt};
1011 $self->_setup;
1012 $self->_nofetch(1);
1013 if ($Girocco::Config::autogchack && $Girocco::Config::autogchack ne "mirror") {
1014 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1015 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1017 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1018 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1019 or die "create-personal-mob-area $self->{name} failed";
1021 $self->perm_initialize;
1024 sub clone {
1025 my $self = shift;
1027 unlink ($self->_clonefail_path()); # Ignore EEXIST error
1028 unlink ($self->_clonelog_path()); # Ignore EEXIST error
1030 use IO::Socket;
1031 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
1032 select((select($sock),$|=1)[0]);
1033 $sock->print("clone ".$self->{name}."\n");
1034 # Just ignore reply, we are going to succeed anyway and the I/O
1035 # would apparently get quite hairy.
1036 $sock->flush();
1037 sleep 2; # *cough*
1038 $sock->close();
1041 # call this after ghost instead of conjure or premirror+clone to adopt a pre-existing Git dir
1042 # ghost must be called with the proper value of $mirror for the to-be-adopted project
1043 # for mirrors the $proj->{url} needs to be set and for push projects the $proj->{users} array ref
1044 sub adopt {
1045 my $self = shift;
1046 my $name = $self->{name};
1048 # Sanity check first
1049 defined($name) && $name ne "" && !$self->{loaded} or return undef;
1050 does_exist($name, 1) or return undef;
1051 defined($self->{path}) && $self->{path} eq $Girocco::Config::reporoot."/$name.git" or return undef;
1052 defined($self->{base_path}) && $self->{base_path} eq $Girocco::Config::reporoot or return undef;
1053 defined($self->{email}) && defined($self->{orig_email}) && defined($self->{mirror}) && ref($self->{users}) eq 'ARRAY'
1054 or return undef;
1055 !defined(Girocco::Project->load($name)) or return undef;
1056 is_git_dir($self->{path}) or return undef;
1057 my $config = read_config_file_hash($self->{path}."/config");
1058 defined($config) && _boolval($config->{"core.bare"}) or die "refusing to adopt non-bare repository";
1059 defined(read_HEAD_symref($self->{path})) or die "refusing to adopt non-symref HEAD repository";
1061 # Adopt the project by creating a new $chroot/etc/group entry and setting up anything that's missing
1062 $self->_nofetch(!$self->{mirror});
1063 $self->{adopt} = 1;
1064 $self->_setup($self->{mirror} ? ":" : "");
1065 delete $self->{adopt};
1066 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
1067 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1068 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1070 if (!$self->{mirror} && $Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1071 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1072 or die "create-personal-mob-area $self->{name} failed";
1074 my $result = $self->perm_initialize;
1075 unlink("$self->{path}/.delaygc") unless $self->is_empty;
1076 # Pick up any pre-existing settings
1077 my $p = Girocco::Project->load($name);
1078 %$self = %$p if defined($p) && $p->{loaded};
1079 $result;
1082 sub _update_users {
1083 my $self = shift;
1085 $self->_group_update;
1086 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
1087 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
1088 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
1089 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
1092 sub update {
1093 my $self = shift;
1095 $self->_properties_save;
1096 $self->_update_users;
1098 if (exists($self->{tags_to_delete})) {
1099 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1102 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1104 $self->_update_index if $self->{email} ne $self->{orig_email};
1105 $self->{orig_email} = $self->{email};
1106 $self->_set_changed;
1111 sub update_password {
1112 my $self = shift;
1113 my ($pwd) = @_;
1115 $self->{crypt} = scrypt_sha1($pwd);
1116 $self->_group_update;
1119 # You can explicitly do this just on a ghost() repository too.
1120 sub delete {
1121 my $self = shift;
1123 if (-d $self->{path}) {
1124 system('rm', '-rf', $self->{path}) == 0
1125 or die "rm -rf $self->{path} failed: $?";
1127 # attempt to clean up any empty fork directories by removing them
1128 my @pelems = split('/', $self->{name});
1129 while (@pelems > 1) {
1130 pop @pelems;
1131 # okay to fail
1132 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1134 $self->_group_remove;
1135 $self->_update_index;
1136 $self->_set_forkchange(1);
1141 # If the project's directory actually exists archive it before deleting it
1142 # Return full path to archived project ("" if none)
1143 sub archive_and_delete {
1144 my $self = shift;
1146 unless (-d $self->{path}) {
1147 $self->delete;
1148 return "";
1151 # archive the project before deletion
1152 use POSIX qw(strftime);
1153 my $destdir = $self->{base_path};
1154 $destdir =~ s,(?<=[^/])/+$,,;
1155 $destdir .= "/_recyclebin/";
1156 $destdir .= $1 if $self->{name} =~ m,^(.*/)[^/]+$,;
1157 my $destbase = $self->{name};
1158 $destbase = $1 if $destbase =~ m,^.*/([^/]+)$,;
1159 my $oldmask = umask();
1160 umask($oldmask & ~0070);
1161 system('mkdir', '-p', $destdir) == 0 && -d $destdir
1162 or die "mkdir -p \"$destdir\" failed: $?";
1163 umask($oldmask);
1164 my $suffix = '';
1165 if (-e "$destdir$destbase.git") {
1166 $suffix = 1;
1167 while (-e "$destdir$destbase~$suffix.git") {
1168 ++$suffix;
1169 last if $suffix >= 10000; # don't get too carried away
1171 $suffix = '~'.$suffix;
1173 not -e "$destdir$destbase$suffix.git"
1174 or die "Unable to compute suitable archive path";
1175 system('mv', $self->{path}, "$destdir$destbase$suffix.git") == 0
1176 or die "mv \"$self->{path}\" \"$destdir$destbase$suffix.git\" failed: $?";
1177 if (!$self->{mirror} && @{$self->{users}}) {
1178 # Remember the user list at recycle time
1179 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1180 'config', 'girocco.recycleusers', join(",", @{$self->{users}}));
1182 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1183 my $recycletime = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1184 # We ought to do something if this fails, but the project has already been moved
1185 # so there's really nothing to be done at this point.
1186 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1187 'config', 'girocco.recycletime', $recycletime);
1189 $self->delete;
1190 return $destdir.$destbase.$suffix.".git";
1193 sub _contains_files {
1194 my $dir = shift;
1195 (-d $dir) or return 0;
1196 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1197 while (my $entry = readdir($dh)) {
1198 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1199 closedir($dh), return 1
1200 if -f "$dir/$entry" ||
1201 -d "$dir/$entry" && _contains_files("$dir/$entry");
1203 closedir($dh);
1204 return 0;
1207 sub has_forks {
1208 my $self = shift;
1210 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1213 # Returns an array of 0 or more array refs, one for each bundle:
1214 # ->[0]: bundle creation time (seconds since epoch)
1215 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1216 # ->[2]: bundle size in bytes
1217 sub bundles {
1218 my $self = shift;
1219 use Time::Local;
1221 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1222 my @blist = ();
1223 if (-d $self->{path}.'/bundles') {{
1224 my $prefix = $self->{name};
1225 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1226 opendir(my $dh, $self->{path}.'/bundles') or last;
1227 while (my $bfile = readdir($dh)) {
1228 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1229 my $ctime = eval {timegm(
1230 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1231 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4)-1900)};
1232 next unless $ctime;
1233 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1234 my $f1 = <$bh>;
1235 my $f2 = <$bh>;
1236 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1237 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1238 close($bh);
1239 next unless $f1 && $f2 && $f1 ne $f2;
1240 chomp $f1;
1241 chomp $f2;
1242 next unless -e $f1 && -e $f2;
1243 my $s1 = -s $f1 || 0;
1244 my $s2 = -s $f2 || 0;
1245 next unless $s1 || $s2;
1246 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1248 closedir($dh);
1250 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1251 my %seen = ();
1252 my @result = ();
1253 foreach my $bndl (@blist) {
1254 next if $seen{$bndl->[1]};
1255 $seen{$bndl->[1]} = 1;
1256 push(@result, $bndl);
1258 $self->{bundles} = \@result;
1259 return @result;
1262 sub has_alternates {
1263 my $self = shift;
1264 return -s $self->{path}.'/objects/info/alternates' ? 1 : 0;
1267 sub has_bundle {
1268 my $self = shift;
1270 return scalar($self->bundles);
1273 sub _has_notifyhook {
1274 my $self = shift;
1275 my $val = $Girocco::Config::default_notifyhook;
1276 defined($self->{'notifyhook'}) and $val = $self->{'notifyhook'};
1277 return (defined($val) && $val ne "") ? $val : undef;
1280 # returns true if any of the notify fields are non-empty
1281 sub has_notify {
1282 my $self = shift;
1283 # We do not ckeck notifycia since it's defunct
1284 return
1285 $self->{'notifymail'} || $self->{'notifytag'} ||
1286 $self->{'notifyjson'} ||
1287 !!$self->_has_notifyhook;
1290 sub is_empty {
1291 # A project is considered empty if the git repository does not
1292 # have any refs. This means packed-refs does not exist or is
1293 # empty or only has lines starting with '#' AND there are no
1294 # files in the refs subdirectory hierarchy (no matter how deep).
1296 my $self = shift;
1298 (-d $self->{path}) or return 0;
1299 if (-e $self->{path}.'/packed-refs') {
1300 open(my $pr, '<', $self->{path}.'/packed-refs')
1301 or die "open $self->{path}./packed-refs failed: $!";
1302 my $foundref = 0;
1303 while (my $ref = <$pr>) {
1304 next if $ref =~ /^#/;
1305 $foundref = 1;
1306 last;
1308 close($pr);
1309 return 0 if $foundref;
1311 (-d $self->{path}.'/refs') or return 1;
1312 return !_contains_files($self->{path}.'/refs');
1315 # returns array:
1316 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1317 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1318 # Both values (if not undef) are seconds since epoch
1319 # Result only considers lastgc and min_gc_interval nothing else
1320 sub next_gc {
1321 my $self = shift;
1322 my $lastgcepoch = parse_any_date($self->{lastgc});
1323 return (undef, undef) unless defined $lastgcepoch;
1324 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1325 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1326 $Girocco::Config::min_mirror_interval));
1329 # returns boolean (0 or 1)
1330 # Attempts to determine whether or not a gc (and corresponding build
1331 # of a .bitmap/.bndl file) will actually take place at the next_gc
1332 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1333 # end up being built depends on whether or not the local object graph
1334 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1335 # is not possible because the object graph will be incomplete,
1336 # but it *is* possible that even though the repository has_alternates,
1337 # it does not actually borrow any objects so a .bitmap/.bndl will build
1338 # in spite of the presence of alternates -- but this is expected to be rare.
1339 # The result is a best guess and false return value is not an absolute
1340 # guarantee that gc will not take place at the next interval, but it probably
1341 # will not if nothing changes in the meantime.
1342 sub needs_gc {
1343 my $self = shift;
1344 my $lgc = parse_any_date($self->{lastgc});
1345 my $lrecv = parse_any_date($self->{lastreceive});
1346 my $lpgc = parse_any_date($self->{lastparentgc});
1347 return 1 unless defined($lgc) && defined($lrecv);
1348 if ($self->has_alternates) {
1349 return 1 unless defined($lpgc);
1350 return 1 unless $lpgc < $lgc;
1352 return 1 unless $lrecv < $lgc;
1353 # We don't try running any "is_dirty" check, so if somehow the
1354 # repository became dirty without updating lastreceive we might
1355 # incorrectly return false instead of true.
1356 return 0;
1359 sub delete_ctag {
1360 my $self = shift;
1361 my ($ctag) = @_;
1363 # sanity check, disallow filenames starting with . .. or /
1364 unlink($self->{path}.'/ctags/'.$ctag)
1365 unless !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1368 # returns new tag count value on success (will always be >= 1) otherwise undef
1369 sub add_ctag {
1370 my $self = shift;
1371 my $ctag = valid_tag(shift);
1372 my $nochanged = shift;
1374 # sanity check, disallow filenames starting with . .. or /
1375 return undef if !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1377 my $val = 0;
1378 my $ct;
1379 if (open $ct, '<', $self->{path}."/ctags/$ctag") {
1380 my $count = <$ct>;
1381 close $ct;
1382 defined $count or $count = '';
1383 chomp $count;
1384 $val = $count =~ /^[1-9]\d*$/ ? $count : 1;
1386 ++$val;
1387 my $oldmask = umask();
1388 umask($oldmask & ~0060);
1389 open $ct, '>', $self->{path}."/ctags/$ctag" and print $ct $val."\n" and close $ct;
1390 $self->_set_changed unless $nochanged;
1391 $self->_set_forkchange unless $nochanged;
1392 umask($oldmask);
1393 return $val;
1396 sub get_ctag_names {
1397 my $self = shift;
1398 my @ctags = ();
1399 opendir(my $dh, $self->{path}.'/ctags')
1400 or return @ctags;
1401 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1402 closedir($dh);
1403 return sort({lc($a) cmp lc($b)} @ctags);
1406 sub get_heads {
1407 my $self = shift;
1408 my $fh;
1409 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1410 defined($heads) or $heads = '';
1411 chomp $heads;
1412 my @res = ();
1413 foreach (split(/\n/, $heads)) {
1414 chomp;
1415 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1416 push @res, $1;
1418 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1419 @res;
1422 sub get_HEAD {
1423 my $self = shift;
1424 my $HEAD = read_HEAD_symref($self->{path});
1425 defined($HEAD) or $HEAD = '';
1426 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
1427 return $1;
1430 sub set_HEAD {
1431 my $self = shift;
1432 my $newHEAD = shift;
1433 # Cursory checks only -- if you want to break your HEAD, be my guest
1434 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
1435 die "grossly invalid new HEAD: $newHEAD";
1437 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1438 die "could not set HEAD" if ($? >> 8);
1439 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1440 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1443 sub gen_auth {
1444 my $self = shift;
1445 my ($type) = @_;
1446 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1448 $self->{authtype} = $type;
1450 no warnings;
1451 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1453 my $expire = time + 24 * 3600;
1454 my $propval = "# ${type}AUTH $self->{auth} $expire";
1455 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1456 $self->{auth};
1459 sub del_auth {
1460 my $self = shift;
1462 delete $self->{auth};
1463 delete $self->{authtype};
1464 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1467 sub remove_user {
1468 my $self = shift;
1469 my ($username) = @_;
1471 my $before_count = @{$self->{users}};
1472 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1473 return @{$self->{users}} != $before_count;
1476 ### static methods
1478 sub get_forkee_name {
1479 local $_ = $_[0];
1480 (m#^(.*)/.*?$#)[0]; #
1483 sub get_forkee_path {
1484 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1485 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1486 -d $forkee ? $forkee : '';
1489 # Ultimately the full project/fork name could end up being part of a Git ref name
1490 # when a project's forks are combined into one giant repository for efficiency.
1491 # That means that the project/fork name must satisfy the Git ref name requirements:
1493 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1494 # 2. The character with an ASCII value of 0x7F is not allowed
1495 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1496 # 4. The character '/' is a separator and is not allowed within a name
1497 # 5. The name may not start with '.' or end with '.'
1498 # 6. The name may not end with '.lock'
1499 # 7. The name may not contain the '..' sequence
1500 # 8. The name may not contain the '@{' sequence
1501 # 9. If multiple components are used (separated by '/'), no empty '' components
1503 # We also prohibit a trailing '.git' on any path component and futher restrict
1504 # the allowed characters to alphanumeric and [+._-] where names must start with
1505 # an alphanumeric.
1507 sub _valid_name_characters {
1508 local $_ = $_[0];
1509 (not m#^[/+._-]#)
1510 and (not m#//#)
1511 and (not m#\.\.#)
1512 and (not m#/[+._-]#)
1513 and (not m#\./#)
1514 and (not m#\.$#)
1515 and (not m#\.git/#i)
1516 and (not m#\.git$#i)
1517 and (not m#\.idx/#i)
1518 and (not m#\.idx$#i)
1519 and (not m#\.lock/#i)
1520 and (not m#\.lock$#i)
1521 and (not m#\.pack/#i)
1522 and (not m#\.pack$#i)
1523 and (not m#\.bundle/#i)
1524 and (not m#\.bundle$#i)
1525 and (not m#/$#)
1526 and (not m/^[a-fA-F0-9]{38}$/)
1527 and m#^[a-zA-Z0-9/+._-]+$#
1528 and !has_reserved_suffix($_, $_[1], $_[2]);
1531 # $_[0] => prospective project name (WITHOUT trailing .git)
1532 # $_[1] => true to allow orphans (i.e. two-or-more-level-deep projects without a parent)
1533 # (the directory in which the orphan will be created must, however, already exist)
1534 # $_[2] => true to allow orphans w/o needed directory if $_[1] also true (like mkdir -p)
1535 sub valid_name {
1536 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1537 local $_ = $_[0];
1538 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1539 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1540 and ((not m#/#) or -d get_forkee_path($_) or ($_[1] and ($_[2] or -d $Girocco::Config::reporoot.'/'.get_forkee_name($_))))
1541 and (! -f $Girocco::Config::reporoot."/$_.git");
1544 # It's possible that some forks have been kept but the forkee is gone.
1545 # In this case the standard valid_name check is too strict.
1546 sub does_exist {
1547 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1548 my ($name, $nodie) = @_;
1549 my $okay = (
1550 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1551 and ((not $name =~ m#/#)
1552 or -d get_forkee_path($name)
1553 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1554 (!$okay && $nodie) and return undef;
1555 !$okay and die "tried to query for project with invalid name $name!";
1556 (-d $Girocco::Config::reporoot."/$name.git");
1559 sub get_full_list {
1560 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1561 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1562 close $fd;
1563 @projects;