readme: allow non-HTML formats
[girocco.git] / Girocco / Project.pm
blob2429fea14c460d6a12f622ac2353688f1874d8d8
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 => [
45 ['README Format', 'rmtype', 'select', 'Format of README data entered here', \&_rmtype_choices],
46 ['<span style="display:inline-block;vertical-align:top">'.
47 'README (&lt; 8 KiB)<br />leave blank for automatic</span>',
48 'README', 'textarea', 'Enter only &#x201c;<!-- comments -->&#x201d; '.
49 'to completely suppress any README']],
50 notifymail => ['Commit notify &#x2013; mail to', 'notifymail', 'text',
51 'comma separated address list'],
52 reverseorder => ['Show oldest first', 'reverseorder', 'checkbox',
53 'show new revisions in oldest to newest order (instead of the default newest to oldest older)'.
54 ' in &#x201c;Commit notify&#x201d; email when showing new revisions'],
55 summaryonly => ['Summaries only', 'summaryonly', 'checkbox',
56 'suppress patch/diff output in &#x201c;Commit notify&#x201d; email when showing new revisions'],
57 notifytag => ['Tag notify &#x2013; mail to', 'notifytag', 'text',
58 'comma separated address list &#x2013; if not empty, tag '.
59 'notifications are sent here INSTEAD of to '.
60 '&#x201c;Commit notify &#x2013; mail to&#x201d; address(es)'],
61 notifyjson => [
62 ['Commit notify &#x2013; '.
63 '<a title="'.html_esc('single field name is &#x201c;payload&#x201d;', 1).'" href="'.
64 'https://docs.github.com/developers/webhooks-and-events/webhook-events-and-payloads#push'.
65 '">POST JSON</a> at', 'notifyjson', 'text'],
66 ['JSON Content-Type', 'jsontype', 'select', 'JSON POST Content-Type', \&_json_choices],
67 ['JSON Secret', 'jsonsecret', 'text', 'secret used to compute JSON POST signatures']],
68 notifycia => ['Commit notify &#x2013; <a href="http://cia.vc/doc/">CIA project</a> name',
69 'notifycia', 'text', 'CIA is defunct &#x2013; this value is ignored'],
72 sub _rmtype_choices {
73 return ('Markdown', 'Plain Text', 'HTML');
76 sub _json_choices {
77 return ('application/x-www-form-urlencoded', 'application/json');
80 sub _mkdir_forkees {
81 my $self = shift;
82 my @pelems = split('/', $self->{name});
83 pop @pelems; # do not create dir for the project itself
84 my $path = $self->{base_path};
85 foreach my $pelem (@pelems) {
86 $path .= "/$pelem";
87 (-d "$path") or mkdir $path or die "mkdir $path: $!";
88 chmod 02775, $path; # ok if fails (dir may already exist and be owned by someone else)
92 # With a leading ':' get from project local config replacing ':' with 'gitweb.'
93 # With a leading '%' get from project local config after removing '%'
94 # With a leading '!' get boolean from project local config after removing '!' (prefixed with 'gitweb.' if no '.')
95 # With a leading [:%!] a trailing ':defval' may be added to select the default value to use if unset
96 # Otherwise it's a project file name to be loaded
97 # %propmapro entries are loaded but never written
98 # %propmapromirror entries are loaded only for mirrors but never written
100 our %propmap = (
101 url => ':baseurl',
102 email => ':owner',
103 desc => 'description',
104 README => 'README.html',
105 READMEDATA => 'README.dat',
106 rmtype => '%girocco.readmetype',
107 hp => ':homepage',
108 notifymail => '%hooks.mailinglist',
109 notifytag => '%hooks.announcelist',
110 notifyjson => '%hooks.jsonurl',
111 jsontype => '%hooks.jsontype',
112 jsonsecret => '%hooks.jsonsecret',
113 notifycia => '%hooks.cianame',
114 cleanmirror => '!girocco.cleanmirror',
115 statusupdates => '!statusupdates:1',
116 reverseorder => '!hooks.reverseorder',
117 summaryonly => '!hooks.summaryonly',
120 our %propmapro = (
121 lastchange => ':lastchange',
122 lastactivity => 'info/lastactivity',
123 lastgc => ':lastgc',
124 lastreceive => ':lastreceive',
125 lastparentgc => ':lastparentgc',
126 lastrefresh => ':lastrefresh',
127 creationtime => '%girocco.creationtime',
128 reposizek => '%girocco.reposizek',
129 notifyhook => '%girocco.notifyhook:undef',
130 origurl => ':baseurl',
133 our %propmapromirror = (
134 bangcount => '%girocco.bang.count',
135 bangfirstfail => '%girocco.bang.firstfail',
136 bangmessagesent => '!girocco.bang.messagesent',
137 showpush => '!showpush',
140 # Projects with any of these names will be disallowed to avoid possible
141 # collisions with cgi script paths or chroot paths
142 # NOTE: names are checked after using lc on them, so all entries MUST be lowercase
143 our %reservedprojectnames = (
144 admin => 1, # /admin/ links
145 alternates => 1, # .git/objects/info/alternates
146 b => 1, # /b/ -> bundle.cgi
147 blog => 1, # /blog/ links
148 c => 1, # /c/ -> cgit
149 'git-receive-pack' => 1, # smart HTTP
150 'git-upload-archive' => 1, # smart HTTP
151 'git-upload-pack' => 1, # smart HTTP
152 h => 1, # /h/ -> html.cgi
153 head => 1, # .git/HEAD
154 'http-alternates' => 1, # .git/objects/info/http-alternates
155 info => 1, # .git/info
156 objects => 1, # .git/objects
157 packs => 1, # .git/objects/info/packs
158 r => 1, # /r/ -> git http
159 refs => 1, # .git/refs
160 w => 1, # /w/ -> gitweb
161 wiki => 1, # /wiki/ links
162 srv => 1, # /srv/git/ -> chroot ssh git repositories
165 sub _update_index {
166 my $self = shift;
167 system("$Girocco::Config::basedir/gitweb/genindex.sh", $self->{name});
170 sub _readlocalconfigfile {
171 my $self = shift;
172 my $undefonerr = shift || 0;
173 delete $self->{configfilehash};
174 my $confighash = read_config_file_hash($self->{path} . "/config");
175 my $result = 1;
176 defined($confighash) || $undefonerr or $result = 0, $confighash = {};
177 return undef unless defined($confighash);
178 $self->{configfilehash} = $confighash;
179 return $result;
182 # @_[0]: argument to convert to boolean result (0 or 1)
183 # @_[1]: value to use if argument is undef (default is 0)
184 # Returns 0 or 1
185 sub _boolval {
186 my ($val, $def) = @_;
187 defined($def) or $def = 0;
188 defined($val) or $val = $def;
189 $val =~ s/\s+//gs;
190 $val = lc($val);
191 return 0 if $val eq '' || $val eq 'false' || $val eq 'off' || $val eq 'no' || $val =~ /^[-+]?0+$/;
192 return 1;
195 sub _property_path {
196 my $self = shift;
197 my ($name) = @_;
198 $self->{path}.'/'.$name;
201 sub _property_fget {
202 my $self = shift;
203 my ($name, $nodef) = @_;
204 my $pname = $propmap{$name};
205 $pname = $propmapro{$name} unless $pname;
206 $pname = $propmapromirror{$name} unless $pname;
207 $pname or die "unknown property: $name";
208 if ($pname =~ /^([:%!])([^:]+)(:.*)?$/) {
209 my ($where, $pname, $defval) = ($1, lc($2), substr(($3||":"),1));
210 $defval = undef if $defval eq "undef";
211 $defval = '' if $nodef;
212 $self->_readlocalconfigfile
213 unless ref($self->{configfilehash}) eq 'HASH';
214 $pname = "gitweb." . $pname if $where eq ':' or $where eq '!' && $pname !~ /[.]/;
215 my $val = $self->{configfilehash}->{$pname};
216 defined($val) or $val = $defval;
217 chomp $val if defined($val);
218 $val = _boolval($val, $defval) if $where eq '!';
219 return $nodef && !exists($self->{configfilehash}->{$pname}) ? undef : $val;
222 open my $p, '<', $self->_property_path($pname) or return undef;
223 my @value = <$p>;
224 close $p;
225 my $value = join('', @value); chomp $value;
226 $value;
229 sub _prop_is_same {
230 my $self = shift;
231 my ($name, $value) = @_;
232 my $existing = $self->_property_fget($name, 1);
233 defined($value) or $value = '';
234 return defined($existing) && $existing eq $value;
237 sub _property_fput {
238 my $self = shift;
239 my ($name, $value, $nosetsame) = @_;
240 my $pname = $propmap{$name};
241 $pname or die "unknown property: $name";
242 my $defval = '';
243 ($pname, $defval) = ($1, substr(($2||":"),1)) if $pname =~ /^([:%!][^:]+)(:.*)?$/;
244 defined($value) or $value = $defval;
245 if ($pname =~ s/^://) {
246 return if $nosetsame && $self->_prop_is_same($name, $value);
247 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
248 return;
249 } elsif ($pname =~ s/^%//) {
250 return if $nosetsame && $self->_prop_is_same($name, $value);
251 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
252 return;
253 } elsif ($pname =~ s/^!//) {
254 $pname = "gitweb." . $pname unless $pname =~ /[.]/;
255 $value = _boolval($value, $defval);
256 return if $nosetsame && $self->_prop_is_same($name, $value);
257 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool', $pname, $value);
258 return;
261 my $P = lock_file($self->_property_path($pname));
262 chomp $value;
263 $value ne '' and print $P "$value\n";
264 close $P;
265 unlock_file($self->_property_path($pname));
268 sub _cleanup_datetime {
269 my $self = shift;
270 my $k = shift;
271 defined($k) && $k ne "" or return;
272 local $_ = $self->{$k}; defined($_) or $_ = '';
273 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
274 s/\s+/ /gs;
275 s/^\s+//s;
276 s/\s+$//s;
277 my $ts = parse_any_date($_);
278 defined($ts) or $_ = '';
279 /^(.*)$/ and $self->{$k} = $1;
282 sub _cleanup_description {
283 my $self = shift;
284 local $_ = $self->{desc}; defined($_) or $_ = '';
285 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
286 s/\r\n?/\n/gs;
287 s/^\s+//s;
288 s/\s+$//s;
289 /\A(.*)$/m and $self->{desc} = $1;
292 sub _cleanup_readme_str {
293 local $_ = shift; defined($_) or $_ = '';
294 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
295 s/\r\n?/\n/gs;
296 s/^\s+//s;
297 s/\s+$//s;
298 $_ eq '' or $_ .= "\n";
299 /^(.*)$/s and $_ = $1;
300 return $_;
303 sub _cleanup_readme {
304 my $self = shift;
305 $self->{README} = _cleanup_readme_str($self->{README});
306 $self->{READMEDATA} = _cleanup_readme_str($self->{READMEDATA});
309 my %rmtypes;
310 BEGIN { %rmtypes = (
311 default => 'Markdown',
312 markdown => 'Markdown',
313 'plain text' => 'Plain Text',
314 plain => 'Plain Text',
315 text => 'Plain Text',
316 html => 'HTML'
319 sub _lint_readme {
320 my $self = shift;
321 my $htmlfrag = shift;
322 defined($htmlfrag) or $htmlfrag = 1;
323 defined($self->{READMEDATA}) or $self->{READMEDATA} = '';
324 my $rmtype = $rmtypes{lc($self->{rmtype} || '')};
325 defined($rmtype) && $rmtype ne '' or $rmtype = $rmtypes{'default'};
326 $self->{rmtype} = $rmtype;
327 # Empty always just becomes empty with no errors
328 if ($self->{READMEDATA} eq '') {
329 $self->{README} = '';
330 return 0;
332 if ($rmtype eq 'Plain Text') {
333 # Never any errors with this one
334 my $esc = $self->{READMEDATA};
335 $esc =~ s/&/&amp;/gs;
336 $esc =~ s/</&lt;/gs;
337 $self->{README} = '<pre class="plaintext">' . $esc . '</pre>';
338 return 0;
340 eval { require Markdown; 1 } or do {
341 return (1, "README: Markdown/HTML formats temporarily unavailable");
343 my @errs = ();
344 if ($rmtype eq 'HTML') {
345 # Legacy HTML support but now sanitized with possible auto-fixup
346 my $output;
347 eval { $output = Markdown::ProcessRaw($self->{READMEDATA},
348 sanitize => 1, xmlcheck => 2, htmlauto => 0); 1; } or
349 do {
350 @errs = split(/\n+/, $@);
351 @errs or push(@errs, 'Invalid HTML');
353 # Make one more attempt with htmlauto in case
354 # that's good enough to fix up the HTML and make it valid
355 eval { $output = Markdown::ProcessRaw($self->{READMEDATA},
356 sanitize => 1, xmlcheck => 2, htmlauto => 1); 1; } and
357 do {
358 @errs = ();
361 !@errs and $self->{README} = (chomp($output),$output);
362 } else {
363 # Markdown format
364 my $output;
365 my $gwbase = url_path($Girocco::Config::gitweburl,1).$self->{name}.'.git';
366 my %mdopts = (
367 sanitize => 1,
368 xmlcheck => 2,
369 yamlmode => 1,
370 yamlvis => 0,
371 keepabs => 1,
372 base_prefix => $self->{name}.'.git',
373 url_prefix => $gwbase . '/blob/HEAD:',
374 img_prefix => $gwbase . '/blob_plain/HEAD:'
376 eval { $output = Markdown::Markdown($self->{READMEDATA}, %mdopts); 1; } or
377 do {
378 @errs = split(/\n+/, $@);
379 @errs or push(@errs, 'Invalid Markdown');
381 !@errs and $self->{README} = (chomp($output),$output);
383 return 0 unless @errs;
384 my @fmterrs = ();
385 foreach (@errs) {
386 $_ = html_esc($_) if $htmlfrag;
387 s/ /\&#160;/gs if $htmlfrag;
388 if ($htmlfrag) {
389 push @fmterrs, 'README: <tt>' . $_ . '</tt>';
390 } else {
391 push @fmterrs, 'README: ' . $_ . "\n";
394 if ($htmlfrag) {
395 return (scalar(@fmterrs), join("<br />\n", @fmterrs));
396 } else {
397 return (scalar(@fmterrs), join("", @fmterrs));
401 sub _properties_load {
402 my $self = shift;
403 my $setprop = sub {
404 my $propval = $self->_property_fget($_);
405 defined($propval) and $self->{$_} = $propval;
407 &$setprop foreach keys %propmap;
408 &$setprop foreach keys %propmapro;
409 do {&$setprop foreach keys %propmapromirror} if $self->{mirror};
410 $self->_readlocalconfigfile
411 unless ref($self->{configfilehash}) eq 'HASH';
412 delete $self->{auth};
413 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
414 defined($val) or $val = '';
415 chomp $val;
416 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
417 my $expire = $3;
418 if (time < $expire) {
419 $self->{authtype} = $1;
420 $self->{auth} = $2;
423 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
424 if (defined($self->{configfilehash}->{'girocco.autogchack'})) {
425 $self->{autogchack} = _boolval($self->{configfilehash}->{'girocco.autogchack'});
428 defined($self->{jsontype}) or $self->{jsontype} = "";
429 $self->{jsontype} = lc($self->{jsontype});
430 $self->{jsontype} eq 'application/x-www-form-urlencoded' || $self->{jsontype} eq 'application/json' or
431 $self->{jsontype} = 'application/x-www-form-urlencoded';
432 defined($self->{jsonsecret}) or $self->{jsonsecret} = "";
433 $self->_cleanup_datetime('lastactivity');
434 $self->_cleanup_description;
435 $self->_cleanup_readme;
436 defined($self->{rmtype}) and $self->{rmtype} = $rmtypes{lc($self->{rmtype})};
437 defined($self->{rmtype}) or $self->{rmtype} = "";
438 if (!$self->{rmtype}) {
439 # default type is "Markdown" unless README ne '' but READMEDATA eq ''
440 if ($self->{README} ne '' && $self->{READMEDATA} eq '') {
441 # This was the only previously understood format
442 $self->{rmtype} = 'HTML';
443 $self->{READMEDATA} = $self->{README};
444 } else {
445 $self->{rmtype} = $rmtypes{'default'};
448 delete $self->{configfilehash};
451 sub _set_bangagain {
452 my $self = shift;
453 my $fd;
454 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
455 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
456 if (open($fd, '>', $self->_bangagain_path)) {
457 close $fd;
458 chmod(0664, $self->_bangagain_path);
463 sub _properties_save {
464 my $self = shift;
465 delete $self->{configfilehash};
466 foreach my $prop (keys %propmap) {
467 $self->_property_fput($prop, $self->{$prop}, 1);
469 $self->_set_bangagain;
472 sub _nofetch_path {
473 my $self = shift;
474 $self->_property_path('.nofetch');
477 sub _nofetch {
478 my $self = shift;
479 my ($nofetch) = @_;
480 my $nf = $self->_nofetch_path;
481 if ($nofetch) {
482 open my $x, '>', $nf or die "nofetch failed: $!";
483 close $x;
484 } else {
485 ! -e $nf or unlink $nf or die "yesfetch failed: $!";
489 sub _banged_path {
490 my $self = shift;
491 $self->_property_path('.banged');
494 sub _bangagain_path {
495 my $self = shift;
496 $self->_property_path('.bangagain');
499 sub _gcp_path {
500 my $self = shift;
501 $self->_property_path('.gc_in_progress');
504 sub _clonelog_path {
505 my $self = shift;
506 $self->_property_path('.clonelog');
509 sub _clonefail_path {
510 my $self = shift;
511 $self->_property_path('.clone_failed');
514 sub _clonep_path {
515 my $self = shift;
516 $self->_property_path('.clone_in_progress');
519 sub _clonep {
520 my $self = shift;
521 my ($nofetch) = @_;
522 my $np = $self->_clonep_path;
523 if ($nofetch) {
524 open my $x, '>', $np or die "clonep failed: $!";
525 close $x;
526 } else {
527 unlink $np or die "clonef failed: $!";
530 sub _alternates_setup {
531 use POSIX qw(:fcntl_h);
532 my $self = shift;
533 return unless $self->{name} =~ m#/#;
534 my $forkee_name = get_forkee_name($self->{name});
535 my $forkee_path = get_forkee_path($self->{name});
536 return unless -d $forkee_path;
537 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
538 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
539 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
540 mkdir $self->{path}.'/objects/pack'; chmod 02775, $self->{path}.'/objects/pack';
542 # If somehow either our objects/pack or the prospective alternate's pack
543 # directory does not exist decline to set up any alternates
544 my $altpath = "$forkee_path/objects";
545 -d $self->{path}.'/objects/pack' && -d $altpath.'/pack' or return;
547 # If our objects/pack and the prospective alternate's pack directory
548 # do not share the same device then decline to set up any alternates
549 my ($selfdev) = stat($self->{path}.'/objects/pack');
550 my ($altdev) = stat($altpath.'/pack');
551 defined($selfdev) && defined($altdev) && $selfdev ne "" && $altdev ne "" && $selfdev == $altdev or return;
553 # We set up both alternates and http_alternates since we cannot use
554 # relative path in alternates - that doesn't work recursively.
556 my $filename = $self->{path}.'/objects/info/alternates';
557 open my $x, '>', $filename or die "alternates failed: $!";
558 print $x "$altpath\n";
559 close $x;
560 chmod 0664, $filename or warn "cannot chmod $filename: $!";
562 if ($Girocco::Config::httppullurl) {
563 $filename = $self->{path}.'/objects/info/http-alternates';
564 open my $x, '>', $filename or die "http-alternates failed: $!";
565 my $upfork = $forkee_name;
566 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
567 close $x;
568 chmod 0664, $filename or warn "cannot chmod $filename: $!";
571 # copy lastactivity from the parent project
572 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
573 my $activity = <$x>;
574 close $x;
575 last unless $activity;
576 open $x, '>', $self->{path}.'/info/lastactivity' or last;
577 print $x $activity;
578 close $x;
579 chomp $activity;
580 $self->{'lastactivity'} = $activity;
583 # copy refs from parent project
584 my $dupout;
585 open $dupout, '>&1' or
586 die "could not dup STDOUT_FILENO: $!";
587 my $packedrefsfd = POSIX::open("$self->{path}/packed-refs", O_WRONLY|O_TRUNC|O_CREAT, 0664);
588 defined($packedrefsfd) && $packedrefsfd >= 0 or die "could not open fork's packed-refs file for writing: $!";
589 POSIX::dup2($packedrefsfd, 1) or
590 die "could not dup2 STDOUT_FILENO: $!";
591 POSIX::close($packedrefsfd);
592 my $result = system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
593 my $resultstr = $!;
594 POSIX::dup2(fileno($dupout), 1);
595 close($dupout);
596 $result == 0 or die "could not create fork's packed-refs file data: $resultstr";
597 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
599 # initialize HEAD
600 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
601 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
602 chomp $HEAD;
603 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
604 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
607 sub _set_changed {
608 my $self = shift;
609 my $fd;
610 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
613 sub _set_forkchange {
614 my $self = shift;
615 my $changedtoo = shift;
616 return unless $self->{name} =~ m#/#;
617 my $forkee_path = get_forkee_path($self->{name});
618 return unless -d $forkee_path;
619 # mark forkee as changed
620 my $fd;
621 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
622 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
623 return if -e $forkee_path.'/htmlcache/summary.forkchange';
624 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
627 sub _ctags_setup {
628 my $self = shift;
629 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
630 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
633 sub _group_add {
634 my $self = shift;
635 my ($xtra) = @_;
636 $xtra .= join(',', @{$self->{users}});
637 my $crypt = $self->{crypt};
638 defined($crypt) or $crypt = 'unknown';
639 filedb_atomic_append(jailed_file('/etc/group'),
640 join(':', $self->{name}, $crypt, '\i', $xtra));
643 sub _group_update {
644 my $self = shift;
645 my $xtra = join(',', @{$self->{users}});
646 filedb_atomic_edit(jailed_file('/etc/group'),
647 sub {
648 $_ = $_[0];
649 chomp;
650 if ($self->{name} eq (split /:/)[0]) {
651 # preserve readonly flag
652 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
653 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
654 } else {
655 return "$_\n";
661 sub _group_remove {
662 my $self = shift;
663 filedb_atomic_edit(jailed_file('/etc/group'),
664 sub {
665 $self->{name} ne (split /:/)[0] and return $_;
670 sub _hook_path {
671 my $self = shift;
672 my ($name) = @_;
673 $self->{path}.'/hooks/'.$name;
676 sub _hook_install {
677 my $self = shift;
678 my ($name) = @_;
679 my $hooksdir = $self->{path}.'/hooks';
680 my $oldmask = umask();
681 umask($oldmask & ~0070);
682 -d $hooksdir or mkdir $hooksdir or
683 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
684 umask($oldmask);
685 my $globalhooks = $Girocco::Config::reporoot . "/_global/hooks";
686 -f "$globalhooks/$name" && -r _ or die "cannot find hook $name: $!";
687 ! -e $self->_hook_path($name) || unlink($self->_hook_path($name)) && ! -e $self->_hook_path($name) or
688 die "hooks directory contains unremovable pre-existing hook $name: $!";
689 symlink("$globalhooks/$name", $self->_hook_path($name)) or
690 die "cannot create hook $name symlink: $!";
693 sub _hooks_install {
694 my $self = shift;
695 foreach my $hook ('pre-auto-gc', 'pre-receive', 'post-commit', 'post-receive', 'update') {
696 $self->_hook_install($hook);
700 # private constructor, do not use
701 sub _new {
702 my $class = shift;
703 my ($name, $base_path, $path, $orphan, $optp) = @_;
704 does_exist(\$name,1) || valid_name(\$name, $orphan, $optp) or die "refusing to create project with invalid name ($name)!";
705 $path ||= "$base_path/$name.git";
706 my $proj = { name => $name, base_path => $base_path, path => $path };
708 bless $proj, $class;
711 # public constructor #0
712 # creates a virtual project not connected to disk image
713 # you can conjure() it later to disk
714 sub ghost {
715 my $class = shift;
716 my ($name, $mirror, $orphan, $optp) = @_;
717 my $self = $class->_new($name, $Girocco::Config::reporoot, undef, $orphan, $optp);
718 $self->{users} = [];
719 $self->{mirror} = $mirror;
720 $self->{email} = $self->{orig_email} = '';
721 $self->{notifyjson} = $self->{orig_notifyjson} = '';
722 $self;
725 # public constructor #1
726 sub load {
727 my $class = shift;
728 my $name = shift || '';
730 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
731 my $r = qr/^\Q$name\E:/;
732 foreach (grep /$r/, <$fd>) {
733 chomp;
735 my $self = $class->_new($name, $Girocco::Config::reporoot);
736 (-d $self->{path} && $self->_readlocalconfigfile(1))
737 or die "invalid path (".$self->{path}.") for project ".$self->{name};
739 my (undef, $crypt, $gid, $ulist) = split /:/;
740 $gid =~ /^(\d+)$/ or next; $self->{gid} = $1;
741 { use bytes;
742 $crypt =~ /^([^:\x00-\x1F\x7F-\xFF]*)$/ or next; $self->{crypt} = $1; }
743 defined($ulist) or $ulist = '';
744 $ulist =~ /^((?:\w+(?:,\w+)*)?)$/ or next;
745 $self->{users} = [split /,/, $1];
746 $self->{HEAD} = $self->get_HEAD;
747 $self->{orig_HEAD} = $self->{HEAD};
748 $self->{orig_users} = [@{$self->{users}}];
749 $self->{mirror} = ! -e $self->_nofetch_path;
750 $self->{banged} = -e $self->_banged_path if $self->{mirror};
751 $self->{gc_in_progress} = -e $self->_gcp_path;
752 $self->{clone_in_progress} = -e $self->_clonep_path;
753 $self->{clone_logged} = -e $self->_clonelog_path;
754 $self->{clone_failed} = -e $self->_clonefail_path;
755 $self->{ccrypt} = $self->{crypt};
757 $self->_properties_load;
758 $self->{orig_email} = $self->{email};
759 $self->{orig_notifyjson} = $self->{notifyjson};
760 $self->{loaded} = 1; # indicates self was loaded from etc/group file
761 close $fd;
762 return $self;
764 close $fd;
765 undef;
768 # $proj may not be in sane state if this returns false!
769 # fields listed in %$metadata_fields that are NOT also
770 # in @Girocco::Config::project_fields are totally ignored!
771 sub cgi_fill {
772 my $self = shift;
773 my ($gcgi, $silent) = @_;
774 my $cgi = $gcgi->cgi;
775 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
776 my $field_enabled = sub {
777 defined($cgi->param($_[0])) &&
778 (!exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]}))};
780 my $pwd = $cgi->param('pwd');
781 my $pwd2 = $cgi->param('pwd2');
782 # in case passwords are disabled
783 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd2 = '';
784 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
785 $gcgi->err("Empty passwords are not permitted.");
787 if ($pwd ne '' or not $self->{crypt}) {
788 $self->{crypt} = scrypt_sha1($pwd);
790 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
791 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
794 $self->{cpwd} = $cgi->param('cpwd');
796 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
797 my $newtype = $forkee ? 'fork' : 'project';
798 length($project) <= 64
799 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
801 if ($Girocco::Config::project_owners eq 'email') {
802 $self->{email} = $gcgi->wparam('email');
803 valid_email($self->{email})
804 or $gcgi->err("Your email sure looks weird...?");
805 length($self->{email}) <= 96
806 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
809 # No setting the url unless we're either new or an existing mirror!
810 unless ($self->{loaded} && !$self->{mirror}) {
811 $self->{url} = $gcgi->wparam('url') ;
812 if ($field_enabled->('cleanmirror')) {
813 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
816 # Always validate the url if we're an existing mirror
817 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
818 # Always allow the url to be left unchanged without validation when editing
819 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
820 valid_repo_url($self->{url})
821 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
822 if ($Girocco::Config::restrict_mirror_hosts) {
823 my $mh = extract_url_hostname($self->{url});
824 is_dns_hostname($mh)
825 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
826 !is_our_hostname($mh)
827 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
831 if ($field_enabled->('desc')) {
832 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
833 length($self->{desc}) <= 1024
834 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
837 if ($field_enabled->('README')) {
838 $self->{rmtype} = $rmtypes{lc($gcgi->wparam('rmtype')||'')};
839 if (!$self->{rmtype}) {
840 $gcgi->err("Invalid README Format. Must be 'Markdown', 'Plain Text' or 'HTML'.");
841 $self->{rmtype} = 'Markdown';
843 $self->{READMEDATA} = _cleanup_readme_str(to_utf8($gcgi->wparam('README'), 1));
844 length($self->{READMEDATA}) <= 8192
845 or $gcgi->err("README length &gt; 8kb!");
846 my ($cnt, $err) = (0);
847 ($cnt, $err) = $self->_lint_readme if $gcgi->ok;
848 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
851 if ($field_enabled->('hp')) {
852 $self->{hp} = $gcgi->wparam('hp');
853 if ($self->{hp}) {
854 valid_web_url($self->{hp})
855 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
859 # No mucking about with users unless we're a push project
860 if (($self->{loaded} && !$self->{mirror}) ||
861 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
862 my %users = ();
863 my @users = ();
864 foreach my $user ($cgi->multi_param('user')) {
865 if (!exists($users{$user})) {
866 $users{$user} = 1;
867 push(@users, $user) if Girocco::User::does_exist($user, 1);
870 $self->{users} = \@users;
873 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
874 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
875 my $newhead;
876 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
877 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
878 if ($newhead eq $self->{orig_HEAD} ||
879 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
880 $self->{HEAD} = $newhead;
881 } else {
882 $gcgi->err("Invalid default branch (no such ref)");
886 # schedule deletion of tags (will be committed by update() after auth)
887 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
889 if ($field_enabled->('notifymail')) {
890 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
891 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
892 $self->{notifymail} = $newaddrs;
893 } else {
894 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
896 if ($field_enabled->('reverseorder')) {
897 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
899 if ($field_enabled->('summaryonly')) {
900 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
904 if ($field_enabled->('notifytag')) {
905 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
906 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
907 $self->{notifytag} = $newaddrs;
908 } else {
909 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
913 if ($field_enabled->('notifyjson')) {
914 $self->{notifyjson} = $gcgi->wparam('notifyjson');
915 if ($self->{notifyjson}) {
916 valid_web_url($self->{notifyjson})
917 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
919 $self->{jsontype} = $gcgi->wparam('jsontype');
920 defined($self->{jsontype}) && $self->{jsontype} ne "" or
921 $self->{jsontype} = 'application/x-www-form-urlencoded';
922 $self->{jsontype} = lc($self->{jsontype});
923 unless ($self->{jsontype} eq 'application/x-www-form-urlencoded' ||
924 $self->{jsontype} eq 'application/json') {
925 if ($self->{notifyjson}) {
926 $gcgi->err("Invalid JSON Content-Type. Must be 'application/x-www-form-urlencoded' or 'application/json'.");
927 } else {
928 $self->{jsontype} = 'application/x-www-form-urlencoded';
931 $self->{jsonsecret} = $gcgi->wparam('jsonsecret');
932 my $origurl = $self->{orig_notifyjson};
933 defined($origurl) or $origurl = '';
934 $self->{notifyjson} eq $origurl ||
935 $self->{notifyjson} eq "" ||
936 Girocco::Notify::json_test_post($self) or
937 $gcgi->err("JSON notify URL failed POST test.");
940 if ($field_enabled->('notifycia')) {
941 $self->{notifycia} = $gcgi->wparam('notifycia');
942 if ($self->{notifycia}) {
943 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
944 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
948 if ($cgi->param('setstatusupdates')) {
949 my $val = $gcgi->wparam('statusupdates') || '0';
950 $self->{statusupdates} = $val ? 1 : 0;
953 $silent ? $gcgi->ok : !$gcgi->err_check;
956 sub form_defaults {
957 my $self = shift;
959 name => $self->{name},
960 email => $self->{email},
961 url => $self->{url},
962 cleanmirror => $self->{cleanmirror},
963 desc => html_esc($self->{desc}),
964 README => html_esc($self->{READMEDATA}),
965 rmtype => $self->{rmtype},
966 hp => $self->{hp},
967 users => $self->{users},
968 notifymail => html_esc($self->{notifymail}),
969 reverseorder => $self->{reverseorder},
970 summaryonly => $self->{summaryonly},
971 notifytag => html_esc($self->{notifytag}),
972 notifyjson => html_esc($self->{notifyjson}),
973 jsontype => html_esc($self->{jsontype}),
974 jsonsecret => html_esc($self->{jsonsecret}),
975 notifycia => html_esc($self->{notifycia}),
977 __project__ => $self
981 # return true if $enc_passwd is a match for $plain_passwd
982 my $_check_passwd_match = sub {
983 my $enc_passwd = shift;
984 my $plain_passwd = shift;
985 defined($enc_passwd) or $enc_passwd = '';
986 defined($plain_passwd) or $plain_passwd = '';
987 # $enc_passwd may be crypt or crypt_sha1
988 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
989 # It's using sha1-crypt
990 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
991 } else {
992 # It's using crypt
993 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
997 sub authenticate {
998 my $self = shift;
999 my ($gcgi) = @_;
1001 $self->{ccrypt} or die "Can't authenticate against a project with no password";
1002 defined($self->{cpwd}) or $self->{cpwd} = '';
1003 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
1004 $gcgi->err("Your admin password does not match!");
1005 return 0;
1007 return 1;
1010 # return true if the password from the file is empty or consists of all the same
1011 # character. However, if the project was NOT loaded from the group file
1012 # (!self->{loaded}) then the password is never locked.
1013 # This function does NOT check $Girocco::Config::project_passwords, the caller
1014 # is responsible for doing so if desired. Same for $self->{email}.
1015 sub is_password_locked {
1016 my $self = shift;
1018 $self->{loaded} or return 0;
1019 my $testcrypt = $self->{ccrypt}; # The value from the group file
1020 defined($testcrypt) or $testcrypt = '';
1021 $testcrypt ne '' or return 1; # No password at all
1022 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
1023 return 0; # Not locked
1026 sub _setup {
1027 use POSIX qw(strftime);
1028 my $self = shift;
1029 my ($pushers) = @_;
1030 my $fd;
1032 defined($self->{path}) && $self->{path} ne "" or die "invalid setup call";
1033 $self->_mkdir_forkees unless $self->{adopt};
1035 my $gid;
1036 $self->{adopt} || mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
1037 -d $self->{path} or die "unable to setup nonexistent $self->{path}";
1038 if ($Girocco::Config::owning_group) {
1039 $gid = scalar(getgrnam($Girocco::Config::owning_group));
1040 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
1041 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
1042 } else {
1043 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
1045 delete $ENV{GIT_OBJECT_DIRECTORY};
1046 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
1047 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
1048 or die "git init $self->{path} failed: $?";
1049 # we don't need these two, remove them (they will normally be created empty) if they exist
1050 rmdir $self->{path}."/branches";
1051 rmdir $self->{path}."/remotes";
1052 -d $self->{path}."/info" or mkdir $self->{path}."/info"
1053 or die "info directory does not exist and unable to create it: $!";
1054 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
1055 or die "hooks directory does not exist and unable to create it: $!";
1056 # clean out any kruft that may have come in from the initial template directory
1057 foreach my $cleandir (qw(hooks info)) {
1058 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
1059 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
1060 closedir $hooksdir;
1063 if ($Girocco::Config::owning_group) {
1064 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
1066 # hooks never world writable
1067 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
1068 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.compression', '5') == 0
1069 or die "setting core.compression failed: $?";
1070 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
1071 or die "disabling core.logAllRefUpdates failed: $?";
1072 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
1073 or die "disabling core.ignoreCase failed: $?";
1074 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.hooksPath',
1075 ($Girocco::Config::localhooks ? $self->{path}."/hooks" : $Girocco::Config::reporoot . "/_global/hooks")) == 0
1076 or die "setting core.hooksPath failed: $?";
1077 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'extensions.preciousObjects', 'true') == 0
1078 or die "setting extensions.preciousObjects failed: $?";
1079 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
1080 or die "enabling transfer.fsckObjects failed: $?";
1081 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.unpackLimit', '1') == 0
1082 or die "setting transfer.unpackLimit failed: $?";
1083 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.fsckObjects', 'true') == 0
1084 or die "enabling receive.fsckObjects failed: $?";
1085 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
1086 or die "disabling receive.denyNonFastForwards failed: $?";
1087 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
1088 or die "disabling receive.denyDeleteCurrent failed: $?";
1089 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
1090 or die "disabling receive.autogc failed: $?";
1091 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1092 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
1093 or die "enabling receive.updateServerInfo failed: $?";
1094 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
1095 or die "enabling repack.writeBitmaps failed: $?";
1096 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1097 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
1098 or die "setting girocco.creationtime failed: $?";
1099 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
1100 or die "htmlcache directory does not exist and unable to create it: $!";
1101 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
1102 or die "bundles directory does not exist and unable to create it: $!";
1103 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
1104 or die "reflogs directory does not exist and unable to create it: $!";
1105 foreach my $file (qw(info/lastactivity .delaygc)) {
1106 if (open $fd, '>', $self->{path}."/".$file) {
1107 close $fd;
1108 chmod 0664, $self->{path}."/".$file;
1112 # /info must have right permissions,
1113 # and git init didn't do it for some reason.
1114 # config must have correct permissions.
1115 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
1116 # also make sure /refs, /objects and /htmlcache are correct too.
1117 my ($dmode, $dmodestr, $fmode, $fmodestr);
1118 if ($Girocco::Config::owning_group) {
1119 ($dmode, $dmodestr) = (02775, '02775');
1120 ($fmode, $fmodestr) = (0664, '0664');
1121 } else {
1122 ($dmode, $dmodestr) = (02777, '02777');
1123 ($fmode, $fmodestr) = (0666, '0666');
1125 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
1126 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
1128 foreach my $file (qw(config)) {
1129 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
1131 # these ones are probably not strictly required but are nice to have
1132 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
1133 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
1134 chmod($dmode, $self->{path}."/$dir");
1136 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::htmlcache_owning_group) {
1137 my $htmlgid = scalar(getgrnam($Girocco::Config::htmlcache_owning_group));
1138 if (defined($htmlgid) && $htmlgid ne $gid) {
1139 chown(-1, $htmlgid, $self->{path}."/htmlcache") or die "chgrp $htmlgid $self->{path}/htmlcache failed: $!";
1140 chmod($dmode, $self->{path}."/htmlcache") or die "chmod $dmodestr $self->{path}/htmlcache failed: $!";
1143 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::ctags_owning_group) {
1144 my $ctagsgid = scalar(getgrnam($Girocco::Config::ctags_owning_group));
1145 if (defined($ctagsgid) && $ctagsgid ne $gid) {
1146 chown(-1, $ctagsgid, $self->{path}."/ctags") or die "chgrp $ctagsgid $self->{path}/ctags failed: $!";
1147 chmod($dmode, $self->{path}."/ctags") or die "chmod $dmodestr $self->{path}/ctags failed: $!";
1151 $self->_properties_save;
1152 $self->_alternates_setup unless $self->{noalternates} || $self->{adopt};
1153 $self->_ctags_setup;
1154 $self->_group_remove;
1155 $self->_group_add($pushers);
1156 $self->_hooks_install;
1157 $self->_update_index;
1158 $self->_set_changed;
1159 $self->_set_forkchange(1);
1162 sub premirror {
1163 my $self = shift;
1165 delete $self->{adopt};
1166 $self->_setup(':');
1167 $self->_clonep(1);
1168 if ($Girocco::Config::autogchack) {
1169 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1170 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1172 $self->perm_initialize;
1175 sub conjure {
1176 my $self = shift;
1178 delete $self->{adopt};
1179 $self->_setup;
1180 $self->_nofetch(1);
1181 if ($Girocco::Config::autogchack && $Girocco::Config::autogchack ne "mirror") {
1182 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1183 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1185 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1186 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1187 or die "create-personal-mob-area $self->{name} failed";
1189 $self->perm_initialize;
1192 sub clone {
1193 my $self = shift;
1195 unlink ($self->_clonefail_path()); # Ignore EEXIST error
1196 unlink ($self->_clonelog_path()); # Ignore EEXIST error
1198 use IO::Socket;
1199 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
1200 select((select($sock),$|=1)[0]);
1201 $sock->print("clone ".$self->{name}."\n");
1202 # Just ignore reply, we are going to succeed anyway and the I/O
1203 # would apparently get quite hairy.
1204 $sock->flush();
1205 sleep 2; # *cough*
1206 $sock->close();
1209 # call this after ghost instead of conjure or premirror+clone to adopt a pre-existing Git dir
1210 # ghost must be called with the proper value of $mirror for the to-be-adopted project
1211 # for mirrors the $proj->{url} needs to be set and for push projects the $proj->{users} array ref
1212 sub adopt {
1213 my $self = shift;
1214 my $name = $self->{name};
1216 # Sanity check first
1217 defined($name) && $name ne "" && !$self->{loaded} or return undef;
1218 does_exist($name, 1) or return undef;
1219 defined($self->{path}) && $self->{path} eq $Girocco::Config::reporoot."/$name.git" or return undef;
1220 defined($self->{base_path}) && $self->{base_path} eq $Girocco::Config::reporoot or return undef;
1221 defined($self->{email}) && defined($self->{orig_email}) && defined($self->{mirror}) && ref($self->{users}) eq 'ARRAY'
1222 or return undef;
1223 !defined(Girocco::Project->load($name)) or return undef;
1224 is_git_dir($self->{path}) or return undef;
1225 my $config = read_config_file_hash($self->{path}."/config");
1226 defined($config) && _boolval($config->{"core.bare"}) or die "refusing to adopt non-bare repository";
1227 defined(read_HEAD_symref($self->{path})) or die "refusing to adopt non-symref HEAD repository";
1229 # Adopt the project by creating a new $chroot/etc/group entry and setting up anything that's missing
1230 $self->_nofetch(!$self->{mirror});
1231 $self->{adopt} = 1;
1232 $self->_setup($self->{mirror} ? ":" : "");
1233 delete $self->{adopt};
1234 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
1235 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1236 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1238 if (!$self->{mirror} && $Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1239 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1240 or die "create-personal-mob-area $self->{name} failed";
1242 my $result = $self->perm_initialize;
1243 unlink("$self->{path}/.delaygc") unless $self->is_empty;
1244 # Pick up any pre-existing settings
1245 my $p = Girocco::Project->load($name);
1246 %$self = %$p if defined($p) && $p->{loaded};
1247 $result;
1250 sub _update_users {
1251 my $self = shift;
1253 $self->_group_update;
1254 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
1255 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
1256 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
1257 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
1260 sub update {
1261 my $self = shift;
1263 $self->_properties_save;
1264 $self->_update_users;
1266 if (exists($self->{tags_to_delete})) {
1267 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1270 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1272 $self->_update_index if $self->{email} ne $self->{orig_email};
1273 $self->{orig_email} = $self->{email};
1274 $self->_set_changed;
1279 sub update_password {
1280 my $self = shift;
1281 my ($pwd) = @_;
1283 $self->{crypt} = scrypt_sha1($pwd);
1284 $self->_group_update;
1287 # You can explicitly do this just on a ghost() repository too.
1288 sub delete {
1289 my $self = shift;
1291 if (-d $self->{path}) {
1292 system('rm', '-rf', $self->{path}) == 0
1293 or die "rm -rf $self->{path} failed: $?";
1295 # attempt to clean up any empty fork directories by removing them
1296 my @pelems = split('/', $self->{name});
1297 while (@pelems > 1) {
1298 pop @pelems;
1299 # okay to fail
1300 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1302 $self->_group_remove;
1303 $self->_update_index;
1304 $self->_set_forkchange(1);
1309 # If the project's directory actually exists archive it before deleting it
1310 # Return full path to archived project ("" if none)
1311 sub archive_and_delete {
1312 my $self = shift;
1314 unless (-d $self->{path}) {
1315 $self->delete;
1316 return "";
1319 # archive the project before deletion
1320 use POSIX qw(strftime);
1321 my $destdir = $self->{base_path};
1322 $destdir =~ s,(?<=[^/])/+$,,;
1323 $destdir .= "/_recyclebin/";
1324 $destdir .= $1 if $self->{name} =~ m,^(.*/)[^/]+$,;
1325 my $destbase = $self->{name};
1326 $destbase = $1 if $destbase =~ m,^.*/([^/]+)$,;
1327 my $oldmask = umask();
1328 umask($oldmask & ~0070);
1329 system('mkdir', '-p', $destdir) == 0 && -d $destdir
1330 or die "mkdir -p \"$destdir\" failed: $?";
1331 umask($oldmask);
1332 my $suffix = '';
1333 if (-e "$destdir$destbase.git") {
1334 $suffix = 1;
1335 while (-e "$destdir$destbase~$suffix.git") {
1336 ++$suffix;
1337 last if $suffix >= 10000; # don't get too carried away
1339 $suffix = '~'.$suffix;
1341 not -e "$destdir$destbase$suffix.git"
1342 or die "Unable to compute suitable archive path";
1343 system('mv', $self->{path}, "$destdir$destbase$suffix.git") == 0
1344 or die "mv \"$self->{path}\" \"$destdir$destbase$suffix.git\" failed: $?";
1345 if (!$self->{mirror} && @{$self->{users}}) {
1346 # Remember the user list at recycle time
1347 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1348 'config', 'girocco.recycleusers', join(",", @{$self->{users}}));
1350 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1351 my $recycletime = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1352 # We ought to do something if this fails, but the project has already been moved
1353 # so there's really nothing to be done at this point.
1354 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1355 'config', 'girocco.recycletime', $recycletime);
1357 $self->delete;
1358 return $destdir.$destbase.$suffix.".git";
1361 sub _contains_files {
1362 my $dir = shift;
1363 (-d $dir) or return 0;
1364 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1365 while (my $entry = readdir($dh)) {
1366 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1367 closedir($dh), return 1
1368 if -f "$dir/$entry" ||
1369 -d "$dir/$entry" && _contains_files("$dir/$entry");
1371 closedir($dh);
1372 return 0;
1375 sub has_forks {
1376 my $self = shift;
1378 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1381 # Returns an array of 0 or more array refs, one for each bundle:
1382 # ->[0]: bundle creation time (seconds since epoch)
1383 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1384 # ->[2]: bundle size in bytes
1385 sub bundles {
1386 my $self = shift;
1387 use Time::Local;
1389 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1390 my @blist = ();
1391 if (-d $self->{path}.'/bundles') {{
1392 my $prefix = $self->{name};
1393 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1394 opendir(my $dh, $self->{path}.'/bundles') or last;
1395 while (my $bfile = readdir($dh)) {
1396 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1397 my $ctime = eval {timegm(
1398 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1399 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4))};
1400 next unless $ctime;
1401 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1402 my $f1 = <$bh>;
1403 my $f2 = <$bh>;
1404 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1405 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1406 close($bh);
1407 next unless $f1 && $f2 && $f1 ne $f2;
1408 chomp $f1;
1409 chomp $f2;
1410 next unless -e $f1 && -e $f2;
1411 my $s1 = -s $f1 || 0;
1412 my $s2 = -s $f2 || 0;
1413 next unless $s1 || $s2;
1414 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1416 closedir($dh);
1418 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1419 my %seen = ();
1420 my @result = ();
1421 foreach my $bndl (@blist) {
1422 next if $seen{$bndl->[1]};
1423 $seen{$bndl->[1]} = 1;
1424 push(@result, $bndl);
1426 $self->{bundles} = \@result;
1427 return @result;
1430 sub has_alternates {
1431 my $self = shift;
1432 my $af = $self->{path}.'/objects/info/alternates';
1433 -f $af && -s _ or return 0;
1434 my $nb = 0;
1435 open my $fh, '<', $af or return 1;
1436 while (my $line = <$fh>) {
1437 next if $line =~ /^$/ || $line =~ /^#/;
1438 $nb = 1;
1439 last;
1441 close $fh;
1442 return $nb;
1445 sub has_bundle {
1446 my $self = shift;
1448 return scalar($self->bundles);
1451 sub _has_notifyhook {
1452 my $self = shift;
1453 my $val = $Girocco::Config::default_notifyhook;
1454 defined($self->{'notifyhook'}) and $val = $self->{'notifyhook'};
1455 return (defined($val) && $val ne "") ? $val : undef;
1458 # returns true if any of the notify fields are non-empty
1459 sub has_notify {
1460 my $self = shift;
1461 # We do not ckeck notifycia since it's defunct
1462 return
1463 $self->{'notifymail'} || $self->{'notifytag'} ||
1464 $self->{'notifyjson'} ||
1465 !!$self->_has_notifyhook;
1468 sub is_empty {
1469 # A project is considered empty if the git repository does not
1470 # have any refs. This means packed-refs does not exist or is
1471 # empty or only has lines starting with '#' AND there are no
1472 # files in the refs subdirectory hierarchy (no matter how deep).
1474 my $self = shift;
1476 (-d $self->{path}) or return 0;
1477 if (-e $self->{path}.'/packed-refs') {
1478 open(my $pr, '<', $self->{path}.'/packed-refs')
1479 or die "open $self->{path}./packed-refs failed: $!";
1480 my $foundref = 0;
1481 while (my $ref = <$pr>) {
1482 next if $ref =~ /^#/;
1483 $foundref = 1;
1484 last;
1486 close($pr);
1487 return 0 if $foundref;
1489 (-d $self->{path}.'/refs') or return 1;
1490 return !_contains_files($self->{path}.'/refs');
1493 # returns array:
1494 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1495 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1496 # Both values (if not undef) are seconds since epoch
1497 # Result only considers lastgc and min_gc_interval nothing else
1498 sub next_gc {
1499 my $self = shift;
1500 my $lastgcepoch = parse_any_date($self->{lastgc});
1501 return (undef, undef) unless defined $lastgcepoch;
1502 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1503 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1504 $Girocco::Config::min_mirror_interval));
1507 # returns boolean (0 or 1)
1508 # Attempts to determine whether or not a gc (and corresponding build
1509 # of a .bitmap/.bndl file) will actually take place at the next_gc
1510 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1511 # end up being built depends on whether or not the local object graph
1512 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1513 # is not possible because the object graph will be incomplete,
1514 # but it *is* possible that even though the repository has_alternates,
1515 # it does not actually borrow any objects so a .bitmap/.bndl will build
1516 # in spite of the presence of alternates -- but this is expected to be rare.
1517 # The result is a best guess and false return value is not an absolute
1518 # guarantee that gc will not take place at the next interval, but it probably
1519 # will not if nothing changes in the meantime.
1520 sub needs_gc {
1521 my $self = shift;
1522 my $lgc = parse_any_date($self->{lastgc});
1523 my $lrecv = parse_any_date($self->{lastreceive});
1524 my $lpgc = parse_any_date($self->{lastparentgc});
1525 return 1 unless defined($lgc) && defined($lrecv);
1526 if ($self->has_alternates) {
1527 return 1 unless defined($lpgc);
1528 return 1 unless $lpgc < $lgc;
1530 return 1 unless $lrecv < $lgc;
1531 # We don't try running any "is_dirty" check, so if somehow the
1532 # repository became dirty without updating lastreceive we might
1533 # incorrectly return false instead of true.
1534 return 0;
1537 sub delete_ctag {
1538 my $self = shift;
1539 my ($ctag) = @_;
1541 # sanity check, disallow filenames starting with . .. or /
1542 unlink($self->{path}.'/ctags/'.$ctag)
1543 unless !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1546 # returns new tag count value on success (will always be >= 1) otherwise undef
1547 sub add_ctag {
1548 my $self = shift;
1549 my $ctag = valid_tag(shift);
1550 my $nochanged = shift;
1552 # sanity check, disallow filenames starting with . .. or /
1553 return undef if !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1555 my $val = 0;
1556 my $ct;
1557 if (open $ct, '<', $self->{path}."/ctags/$ctag") {
1558 my $count = <$ct>;
1559 close $ct;
1560 defined $count or $count = '';
1561 chomp $count;
1562 $val = $count =~ /^[1-9]\d*$/ ? $count : 1;
1564 ++$val;
1565 my $oldmask = umask();
1566 umask($oldmask & ~0060);
1567 open $ct, '>', $self->{path}."/ctags/$ctag" and print $ct $val."\n" and close $ct;
1568 $self->_set_changed unless $nochanged;
1569 $self->_set_forkchange unless $nochanged;
1570 umask($oldmask);
1571 return $val;
1574 sub get_ctag_names {
1575 my $self = shift;
1576 my @ctags = ();
1577 opendir(my $dh, $self->{path}.'/ctags')
1578 or return @ctags;
1579 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1580 closedir($dh);
1581 return sort({lc($a) cmp lc($b)} @ctags);
1584 sub get_heads {
1585 my $self = shift;
1586 my $fh;
1587 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1588 defined($heads) or $heads = '';
1589 chomp $heads;
1590 my @res = ();
1591 foreach (split(/\n/, $heads)) {
1592 chomp;
1593 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1594 push @res, $1;
1596 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1597 @res;
1600 sub get_HEAD {
1601 my $self = shift;
1602 my $HEAD = read_HEAD_ref($self->{path});
1603 defined($HEAD) && $HEAD ne "" or die "could not get HEAD";
1604 return $1 if $HEAD =~ m{^refs/heads/(.+)$};
1605 return "[other]" if $HEAD =~ m{^refs/};
1606 return "[detached]" if $HEAD =~ m{^[0-9a-fA-F]{4,}$};
1607 return "[invalid]";
1610 sub set_HEAD {
1611 my $self = shift;
1612 my $newHEAD = shift;
1613 # Cursory checks only -- if you want to break your HEAD, be my guest
1614 if ($newHEAD =~ /^\/|^\.|[\x00-\x1f \x7f\[~^'<>*?\\:]|\@\{|\.\.|\.lock$|\.$|\/$/) {
1615 die "grossly invalid new HEAD: $newHEAD";
1617 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1618 die "could not set HEAD" if ($? >> 8);
1619 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1620 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1623 sub gen_auth {
1624 my $self = shift;
1625 my ($type) = @_;
1626 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1628 $self->{authtype} = $type;
1630 no warnings;
1631 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1633 my $expire = time + 24 * 3600;
1634 my $propval = "# ${type}AUTH $self->{auth} $expire";
1635 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1636 $self->{auth};
1639 sub del_auth {
1640 my $self = shift;
1642 delete $self->{auth};
1643 delete $self->{authtype};
1644 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1647 sub remove_user {
1648 my $self = shift;
1649 my ($username) = @_;
1651 my $before_count = @{$self->{users}};
1652 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1653 return @{$self->{users}} != $before_count;
1656 ### static methods
1658 sub get_forkee_name {
1659 local $_ = $_[0];
1660 (m#^(.*)/.*?$#)[0]; #
1663 sub get_forkee_path {
1664 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1665 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1666 -d $forkee ? $forkee : '';
1669 # Ultimately the full project/fork name could end up being part of a Git ref name
1670 # when a project's forks are combined into one giant repository for efficiency.
1671 # That means that the project/fork name must satisfy the Git ref name requirements:
1673 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1674 # 2. The character with an ASCII value of 0x7F is not allowed
1675 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1676 # 4. The character '/' is a separator and is not allowed within a name
1677 # 5. The name may not start with '.' or end with '.'
1678 # 6. The name may not end with '.lock'
1679 # 7. The name may not contain the '..' sequence
1680 # 8. The name may not contain the '@{' sequence
1681 # 9. If multiple components are used (separated by '/'), no empty '' components
1683 # We also prohibit a trailing '.git' on any path component and futher restrict
1684 # the allowed characters to alphanumeric and [+._-] where names must start with
1685 # an alphanumeric.
1687 sub _valid_name_characters {
1688 local $_ = $_[0];
1689 (not m#^[/+._-]#)
1690 and (not m#//#)
1691 and (not m#\.\.#)
1692 and (not m#/[+._-]#)
1693 and (not m#\./#)
1694 and (not m#\.$#)
1695 and (not m#\.git/#i)
1696 and (not m#\.git$#i)
1697 and (not m#\.idx/#i)
1698 and (not m#\.idx$#i)
1699 and (not m#\.lock/#i)
1700 and (not m#\.lock$#i)
1701 and (not m#\.pack/#i)
1702 and (not m#\.pack$#i)
1703 and (not m#\.bundle/#i)
1704 and (not m#\.bundle$#i)
1705 and (not m#/$#)
1706 and (not m/^[a-fA-F0-9]{38}$/)
1707 and m#^[a-zA-Z0-9/+._-]+$#
1708 and !has_reserved_suffix($_, $_[1], $_[2]);
1711 # $_[0] => prospective project name (WITHOUT trailing .git)
1712 # $_[1] => true to allow orphans (i.e. two-or-more-level-deep projects without a parent)
1713 # (the directory in which the orphan will be created must, however, already exist)
1714 # $_[2] => true to allow orphans w/o needed directory if $_[1] also true (like mkdir -p)
1715 # If $_[0] is a SCALAR ref, ${$_[0]} contains the name and will be untainted on success.
1716 sub valid_name {
1717 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1718 local $_ = $_[0];
1719 my $mayberef_name = $_;
1720 ref($_) eq 'SCALAR' and $_ = $$_;
1721 my $rv = (
1722 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1723 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1724 and ((not m#/#) or -d get_forkee_path($_) or ($_[1] and ($_[2] or -d $Girocco::Config::reporoot.'/'.get_forkee_name($_))))
1725 and (! -f $Girocco::Config::reporoot."/$_.git")
1727 $rv && ref($mayberef_name) eq 'SCALAR' && m|^(.+)$| and $$mayberef_name = $1;
1728 return $rv;
1731 # It's possible that some forks have been kept but the forkee is gone.
1732 # In this case the standard valid_name check is too strict.
1733 # If $_[0] is a SCALAR ref, ${$_[0]} contains the name and will be untainted on success.
1734 sub does_exist {
1735 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1736 my ($mayberef_name, $nodie) = @_;
1737 my $name = ref($mayberef_name) eq 'SCALAR' ? $$mayberef_name : $mayberef_name;
1738 my $okay = (
1739 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1740 and ((not $name =~ m#/#)
1741 or -d get_forkee_path($name)
1742 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1743 (!$okay && $nodie) and return undef;
1744 !$okay and die "tried to query for project with invalid name $name!";
1745 -d $Girocco::Config::reporoot."/$name.git" or return undef;
1746 ref($mayberef_name) eq 'SCALAR' && $name =~ m|^(.+)$| and $$mayberef_name = $1;
1747 return 1;
1750 sub get_full_list {
1751 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1752 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1753 close $fd;
1754 @projects;