Girocco/Project.pm: validate new JSON POST url with test POST
[girocco/readme.git] / Girocco / Project.pm
blob1c47a086a35a1d6097e56cb6265e81375be561aa
1 package Girocco::Project;
3 use strict;
4 use warnings;
6 BEGIN {
7 use Girocco::Config;
8 use Girocco::CGI;
9 use Girocco::User;
10 use Girocco::Util;
11 use Girocco::HashUtil;
12 use Girocco::Notify;
13 use Girocco::ProjPerm;
14 use base ('Girocco::ProjPerm::'.$Girocco::Config::permission_control); # mwahaha
17 BEGIN {
18 eval {
19 require Digest::SHA;
20 Digest::SHA->import(
21 qw(sha1_hex)
22 );1} ||
23 eval {
24 require Digest::SHA1;
25 Digest::SHA1->import(
26 qw(sha1_hex)
27 );1} ||
28 eval {
29 require Digest::SHA::PurePerl;
30 Digest::SHA::PurePerl->import(
31 qw(sha1_hex)
32 );1} ||
33 die "One of Digest::SHA or Digest::SHA1 or Digest::SHA::PurePerl "
34 . "must be available\n";
37 # NOTE: Each value may be either an ARRAY ref of a single element
38 # OR an ARRAY ref containing 1 or more ARRAY refs thus allowing
39 # a set of fields to be associated with a name (e.g. 'notifyjson')
40 our $metadata_fields = {
41 cleanmirror => ['Mirror refs', 'cleanmirror', 'placeholder'],
42 homepage => ['Homepage URL', 'hp', 'text'],
43 shortdesc => ['Short description', 'desc', 'text'],
44 README => ['<span style="display:inline-block;vertical-align:top">'.
45 'README (HTML, &lt; 8 KiB)<br />leave blank for automatic</span>',
46 'README', 'textarea', 'Enter only &#x201c;<!-- comments -->&#x201d; '.
47 'to completely suppress any README'],
48 notifymail => ['Commit notify &#x2013; mail to', 'notifymail', 'text',
49 'comma separated address list'],
50 reverseorder => ['Show oldest first', 'reverseorder', 'checkbox',
51 'show new revisions in oldest to newest order (instead of the default newest to oldest older)'.
52 ' in &#x201c;Commit notify&#x201d; email when showing new revisions'],
53 summaryonly => ['Summaries only', 'summaryonly', 'checkbox',
54 'suppress patch/diff output in &#x201c;Commit notify&#x201d; email when showing new revisions'],
55 notifytag => ['Tag notify &#x2013; mail to', 'notifytag', 'text',
56 'comma separated address list &#x2013; if not empty, tag '.
57 'notifications are sent here INSTEAD of to '.
58 '&#x201c;Commit notify &#x2013; mail to&#x201d; address(es)'],
59 notifyjson => [
60 ['Commit notify &#x2013; '.
61 '<a title="'.html_esc('single field name is &#x201c;payload&#x201d;', 1).'" href="'.
62 'https://docs.github.com/developers/webhooks-and-events/webhook-events-and-payloads#push'.
63 '">POST JSON</a> at', 'notifyjson', 'text'],
64 ['JSON Content-Type', 'jsontype', 'select', 'JSON POST Content-Type', \&_json_choices],
65 ['JSON Secret', 'jsonsecret', 'text', 'secret used to compute JSON POST signatures']],
66 notifycia => ['Commit notify &#x2013; <a href="http://cia.vc/doc/">CIA project</a> name',
67 'notifycia', 'text', 'CIA is defunct &#x2013; this value is ignored'],
70 sub _json_choices {
71 return ('application/x-www-form-urlencoded', 'application/json');
74 sub _mkdir_forkees {
75 my $self = shift;
76 my @pelems = split('/', $self->{name});
77 pop @pelems; # do not create dir for the project itself
78 my $path = $self->{base_path};
79 foreach my $pelem (@pelems) {
80 $path .= "/$pelem";
81 (-d "$path") or mkdir $path or die "mkdir $path: $!";
82 chmod 02775, $path; # ok if fails (dir may already exist and be owned by someone else)
86 # With a leading ':' get from project local config replacing ':' with 'gitweb.'
87 # With a leading '%' get from project local config after removing '%'
88 # With a leading '!' get boolean from project local config after removing '!' (prefixed with 'gitweb.' if no '.')
89 # With a leading [:%!] a trailing ':defval' may be added to select the default value to use if unset
90 # Otherwise it's a project file name to be loaded
91 # %propmapro entries are loaded but never written
92 # %propmapromirror entries are loaded only for mirrors but never written
94 our %propmap = (
95 url => ':baseurl',
96 email => ':owner',
97 desc => 'description',
98 README => 'README.html',
99 hp => ':homepage',
100 notifymail => '%hooks.mailinglist',
101 notifytag => '%hooks.announcelist',
102 notifyjson => '%hooks.jsonurl',
103 jsontype => '%hooks.jsontype',
104 jsonsecret => '%hooks.jsonsecret',
105 notifycia => '%hooks.cianame',
106 cleanmirror => '!girocco.cleanmirror',
107 statusupdates => '!statusupdates:1',
108 reverseorder => '!hooks.reverseorder',
109 summaryonly => '!hooks.summaryonly',
112 our %propmapro = (
113 lastchange => ':lastchange',
114 lastactivity => 'info/lastactivity',
115 lastgc => ':lastgc',
116 lastreceive => ':lastreceive',
117 lastparentgc => ':lastparentgc',
118 lastrefresh => ':lastrefresh',
119 creationtime => '%girocco.creationtime',
120 reposizek => '%girocco.reposizek',
121 notifyhook => '%girocco.notifyhook:undef',
122 origurl => ':baseurl',
125 our %propmapromirror = (
126 bangcount => '%girocco.bang.count',
127 bangfirstfail => '%girocco.bang.firstfail',
128 bangmessagesent => '!girocco.bang.messagesent',
129 showpush => '!showpush',
132 # Projects with any of these names will be disallowed to avoid possible
133 # collisions with cgi script paths or chroot paths
134 # NOTE: names are checked after using lc on them, so all entries MUST be lowercase
135 our %reservedprojectnames = (
136 admin => 1, # /admin/ links
137 alternates => 1, # .git/objects/info/alternates
138 b => 1, # /b/ -> bundle.cgi
139 blog => 1, # /blog/ links
140 c => 1, # /c/ -> cgit
141 'git-receive-pack' => 1, # smart HTTP
142 'git-upload-archive' => 1, # smart HTTP
143 'git-upload-pack' => 1, # smart HTTP
144 h => 1, # /h/ -> html.cgi
145 head => 1, # .git/HEAD
146 'http-alternates' => 1, # .git/objects/info/http-alternates
147 info => 1, # .git/info
148 objects => 1, # .git/objects
149 packs => 1, # .git/objects/info/packs
150 r => 1, # /r/ -> git http
151 refs => 1, # .git/refs
152 w => 1, # /w/ -> gitweb
153 wiki => 1, # /wiki/ links
154 srv => 1, # /srv/git/ -> chroot ssh git repositories
157 sub _update_index {
158 my $self = shift;
159 system("$Girocco::Config::basedir/gitweb/genindex.sh", $self->{name});
162 sub _readlocalconfigfile {
163 my $self = shift;
164 my $undefonerr = shift || 0;
165 delete $self->{configfilehash};
166 my $confighash = read_config_file_hash($self->{path} . "/config");
167 my $result = 1;
168 defined($confighash) || $undefonerr or $result = 0, $confighash = {};
169 return undef unless defined($confighash);
170 $self->{configfilehash} = $confighash;
171 return $result;
174 # @_[0]: argument to convert to boolean result (0 or 1)
175 # @_[1]: value to use if argument is undef (default is 0)
176 # Returns 0 or 1
177 sub _boolval {
178 my ($val, $def) = @_;
179 defined($def) or $def = 0;
180 defined($val) or $val = $def;
181 $val =~ s/\s+//gs;
182 $val = lc($val);
183 return 0 if $val eq '' || $val eq 'false' || $val eq 'off' || $val eq 'no' || $val =~ /^[-+]?0+$/;
184 return 1;
187 sub _property_path {
188 my $self = shift;
189 my ($name) = @_;
190 $self->{path}.'/'.$name;
193 sub _property_fget {
194 my $self = shift;
195 my ($name, $nodef) = @_;
196 my $pname = $propmap{$name};
197 $pname = $propmapro{$name} unless $pname;
198 $pname = $propmapromirror{$name} unless $pname;
199 $pname or die "unknown property: $name";
200 if ($pname =~ /^([:%!])([^:]+)(:.*)?$/) {
201 my ($where, $pname, $defval) = ($1, lc($2), substr(($3||":"),1));
202 $defval = undef if $defval eq "undef";
203 $defval = '' if $nodef;
204 $self->_readlocalconfigfile
205 unless ref($self->{configfilehash}) eq 'HASH';
206 $pname = "gitweb." . $pname if $where eq ':' or $where eq '!' && $pname !~ /[.]/;
207 my $val = $self->{configfilehash}->{$pname};
208 defined($val) or $val = $defval;
209 chomp $val if defined($val);
210 $val = _boolval($val, $defval) if $where eq '!';
211 return $nodef && !exists($self->{configfilehash}->{$pname}) ? undef : $val;
214 open my $p, '<', $self->_property_path($pname) or return undef;
215 my @value = <$p>;
216 close $p;
217 my $value = join('', @value); chomp $value;
218 $value;
221 sub _prop_is_same {
222 my $self = shift;
223 my ($name, $value) = @_;
224 my $existing = $self->_property_fget($name, 1);
225 defined($value) or $value = '';
226 return defined($existing) && $existing eq $value;
229 sub _property_fput {
230 my $self = shift;
231 my ($name, $value, $nosetsame) = @_;
232 my $pname = $propmap{$name};
233 $pname or die "unknown property: $name";
234 my $defval = '';
235 ($pname, $defval) = ($1, substr(($2||":"),1)) if $pname =~ /^([:%!][^:]+)(:.*)?$/;
236 defined($value) or $value = $defval;
237 if ($pname =~ s/^://) {
238 return if $nosetsame && $self->_prop_is_same($name, $value);
239 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
240 return;
241 } elsif ($pname =~ s/^%//) {
242 return if $nosetsame && $self->_prop_is_same($name, $value);
243 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
244 return;
245 } elsif ($pname =~ s/^!//) {
246 $pname = "gitweb." . $pname unless $pname =~ /[.]/;
247 $value = _boolval($value, $defval);
248 return if $nosetsame && $self->_prop_is_same($name, $value);
249 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool', $pname, $value);
250 return;
253 my $P = lock_file($self->_property_path($pname));
254 chomp $value;
255 $value ne '' and print $P "$value\n";
256 close $P;
257 unlock_file($self->_property_path($pname));
260 sub _cleanup_datetime {
261 my $self = shift;
262 my $k = shift;
263 defined($k) && $k ne "" or return;
264 local $_ = $self->{$k}; defined($_) or $_ = '';
265 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
266 s/\s+/ /gs;
267 s/^\s+//s;
268 s/\s+$//s;
269 my $ts = parse_any_date($_);
270 defined($ts) or $_ = '';
271 /^(.*)$/ and $self->{$k} = $1;
274 sub _cleanup_description {
275 my $self = shift;
276 local $_ = $self->{desc}; defined($_) or $_ = '';
277 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
278 s/\r\n?/\n/gs;
279 s/^\s+//s;
280 s/\s+$//s;
281 /\A(.*)$/m and $self->{desc} = $1;
284 sub _cleanup_readme {
285 my $self = shift;
286 local $_ = $self->{README}; defined($_) or $_ = '';
287 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
288 s/\r\n?/\n/gs;
289 s/^\s+//s;
290 s/\s+$//s;
291 $_ eq '' or $_ .= "\n";
292 /^(.*)$/s and $self->{README} = $1;
295 sub _lint_readme {
296 my $self = shift;
297 my $htmlfrag = shift;
298 defined($htmlfrag) or $htmlfrag = 1;
299 return 0 unless defined($self->{README}) && $self->{README} ne '';
300 my $test = '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>';
301 $test .= $self->{README};
302 $test .= '</div></body></html>';
303 my ($code, $errors) = capture_command(2, $test, 'xmllint', '--nonet',
304 '--noout', '--nowarning', '-');
305 return 0 unless $code;
306 my $cnt = 0;
307 my @errs = ();
308 for my $line (split(/\n+/, $errors)) {
309 $line = html_esc($line) if $htmlfrag;
310 $line =~ s/ /\&#160;/gs if $htmlfrag;
311 ++$cnt, $line = 'README'.$1 if $line =~ /^-(:\d+:.*)$/;
312 if ($htmlfrag) {
313 push @errs, '<tt>' . $line . '</tt>';
314 } else {
315 push @errs, $line . "\n";
318 if ($htmlfrag) {
319 return ($cnt, join("<br />\n", @errs));
320 } else {
321 return ($cnt, join("", @errs));
325 sub _properties_load {
326 my $self = shift;
327 my $setprop = sub {
328 my $propval = $self->_property_fget($_);
329 defined($propval) and $self->{$_} = $propval;
331 &$setprop foreach keys %propmap;
332 &$setprop foreach keys %propmapro;
333 do {&$setprop foreach keys %propmapromirror} if $self->{mirror};
334 $self->_readlocalconfigfile
335 unless ref($self->{configfilehash}) eq 'HASH';
336 delete $self->{auth};
337 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
338 defined($val) or $val = '';
339 chomp $val;
340 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
341 my $expire = $3;
342 if (time < $expire) {
343 $self->{authtype} = $1;
344 $self->{auth} = $2;
347 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
348 if (defined($self->{configfilehash}->{'girocco.autogchack'})) {
349 $self->{autogchack} = _boolval($self->{configfilehash}->{'girocco.autogchack'});
352 defined($self->{jsontype}) or $self->{jsontype} = "";
353 $self->{jsontype} = lc($self->{jsontype});
354 $self->{jsontype} eq 'application/x-www-form-urlencoded' || $self->{jsontype} eq 'application/json' or
355 $self->{jsontype} = 'application/x-www-form-urlencoded';
356 defined($self->{jsonsecret}) or $self->{jsonsecret} = "";
357 $self->_cleanup_datetime('lastactivity');
358 $self->_cleanup_description;
359 $self->_cleanup_readme;
360 delete $self->{configfilehash};
363 sub _set_bangagain {
364 my $self = shift;
365 my $fd;
366 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
367 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
368 if (open($fd, '>', $self->_bangagain_path)) {
369 close $fd;
370 chmod(0664, $self->_bangagain_path);
375 sub _properties_save {
376 my $self = shift;
377 delete $self->{configfilehash};
378 foreach my $prop (keys %propmap) {
379 $self->_property_fput($prop, $self->{$prop}, 1);
381 $self->_set_bangagain;
384 sub _nofetch_path {
385 my $self = shift;
386 $self->_property_path('.nofetch');
389 sub _nofetch {
390 my $self = shift;
391 my ($nofetch) = @_;
392 my $nf = $self->_nofetch_path;
393 if ($nofetch) {
394 open my $x, '>', $nf or die "nofetch failed: $!";
395 close $x;
396 } else {
397 ! -e $nf or unlink $nf or die "yesfetch failed: $!";
401 sub _banged_path {
402 my $self = shift;
403 $self->_property_path('.banged');
406 sub _bangagain_path {
407 my $self = shift;
408 $self->_property_path('.bangagain');
411 sub _gcp_path {
412 my $self = shift;
413 $self->_property_path('.gc_in_progress');
416 sub _clonelog_path {
417 my $self = shift;
418 $self->_property_path('.clonelog');
421 sub _clonefail_path {
422 my $self = shift;
423 $self->_property_path('.clone_failed');
426 sub _clonep_path {
427 my $self = shift;
428 $self->_property_path('.clone_in_progress');
431 sub _clonep {
432 my $self = shift;
433 my ($nofetch) = @_;
434 my $np = $self->_clonep_path;
435 if ($nofetch) {
436 open my $x, '>', $np or die "clonep failed: $!";
437 close $x;
438 } else {
439 unlink $np or die "clonef failed: $!";
442 sub _alternates_setup {
443 use POSIX qw(:fcntl_h);
444 my $self = shift;
445 return unless $self->{name} =~ m#/#;
446 my $forkee_name = get_forkee_name($self->{name});
447 my $forkee_path = get_forkee_path($self->{name});
448 return unless -d $forkee_path;
449 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
450 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
451 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
452 mkdir $self->{path}.'/objects/pack'; chmod 02775, $self->{path}.'/objects/pack';
454 # If somehow either our objects/pack or the prospective alternate's pack
455 # directory does not exist decline to set up any alternates
456 my $altpath = "$forkee_path/objects";
457 -d $self->{path}.'/objects/pack' && -d $altpath.'/pack' or return;
459 # If our objects/pack and the prospective alternate's pack directory
460 # do not share the same device then decline to set up any alternates
461 my ($selfdev) = stat($self->{path}.'/objects/pack');
462 my ($altdev) = stat($altpath.'/pack');
463 defined($selfdev) && defined($altdev) && $selfdev ne "" && $altdev ne "" && $selfdev == $altdev or return;
465 # We set up both alternates and http_alternates since we cannot use
466 # relative path in alternates - that doesn't work recursively.
468 my $filename = $self->{path}.'/objects/info/alternates';
469 open my $x, '>', $filename or die "alternates failed: $!";
470 print $x "$altpath\n";
471 close $x;
472 chmod 0664, $filename or warn "cannot chmod $filename: $!";
474 if ($Girocco::Config::httppullurl) {
475 $filename = $self->{path}.'/objects/info/http-alternates';
476 open my $x, '>', $filename or die "http-alternates failed: $!";
477 my $upfork = $forkee_name;
478 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
479 close $x;
480 chmod 0664, $filename or warn "cannot chmod $filename: $!";
483 # copy lastactivity from the parent project
484 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
485 my $activity = <$x>;
486 close $x;
487 last unless $activity;
488 open $x, '>', $self->{path}.'/info/lastactivity' or last;
489 print $x $activity;
490 close $x;
491 chomp $activity;
492 $self->{'lastactivity'} = $activity;
495 # copy refs from parent project
496 my $dupout;
497 open $dupout, '>&1' or
498 die "could not dup STDOUT_FILENO: $!";
499 my $packedrefsfd = POSIX::open("$self->{path}/packed-refs", O_WRONLY|O_TRUNC|O_CREAT, 0664);
500 defined($packedrefsfd) && $packedrefsfd >= 0 or die "could not open fork's packed-refs file for writing: $!";
501 POSIX::dup2($packedrefsfd, 1) or
502 die "could not dup2 STDOUT_FILENO: $!";
503 POSIX::close($packedrefsfd);
504 my $result = system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
505 my $resultstr = $!;
506 POSIX::dup2(fileno($dupout), 1);
507 close($dupout);
508 $result == 0 or die "could not create fork's packed-refs file data: $resultstr";
509 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
511 # initialize HEAD
512 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
513 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
514 chomp $HEAD;
515 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
516 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
519 sub _set_changed {
520 my $self = shift;
521 my $fd;
522 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
525 sub _set_forkchange {
526 my $self = shift;
527 my $changedtoo = shift;
528 return unless $self->{name} =~ m#/#;
529 my $forkee_path = get_forkee_path($self->{name});
530 return unless -d $forkee_path;
531 # mark forkee as changed
532 my $fd;
533 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
534 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
535 return if -e $forkee_path.'/htmlcache/summary.forkchange';
536 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
539 sub _ctags_setup {
540 my $self = shift;
541 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
542 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
545 sub _group_add {
546 my $self = shift;
547 my ($xtra) = @_;
548 $xtra .= join(',', @{$self->{users}});
549 my $crypt = $self->{crypt};
550 defined($crypt) or $crypt = 'unknown';
551 filedb_atomic_append(jailed_file('/etc/group'),
552 join(':', $self->{name}, $crypt, '\i', $xtra));
555 sub _group_update {
556 my $self = shift;
557 my $xtra = join(',', @{$self->{users}});
558 filedb_atomic_edit(jailed_file('/etc/group'),
559 sub {
560 $_ = $_[0];
561 chomp;
562 if ($self->{name} eq (split /:/)[0]) {
563 # preserve readonly flag
564 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
565 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
566 } else {
567 return "$_\n";
573 sub _group_remove {
574 my $self = shift;
575 filedb_atomic_edit(jailed_file('/etc/group'),
576 sub {
577 $self->{name} ne (split /:/)[0] and return $_;
582 sub _hook_path {
583 my $self = shift;
584 my ($name) = @_;
585 $self->{path}.'/hooks/'.$name;
588 sub _hook_install {
589 my $self = shift;
590 my ($name) = @_;
591 my $hooksdir = $self->{path}.'/hooks';
592 my $oldmask = umask();
593 umask($oldmask & ~0070);
594 -d $hooksdir or mkdir $hooksdir or
595 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
596 umask($oldmask);
597 my $globalhooks = $Girocco::Config::reporoot . "/_global/hooks";
598 -f "$globalhooks/$name" && -r _ or die "cannot find hook $name: $!";
599 ! -e $self->_hook_path($name) || unlink($self->_hook_path($name)) && ! -e $self->_hook_path($name) or
600 die "hooks directory contains unremovable pre-existing hook $name: $!";
601 symlink("$globalhooks/$name", $self->_hook_path($name)) or
602 die "cannot create hook $name symlink: $!";
605 sub _hooks_install {
606 my $self = shift;
607 foreach my $hook ('pre-auto-gc', 'pre-receive', 'post-commit', 'post-receive', 'update') {
608 $self->_hook_install($hook);
612 # private constructor, do not use
613 sub _new {
614 my $class = shift;
615 my ($name, $base_path, $path, $orphan, $optp) = @_;
616 does_exist(\$name,1) || valid_name(\$name, $orphan, $optp) or die "refusing to create project with invalid name ($name)!";
617 $path ||= "$base_path/$name.git";
618 my $proj = { name => $name, base_path => $base_path, path => $path };
620 bless $proj, $class;
623 # public constructor #0
624 # creates a virtual project not connected to disk image
625 # you can conjure() it later to disk
626 sub ghost {
627 my $class = shift;
628 my ($name, $mirror, $orphan, $optp) = @_;
629 my $self = $class->_new($name, $Girocco::Config::reporoot, undef, $orphan, $optp);
630 $self->{users} = [];
631 $self->{mirror} = $mirror;
632 $self->{email} = $self->{orig_email} = '';
633 $self->{notifyjson} = $self->{orig_notifyjson} = '';
634 $self;
637 # public constructor #1
638 sub load {
639 my $class = shift;
640 my $name = shift || '';
642 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
643 my $r = qr/^\Q$name\E:/;
644 foreach (grep /$r/, <$fd>) {
645 chomp;
647 my $self = $class->_new($name, $Girocco::Config::reporoot);
648 (-d $self->{path} && $self->_readlocalconfigfile(1))
649 or die "invalid path (".$self->{path}.") for project ".$self->{name};
651 my (undef, $crypt, $gid, $ulist) = split /:/;
652 $gid =~ /^(\d+)$/ or next; $self->{gid} = $1;
653 { use bytes;
654 $crypt =~ /^([^:\x00-\x1F\x7F-\xFF]*)$/ or next; $self->{crypt} = $1; }
655 defined($ulist) or $ulist = '';
656 $ulist =~ /^((?:\w+(?:,\w+)*)?)$/ or next;
657 $self->{users} = [split /,/, $1];
658 $self->{HEAD} = $self->get_HEAD;
659 $self->{orig_HEAD} = $self->{HEAD};
660 $self->{orig_users} = [@{$self->{users}}];
661 $self->{mirror} = ! -e $self->_nofetch_path;
662 $self->{banged} = -e $self->_banged_path if $self->{mirror};
663 $self->{gc_in_progress} = -e $self->_gcp_path;
664 $self->{clone_in_progress} = -e $self->_clonep_path;
665 $self->{clone_logged} = -e $self->_clonelog_path;
666 $self->{clone_failed} = -e $self->_clonefail_path;
667 $self->{ccrypt} = $self->{crypt};
669 $self->_properties_load;
670 $self->{orig_email} = $self->{email};
671 $self->{orig_notifyjson} = $self->{notifyjson};
672 $self->{loaded} = 1; # indicates self was loaded from etc/group file
673 close $fd;
674 return $self;
676 close $fd;
677 undef;
680 # $proj may not be in sane state if this returns false!
681 # fields listed in %$metadata_fields that are NOT also
682 # in @Girocco::Config::project_fields are totally ignored!
683 sub cgi_fill {
684 my $self = shift;
685 my ($gcgi, $silent) = @_;
686 my $cgi = $gcgi->cgi;
687 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
688 my $field_enabled = sub {
689 defined($cgi->param($_[0])) &&
690 (!exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]}))};
692 my $pwd = $cgi->param('pwd');
693 my $pwd2 = $cgi->param('pwd2');
694 # in case passwords are disabled
695 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd2 = '';
696 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
697 $gcgi->err("Empty passwords are not permitted.");
699 if ($pwd ne '' or not $self->{crypt}) {
700 $self->{crypt} = scrypt_sha1($pwd);
702 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
703 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
706 $self->{cpwd} = $cgi->param('cpwd');
708 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
709 my $newtype = $forkee ? 'fork' : 'project';
710 length($project) <= 64
711 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
713 if ($Girocco::Config::project_owners eq 'email') {
714 $self->{email} = $gcgi->wparam('email');
715 valid_email($self->{email})
716 or $gcgi->err("Your email sure looks weird...?");
717 length($self->{email}) <= 96
718 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
721 # No setting the url unless we're either new or an existing mirror!
722 unless ($self->{loaded} && !$self->{mirror}) {
723 $self->{url} = $gcgi->wparam('url') ;
724 if ($field_enabled->('cleanmirror')) {
725 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
728 # Always validate the url if we're an existing mirror
729 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
730 # Always allow the url to be left unchanged without validation when editing
731 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
732 valid_repo_url($self->{url})
733 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
734 if ($Girocco::Config::restrict_mirror_hosts) {
735 my $mh = extract_url_hostname($self->{url});
736 is_dns_hostname($mh)
737 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
738 !is_our_hostname($mh)
739 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
743 if ($field_enabled->('desc')) {
744 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
745 length($self->{desc}) <= 1024
746 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
749 if ($field_enabled->('README')) {
750 $self->{README} = to_utf8($gcgi->wparam('README'), 1);
751 $self->_cleanup_readme;
752 length($self->{README}) <= 8192
753 or $gcgi->err("README length &gt; 8kb!");
754 my ($cnt, $err) = (0);
755 ($cnt, $err) = $self->_lint_readme if $gcgi->ok && $Girocco::Config::xmllint_readme;
756 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
759 if ($field_enabled->('hp')) {
760 $self->{hp} = $gcgi->wparam('hp');
761 if ($self->{hp}) {
762 valid_web_url($self->{hp})
763 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
767 # No mucking about with users unless we're a push project
768 if (($self->{loaded} && !$self->{mirror}) ||
769 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
770 my %users = ();
771 my @users = ();
772 foreach my $user ($cgi->multi_param('user')) {
773 if (!exists($users{$user})) {
774 $users{$user} = 1;
775 push(@users, $user) if Girocco::User::does_exist($user, 1);
778 $self->{users} = \@users;
781 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
782 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
783 my $newhead;
784 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
785 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
786 if ($newhead eq $self->{orig_HEAD} ||
787 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
788 $self->{HEAD} = $newhead;
789 } else {
790 $gcgi->err("Invalid default branch (no such ref)");
794 # schedule deletion of tags (will be committed by update() after auth)
795 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
797 if ($field_enabled->('notifymail')) {
798 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
799 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
800 $self->{notifymail} = $newaddrs;
801 } else {
802 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
804 if ($field_enabled->('reverseorder')) {
805 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
807 if ($field_enabled->('summaryonly')) {
808 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
812 if ($field_enabled->('notifytag')) {
813 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
814 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
815 $self->{notifytag} = $newaddrs;
816 } else {
817 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
821 if ($field_enabled->('notifyjson')) {
822 $self->{notifyjson} = $gcgi->wparam('notifyjson');
823 if ($self->{notifyjson}) {
824 valid_web_url($self->{notifyjson})
825 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
827 $self->{jsontype} = $gcgi->wparam('jsontype');
828 defined($self->{jsontype}) && $self->{jsontype} ne "" or
829 $self->{jsontype} = 'application/x-www-form-urlencoded';
830 $self->{jsontype} = lc($self->{jsontype});
831 unless ($self->{jsontype} eq 'application/x-www-form-urlencoded' ||
832 $self->{jsontype} eq 'application/json') {
833 if ($self->{notifyjson}) {
834 $gcgi->err("Invalid JSON Content-Type. Must be 'application/x-www-form-urlencoded' or 'application/json'.");
835 } else {
836 $self->{jsontype} = 'application/x-www-form-urlencoded';
839 $self->{jsonsecret} = $gcgi->wparam('jsonsecret');
840 my $origurl = $self->{orig_notifyjson};
841 defined($origurl) or $origurl = '';
842 $self->{notifyjson} eq $origurl ||
843 $self->{notifyjson} eq "" ||
844 Girocco::Notify::json_test_post($self) or
845 $gcgi->err("JSON notify URL failed POST test.");
848 if ($field_enabled->('notifycia')) {
849 $self->{notifycia} = $gcgi->wparam('notifycia');
850 if ($self->{notifycia}) {
851 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
852 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
856 if ($cgi->param('setstatusupdates')) {
857 my $val = $gcgi->wparam('statusupdates') || '0';
858 $self->{statusupdates} = $val ? 1 : 0;
861 $silent ? $gcgi->ok : !$gcgi->err_check;
864 sub form_defaults {
865 my $self = shift;
867 name => $self->{name},
868 email => $self->{email},
869 url => $self->{url},
870 cleanmirror => $self->{cleanmirror},
871 desc => html_esc($self->{desc}),
872 README => html_esc($self->{README}),
873 hp => $self->{hp},
874 users => $self->{users},
875 notifymail => html_esc($self->{notifymail}),
876 reverseorder => $self->{reverseorder},
877 summaryonly => $self->{summaryonly},
878 notifytag => html_esc($self->{notifytag}),
879 notifyjson => html_esc($self->{notifyjson}),
880 jsontype => html_esc($self->{jsontype}),
881 jsonsecret => html_esc($self->{jsonsecret}),
882 notifycia => html_esc($self->{notifycia}),
884 __project__ => $self
888 # return true if $enc_passwd is a match for $plain_passwd
889 my $_check_passwd_match = sub {
890 my $enc_passwd = shift;
891 my $plain_passwd = shift;
892 defined($enc_passwd) or $enc_passwd = '';
893 defined($plain_passwd) or $plain_passwd = '';
894 # $enc_passwd may be crypt or crypt_sha1
895 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
896 # It's using sha1-crypt
897 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
898 } else {
899 # It's using crypt
900 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
904 sub authenticate {
905 my $self = shift;
906 my ($gcgi) = @_;
908 $self->{ccrypt} or die "Can't authenticate against a project with no password";
909 defined($self->{cpwd}) or $self->{cpwd} = '';
910 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
911 $gcgi->err("Your admin password does not match!");
912 return 0;
914 return 1;
917 # return true if the password from the file is empty or consists of all the same
918 # character. However, if the project was NOT loaded from the group file
919 # (!self->{loaded}) then the password is never locked.
920 # This function does NOT check $Girocco::Config::project_passwords, the caller
921 # is responsible for doing so if desired. Same for $self->{email}.
922 sub is_password_locked {
923 my $self = shift;
925 $self->{loaded} or return 0;
926 my $testcrypt = $self->{ccrypt}; # The value from the group file
927 defined($testcrypt) or $testcrypt = '';
928 $testcrypt ne '' or return 1; # No password at all
929 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
930 return 0; # Not locked
933 sub _setup {
934 use POSIX qw(strftime);
935 my $self = shift;
936 my ($pushers) = @_;
937 my $fd;
939 defined($self->{path}) && $self->{path} ne "" or die "invalid setup call";
940 $self->_mkdir_forkees unless $self->{adopt};
942 my $gid;
943 $self->{adopt} || mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
944 -d $self->{path} or die "unable to setup nonexistent $self->{path}";
945 if ($Girocco::Config::owning_group) {
946 $gid = scalar(getgrnam($Girocco::Config::owning_group));
947 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
948 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
949 } else {
950 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
952 delete $ENV{GIT_OBJECT_DIRECTORY};
953 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
954 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
955 or die "git init $self->{path} failed: $?";
956 # we don't need these two, remove them (they will normally be created empty) if they exist
957 rmdir $self->{path}."/branches";
958 rmdir $self->{path}."/remotes";
959 -d $self->{path}."/info" or mkdir $self->{path}."/info"
960 or die "info directory does not exist and unable to create it: $!";
961 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
962 or die "hooks directory does not exist and unable to create it: $!";
963 # clean out any kruft that may have come in from the initial template directory
964 foreach my $cleandir (qw(hooks info)) {
965 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
966 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
967 closedir $hooksdir;
970 if ($Girocco::Config::owning_group) {
971 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
973 # hooks never world writable
974 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
975 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.compression', '5') == 0
976 or die "setting core.compression failed: $?";
977 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
978 or die "disabling core.logAllRefUpdates failed: $?";
979 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
980 or die "disabling core.ignoreCase failed: $?";
981 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.hooksPath',
982 ($Girocco::Config::localhooks ? $self->{path}."/hooks" : $Girocco::Config::reporoot . "/_global/hooks")) == 0
983 or die "setting core.hooksPath failed: $?";
984 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'extensions.preciousObjects', 'true') == 0
985 or die "setting extensions.preciousObjects failed: $?";
986 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
987 or die "enabling transfer.fsckObjects failed: $?";
988 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.unpackLimit', '1') == 0
989 or die "setting transfer.unpackLimit failed: $?";
990 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.fsckObjects', 'true') == 0
991 or die "enabling receive.fsckObjects failed: $?";
992 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
993 or die "disabling receive.denyNonFastForwards failed: $?";
994 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
995 or die "disabling receive.denyDeleteCurrent failed: $?";
996 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
997 or die "disabling receive.autogc failed: $?";
998 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
999 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
1000 or die "enabling receive.updateServerInfo failed: $?";
1001 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
1002 or die "enabling repack.writeBitmaps failed: $?";
1003 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1004 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
1005 or die "setting girocco.creationtime failed: $?";
1006 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
1007 or die "htmlcache directory does not exist and unable to create it: $!";
1008 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
1009 or die "bundles directory does not exist and unable to create it: $!";
1010 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
1011 or die "reflogs directory does not exist and unable to create it: $!";
1012 foreach my $file (qw(info/lastactivity .delaygc)) {
1013 if (open $fd, '>', $self->{path}."/".$file) {
1014 close $fd;
1015 chmod 0664, $self->{path}."/".$file;
1019 # /info must have right permissions,
1020 # and git init didn't do it for some reason.
1021 # config must have correct permissions.
1022 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
1023 # also make sure /refs, /objects and /htmlcache are correct too.
1024 my ($dmode, $dmodestr, $fmode, $fmodestr);
1025 if ($Girocco::Config::owning_group) {
1026 ($dmode, $dmodestr) = (02775, '02775');
1027 ($fmode, $fmodestr) = (0664, '0664');
1028 } else {
1029 ($dmode, $dmodestr) = (02777, '02777');
1030 ($fmode, $fmodestr) = (0666, '0666');
1032 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
1033 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
1035 foreach my $file (qw(config)) {
1036 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
1038 # these ones are probably not strictly required but are nice to have
1039 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
1040 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
1041 chmod($dmode, $self->{path}."/$dir");
1043 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::htmlcache_owning_group) {
1044 my $htmlgid = scalar(getgrnam($Girocco::Config::htmlcache_owning_group));
1045 if (defined($htmlgid) && $htmlgid ne $gid) {
1046 chown(-1, $htmlgid, $self->{path}."/htmlcache") or die "chgrp $htmlgid $self->{path}/htmlcache failed: $!";
1047 chmod($dmode, $self->{path}."/htmlcache") or die "chmod $dmodestr $self->{path}/htmlcache failed: $!";
1050 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::ctags_owning_group) {
1051 my $ctagsgid = scalar(getgrnam($Girocco::Config::ctags_owning_group));
1052 if (defined($ctagsgid) && $ctagsgid ne $gid) {
1053 chown(-1, $ctagsgid, $self->{path}."/ctags") or die "chgrp $ctagsgid $self->{path}/ctags failed: $!";
1054 chmod($dmode, $self->{path}."/ctags") or die "chmod $dmodestr $self->{path}/ctags failed: $!";
1058 $self->_properties_save;
1059 $self->_alternates_setup unless $self->{noalternates} || $self->{adopt};
1060 $self->_ctags_setup;
1061 $self->_group_remove;
1062 $self->_group_add($pushers);
1063 $self->_hooks_install;
1064 $self->_update_index;
1065 $self->_set_changed;
1066 $self->_set_forkchange(1);
1069 sub premirror {
1070 my $self = shift;
1072 delete $self->{adopt};
1073 $self->_setup(':');
1074 $self->_clonep(1);
1075 if ($Girocco::Config::autogchack) {
1076 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1077 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1079 $self->perm_initialize;
1082 sub conjure {
1083 my $self = shift;
1085 delete $self->{adopt};
1086 $self->_setup;
1087 $self->_nofetch(1);
1088 if ($Girocco::Config::autogchack && $Girocco::Config::autogchack ne "mirror") {
1089 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1090 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1092 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1093 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1094 or die "create-personal-mob-area $self->{name} failed";
1096 $self->perm_initialize;
1099 sub clone {
1100 my $self = shift;
1102 unlink ($self->_clonefail_path()); # Ignore EEXIST error
1103 unlink ($self->_clonelog_path()); # Ignore EEXIST error
1105 use IO::Socket;
1106 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
1107 select((select($sock),$|=1)[0]);
1108 $sock->print("clone ".$self->{name}."\n");
1109 # Just ignore reply, we are going to succeed anyway and the I/O
1110 # would apparently get quite hairy.
1111 $sock->flush();
1112 sleep 2; # *cough*
1113 $sock->close();
1116 # call this after ghost instead of conjure or premirror+clone to adopt a pre-existing Git dir
1117 # ghost must be called with the proper value of $mirror for the to-be-adopted project
1118 # for mirrors the $proj->{url} needs to be set and for push projects the $proj->{users} array ref
1119 sub adopt {
1120 my $self = shift;
1121 my $name = $self->{name};
1123 # Sanity check first
1124 defined($name) && $name ne "" && !$self->{loaded} or return undef;
1125 does_exist($name, 1) or return undef;
1126 defined($self->{path}) && $self->{path} eq $Girocco::Config::reporoot."/$name.git" or return undef;
1127 defined($self->{base_path}) && $self->{base_path} eq $Girocco::Config::reporoot or return undef;
1128 defined($self->{email}) && defined($self->{orig_email}) && defined($self->{mirror}) && ref($self->{users}) eq 'ARRAY'
1129 or return undef;
1130 !defined(Girocco::Project->load($name)) or return undef;
1131 is_git_dir($self->{path}) or return undef;
1132 my $config = read_config_file_hash($self->{path}."/config");
1133 defined($config) && _boolval($config->{"core.bare"}) or die "refusing to adopt non-bare repository";
1134 defined(read_HEAD_symref($self->{path})) or die "refusing to adopt non-symref HEAD repository";
1136 # Adopt the project by creating a new $chroot/etc/group entry and setting up anything that's missing
1137 $self->_nofetch(!$self->{mirror});
1138 $self->{adopt} = 1;
1139 $self->_setup($self->{mirror} ? ":" : "");
1140 delete $self->{adopt};
1141 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
1142 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1143 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1145 if (!$self->{mirror} && $Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1146 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1147 or die "create-personal-mob-area $self->{name} failed";
1149 my $result = $self->perm_initialize;
1150 unlink("$self->{path}/.delaygc") unless $self->is_empty;
1151 # Pick up any pre-existing settings
1152 my $p = Girocco::Project->load($name);
1153 %$self = %$p if defined($p) && $p->{loaded};
1154 $result;
1157 sub _update_users {
1158 my $self = shift;
1160 $self->_group_update;
1161 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
1162 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
1163 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
1164 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
1167 sub update {
1168 my $self = shift;
1170 $self->_properties_save;
1171 $self->_update_users;
1173 if (exists($self->{tags_to_delete})) {
1174 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1177 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1179 $self->_update_index if $self->{email} ne $self->{orig_email};
1180 $self->{orig_email} = $self->{email};
1181 $self->_set_changed;
1186 sub update_password {
1187 my $self = shift;
1188 my ($pwd) = @_;
1190 $self->{crypt} = scrypt_sha1($pwd);
1191 $self->_group_update;
1194 # You can explicitly do this just on a ghost() repository too.
1195 sub delete {
1196 my $self = shift;
1198 if (-d $self->{path}) {
1199 system('rm', '-rf', $self->{path}) == 0
1200 or die "rm -rf $self->{path} failed: $?";
1202 # attempt to clean up any empty fork directories by removing them
1203 my @pelems = split('/', $self->{name});
1204 while (@pelems > 1) {
1205 pop @pelems;
1206 # okay to fail
1207 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1209 $self->_group_remove;
1210 $self->_update_index;
1211 $self->_set_forkchange(1);
1216 # If the project's directory actually exists archive it before deleting it
1217 # Return full path to archived project ("" if none)
1218 sub archive_and_delete {
1219 my $self = shift;
1221 unless (-d $self->{path}) {
1222 $self->delete;
1223 return "";
1226 # archive the project before deletion
1227 use POSIX qw(strftime);
1228 my $destdir = $self->{base_path};
1229 $destdir =~ s,(?<=[^/])/+$,,;
1230 $destdir .= "/_recyclebin/";
1231 $destdir .= $1 if $self->{name} =~ m,^(.*/)[^/]+$,;
1232 my $destbase = $self->{name};
1233 $destbase = $1 if $destbase =~ m,^.*/([^/]+)$,;
1234 my $oldmask = umask();
1235 umask($oldmask & ~0070);
1236 system('mkdir', '-p', $destdir) == 0 && -d $destdir
1237 or die "mkdir -p \"$destdir\" failed: $?";
1238 umask($oldmask);
1239 my $suffix = '';
1240 if (-e "$destdir$destbase.git") {
1241 $suffix = 1;
1242 while (-e "$destdir$destbase~$suffix.git") {
1243 ++$suffix;
1244 last if $suffix >= 10000; # don't get too carried away
1246 $suffix = '~'.$suffix;
1248 not -e "$destdir$destbase$suffix.git"
1249 or die "Unable to compute suitable archive path";
1250 system('mv', $self->{path}, "$destdir$destbase$suffix.git") == 0
1251 or die "mv \"$self->{path}\" \"$destdir$destbase$suffix.git\" failed: $?";
1252 if (!$self->{mirror} && @{$self->{users}}) {
1253 # Remember the user list at recycle time
1254 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1255 'config', 'girocco.recycleusers', join(",", @{$self->{users}}));
1257 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1258 my $recycletime = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1259 # We ought to do something if this fails, but the project has already been moved
1260 # so there's really nothing to be done at this point.
1261 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1262 'config', 'girocco.recycletime', $recycletime);
1264 $self->delete;
1265 return $destdir.$destbase.$suffix.".git";
1268 sub _contains_files {
1269 my $dir = shift;
1270 (-d $dir) or return 0;
1271 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1272 while (my $entry = readdir($dh)) {
1273 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1274 closedir($dh), return 1
1275 if -f "$dir/$entry" ||
1276 -d "$dir/$entry" && _contains_files("$dir/$entry");
1278 closedir($dh);
1279 return 0;
1282 sub has_forks {
1283 my $self = shift;
1285 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1288 # Returns an array of 0 or more array refs, one for each bundle:
1289 # ->[0]: bundle creation time (seconds since epoch)
1290 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1291 # ->[2]: bundle size in bytes
1292 sub bundles {
1293 my $self = shift;
1294 use Time::Local;
1296 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1297 my @blist = ();
1298 if (-d $self->{path}.'/bundles') {{
1299 my $prefix = $self->{name};
1300 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1301 opendir(my $dh, $self->{path}.'/bundles') or last;
1302 while (my $bfile = readdir($dh)) {
1303 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1304 my $ctime = eval {timegm(
1305 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1306 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4))};
1307 next unless $ctime;
1308 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1309 my $f1 = <$bh>;
1310 my $f2 = <$bh>;
1311 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1312 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1313 close($bh);
1314 next unless $f1 && $f2 && $f1 ne $f2;
1315 chomp $f1;
1316 chomp $f2;
1317 next unless -e $f1 && -e $f2;
1318 my $s1 = -s $f1 || 0;
1319 my $s2 = -s $f2 || 0;
1320 next unless $s1 || $s2;
1321 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1323 closedir($dh);
1325 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1326 my %seen = ();
1327 my @result = ();
1328 foreach my $bndl (@blist) {
1329 next if $seen{$bndl->[1]};
1330 $seen{$bndl->[1]} = 1;
1331 push(@result, $bndl);
1333 $self->{bundles} = \@result;
1334 return @result;
1337 sub has_alternates {
1338 my $self = shift;
1339 my $af = $self->{path}.'/objects/info/alternates';
1340 -f $af && -s _ or return 0;
1341 my $nb = 0;
1342 open my $fh, '<', $af or return 1;
1343 while (my $line = <$fh>) {
1344 next if $line =~ /^$/ || $line =~ /^#/;
1345 $nb = 1;
1346 last;
1348 close $fh;
1349 return $nb;
1352 sub has_bundle {
1353 my $self = shift;
1355 return scalar($self->bundles);
1358 sub _has_notifyhook {
1359 my $self = shift;
1360 my $val = $Girocco::Config::default_notifyhook;
1361 defined($self->{'notifyhook'}) and $val = $self->{'notifyhook'};
1362 return (defined($val) && $val ne "") ? $val : undef;
1365 # returns true if any of the notify fields are non-empty
1366 sub has_notify {
1367 my $self = shift;
1368 # We do not ckeck notifycia since it's defunct
1369 return
1370 $self->{'notifymail'} || $self->{'notifytag'} ||
1371 $self->{'notifyjson'} ||
1372 !!$self->_has_notifyhook;
1375 sub is_empty {
1376 # A project is considered empty if the git repository does not
1377 # have any refs. This means packed-refs does not exist or is
1378 # empty or only has lines starting with '#' AND there are no
1379 # files in the refs subdirectory hierarchy (no matter how deep).
1381 my $self = shift;
1383 (-d $self->{path}) or return 0;
1384 if (-e $self->{path}.'/packed-refs') {
1385 open(my $pr, '<', $self->{path}.'/packed-refs')
1386 or die "open $self->{path}./packed-refs failed: $!";
1387 my $foundref = 0;
1388 while (my $ref = <$pr>) {
1389 next if $ref =~ /^#/;
1390 $foundref = 1;
1391 last;
1393 close($pr);
1394 return 0 if $foundref;
1396 (-d $self->{path}.'/refs') or return 1;
1397 return !_contains_files($self->{path}.'/refs');
1400 # returns array:
1401 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1402 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1403 # Both values (if not undef) are seconds since epoch
1404 # Result only considers lastgc and min_gc_interval nothing else
1405 sub next_gc {
1406 my $self = shift;
1407 my $lastgcepoch = parse_any_date($self->{lastgc});
1408 return (undef, undef) unless defined $lastgcepoch;
1409 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1410 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1411 $Girocco::Config::min_mirror_interval));
1414 # returns boolean (0 or 1)
1415 # Attempts to determine whether or not a gc (and corresponding build
1416 # of a .bitmap/.bndl file) will actually take place at the next_gc
1417 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1418 # end up being built depends on whether or not the local object graph
1419 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1420 # is not possible because the object graph will be incomplete,
1421 # but it *is* possible that even though the repository has_alternates,
1422 # it does not actually borrow any objects so a .bitmap/.bndl will build
1423 # in spite of the presence of alternates -- but this is expected to be rare.
1424 # The result is a best guess and false return value is not an absolute
1425 # guarantee that gc will not take place at the next interval, but it probably
1426 # will not if nothing changes in the meantime.
1427 sub needs_gc {
1428 my $self = shift;
1429 my $lgc = parse_any_date($self->{lastgc});
1430 my $lrecv = parse_any_date($self->{lastreceive});
1431 my $lpgc = parse_any_date($self->{lastparentgc});
1432 return 1 unless defined($lgc) && defined($lrecv);
1433 if ($self->has_alternates) {
1434 return 1 unless defined($lpgc);
1435 return 1 unless $lpgc < $lgc;
1437 return 1 unless $lrecv < $lgc;
1438 # We don't try running any "is_dirty" check, so if somehow the
1439 # repository became dirty without updating lastreceive we might
1440 # incorrectly return false instead of true.
1441 return 0;
1444 sub delete_ctag {
1445 my $self = shift;
1446 my ($ctag) = @_;
1448 # sanity check, disallow filenames starting with . .. or /
1449 unlink($self->{path}.'/ctags/'.$ctag)
1450 unless !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1453 # returns new tag count value on success (will always be >= 1) otherwise undef
1454 sub add_ctag {
1455 my $self = shift;
1456 my $ctag = valid_tag(shift);
1457 my $nochanged = shift;
1459 # sanity check, disallow filenames starting with . .. or /
1460 return undef if !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1462 my $val = 0;
1463 my $ct;
1464 if (open $ct, '<', $self->{path}."/ctags/$ctag") {
1465 my $count = <$ct>;
1466 close $ct;
1467 defined $count or $count = '';
1468 chomp $count;
1469 $val = $count =~ /^[1-9]\d*$/ ? $count : 1;
1471 ++$val;
1472 my $oldmask = umask();
1473 umask($oldmask & ~0060);
1474 open $ct, '>', $self->{path}."/ctags/$ctag" and print $ct $val."\n" and close $ct;
1475 $self->_set_changed unless $nochanged;
1476 $self->_set_forkchange unless $nochanged;
1477 umask($oldmask);
1478 return $val;
1481 sub get_ctag_names {
1482 my $self = shift;
1483 my @ctags = ();
1484 opendir(my $dh, $self->{path}.'/ctags')
1485 or return @ctags;
1486 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1487 closedir($dh);
1488 return sort({lc($a) cmp lc($b)} @ctags);
1491 sub get_heads {
1492 my $self = shift;
1493 my $fh;
1494 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1495 defined($heads) or $heads = '';
1496 chomp $heads;
1497 my @res = ();
1498 foreach (split(/\n/, $heads)) {
1499 chomp;
1500 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1501 push @res, $1;
1503 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1504 @res;
1507 sub get_HEAD {
1508 my $self = shift;
1509 my $HEAD = read_HEAD_ref($self->{path});
1510 defined($HEAD) && $HEAD ne "" or die "could not get HEAD";
1511 return $1 if $HEAD =~ m{^refs/heads/(.+)$};
1512 return "[other]" if $HEAD =~ m{^refs/};
1513 return "[detached]" if $HEAD =~ m{^[0-9a-fA-F]{4,}$};
1514 return "[invalid]";
1517 sub set_HEAD {
1518 my $self = shift;
1519 my $newHEAD = shift;
1520 # Cursory checks only -- if you want to break your HEAD, be my guest
1521 if ($newHEAD =~ /^\/|^\.|[\x00-\x1f \x7f\[~^'<>*?\\:]|\@\{|\.\.|\.lock$|\.$|\/$/) {
1522 die "grossly invalid new HEAD: $newHEAD";
1524 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1525 die "could not set HEAD" if ($? >> 8);
1526 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1527 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1530 sub gen_auth {
1531 my $self = shift;
1532 my ($type) = @_;
1533 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1535 $self->{authtype} = $type;
1537 no warnings;
1538 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1540 my $expire = time + 24 * 3600;
1541 my $propval = "# ${type}AUTH $self->{auth} $expire";
1542 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1543 $self->{auth};
1546 sub del_auth {
1547 my $self = shift;
1549 delete $self->{auth};
1550 delete $self->{authtype};
1551 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1554 sub remove_user {
1555 my $self = shift;
1556 my ($username) = @_;
1558 my $before_count = @{$self->{users}};
1559 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1560 return @{$self->{users}} != $before_count;
1563 ### static methods
1565 sub get_forkee_name {
1566 local $_ = $_[0];
1567 (m#^(.*)/.*?$#)[0]; #
1570 sub get_forkee_path {
1571 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1572 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1573 -d $forkee ? $forkee : '';
1576 # Ultimately the full project/fork name could end up being part of a Git ref name
1577 # when a project's forks are combined into one giant repository for efficiency.
1578 # That means that the project/fork name must satisfy the Git ref name requirements:
1580 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1581 # 2. The character with an ASCII value of 0x7F is not allowed
1582 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1583 # 4. The character '/' is a separator and is not allowed within a name
1584 # 5. The name may not start with '.' or end with '.'
1585 # 6. The name may not end with '.lock'
1586 # 7. The name may not contain the '..' sequence
1587 # 8. The name may not contain the '@{' sequence
1588 # 9. If multiple components are used (separated by '/'), no empty '' components
1590 # We also prohibit a trailing '.git' on any path component and futher restrict
1591 # the allowed characters to alphanumeric and [+._-] where names must start with
1592 # an alphanumeric.
1594 sub _valid_name_characters {
1595 local $_ = $_[0];
1596 (not m#^[/+._-]#)
1597 and (not m#//#)
1598 and (not m#\.\.#)
1599 and (not m#/[+._-]#)
1600 and (not m#\./#)
1601 and (not m#\.$#)
1602 and (not m#\.git/#i)
1603 and (not m#\.git$#i)
1604 and (not m#\.idx/#i)
1605 and (not m#\.idx$#i)
1606 and (not m#\.lock/#i)
1607 and (not m#\.lock$#i)
1608 and (not m#\.pack/#i)
1609 and (not m#\.pack$#i)
1610 and (not m#\.bundle/#i)
1611 and (not m#\.bundle$#i)
1612 and (not m#/$#)
1613 and (not m/^[a-fA-F0-9]{38}$/)
1614 and m#^[a-zA-Z0-9/+._-]+$#
1615 and !has_reserved_suffix($_, $_[1], $_[2]);
1618 # $_[0] => prospective project name (WITHOUT trailing .git)
1619 # $_[1] => true to allow orphans (i.e. two-or-more-level-deep projects without a parent)
1620 # (the directory in which the orphan will be created must, however, already exist)
1621 # $_[2] => true to allow orphans w/o needed directory if $_[1] also true (like mkdir -p)
1622 # If $_[0] is a SCALAR ref, ${$_[0]} contains the name and will be untainted on success.
1623 sub valid_name {
1624 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1625 local $_ = $_[0];
1626 my $mayberef_name = $_;
1627 ref($_) eq 'SCALAR' and $_ = $$_;
1628 my $rv = (
1629 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1630 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1631 and ((not m#/#) or -d get_forkee_path($_) or ($_[1] and ($_[2] or -d $Girocco::Config::reporoot.'/'.get_forkee_name($_))))
1632 and (! -f $Girocco::Config::reporoot."/$_.git")
1634 $rv && ref($mayberef_name) eq 'SCALAR' && m|^(.+)$| and $$mayberef_name = $1;
1635 return $rv;
1638 # It's possible that some forks have been kept but the forkee is gone.
1639 # In this case the standard valid_name check is too strict.
1640 # If $_[0] is a SCALAR ref, ${$_[0]} contains the name and will be untainted on success.
1641 sub does_exist {
1642 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1643 my ($mayberef_name, $nodie) = @_;
1644 my $name = ref($mayberef_name) eq 'SCALAR' ? $$mayberef_name : $mayberef_name;
1645 my $okay = (
1646 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1647 and ((not $name =~ m#/#)
1648 or -d get_forkee_path($name)
1649 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1650 (!$okay && $nodie) and return undef;
1651 !$okay and die "tried to query for project with invalid name $name!";
1652 -d $Girocco::Config::reporoot."/$name.git" or return undef;
1653 ref($mayberef_name) eq 'SCALAR' && $name =~ m|^(.+)$| and $$mayberef_name = $1;
1654 return 1;
1657 sub get_full_list {
1658 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1659 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1660 close $fd;
1661 @projects;