Girocco/HashUtil.pm: take advantage of Digest::SHA::hmac_sha1
[girocco.git] / Girocco / Project.pm
blob11897d441ac03e9c9db1b8b26c46f0248d8f1c70
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',
313 'text/markdown' => 'Markdown',
314 'text/x-markdown' => 'Markdown',
315 markdown => 'Markdown',
316 md => 'Markdown',
318 'text/plain' => 'Plain Text',
319 'plain text' => 'Plain Text',
320 'plain-text' => 'Plain Text',
321 plain_text => 'Plain Text',
322 plaintext => 'Plain Text',
323 plain => 'Plain Text',
324 text => 'Plain Text',
325 txt => 'Plain Text',
327 'text/html' => 'HTML',
328 html => 'HTML',
329 htm => 'HTML'
332 # if $_[1] is true, return "" instead of default for unknown type
333 sub _normalize_rmtype {
334 my $rmtype = shift;
335 my $nodefault = shift;
336 defined($rmtype) and $rmtype = $rmtypes{lc($rmtype)};
337 defined($rmtype) && $rmtype ne '' or
338 $rmtype = $nodefault ? "" : $rmtypes{'default'};
339 return $rmtype;
342 sub _lint_readme {
343 my $self = shift;
344 my $htmlfrag = shift;
345 defined($htmlfrag) or $htmlfrag = 1;
346 defined($self->{READMEDATA}) or $self->{READMEDATA} = '';
347 $self->{rmtype} = _normalize_rmtype($self->{rmtype});
348 # Empty always just becomes empty with no errors
349 if ($self->{READMEDATA} eq '') {
350 $self->{README} = '';
351 return 0;
353 if ($self->{rmtype} eq 'Plain Text') {
354 # Never any errors with this one
355 my $esc = $self->{READMEDATA};
356 $esc =~ s/&/&amp;/gs;
357 $esc =~ s/</&lt;/gs;
358 $self->{README} = '<pre class="plaintext">' . $esc . '</pre>';
359 return 0;
361 eval { require Markdown; 1 } or do {
362 return (1, "README: Markdown/HTML formats temporarily unavailable");
364 my @errs = ();
365 if ($self->{rmtype} eq 'HTML') {
366 # Legacy HTML support but now sanitized with possible auto-fixup
367 my $output;
368 eval { $output = Markdown::ProcessRaw($self->{READMEDATA},
369 sanitize => 1, xmlcheck => 2, htmlauto => 0); 1; } or
370 do {
371 @errs = split(/\n+/, $@);
372 @errs or push(@errs, 'Invalid HTML');
374 # Make one more attempt with htmlauto in case
375 # that's good enough to fix up the HTML and make it valid
376 eval { $output = Markdown::ProcessRaw($self->{READMEDATA},
377 sanitize => 1, xmlcheck => 2, htmlauto => 1); 1; } and
378 do {
379 @errs = ();
382 !@errs and $self->{README} = (chomp($output),$output);
383 } else {
384 # Markdown format
385 my $output;
386 my $gwbase = url_path($Girocco::Config::gitweburl,1).$self->{name}.'.git';
387 my %mdopts = (
388 sanitize => 1,
389 xmlcheck => 2,
390 yamlmode => 1,
391 yamlvis => 0,
392 keepabs => 1,
393 base_prefix => $self->{name}.'.git',
394 url_prefix => $gwbase . '/blob/HEAD:',
395 img_prefix => $gwbase . '/blob_plain/HEAD:'
397 eval { $output = Markdown::Markdown($self->{READMEDATA}, %mdopts); 1; } or
398 do {
399 @errs = split(/\n+/, $@);
400 @errs or push(@errs, 'Invalid Markdown');
402 !@errs and $self->{README} = (chomp($output),$output);
404 return 0 unless @errs;
405 my @fmterrs = ();
406 foreach (@errs) {
407 $_ = html_esc($_) if $htmlfrag;
408 s/ /\&#160;/gs if $htmlfrag;
409 if ($htmlfrag) {
410 push @fmterrs, 'README: <tt>' . $_ . '</tt>';
411 } else {
412 push @fmterrs, 'README: ' . $_ . "\n";
415 if ($htmlfrag) {
416 return (scalar(@fmterrs), join("<br />\n", @fmterrs));
417 } else {
418 return (scalar(@fmterrs), join("", @fmterrs));
422 sub _properties_load {
423 my $self = shift;
424 my $setprop = sub {
425 my $propval = $self->_property_fget($_);
426 defined($propval) and $self->{$_} = $propval;
428 &$setprop foreach keys %propmap;
429 &$setprop foreach keys %propmapro;
430 do {&$setprop foreach keys %propmapromirror} if $self->{mirror};
431 $self->_readlocalconfigfile
432 unless ref($self->{configfilehash}) eq 'HASH';
433 delete $self->{auth};
434 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
435 defined($val) or $val = '';
436 chomp $val;
437 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
438 my $expire = $3;
439 if (time < $expire) {
440 $self->{authtype} = $1;
441 $self->{auth} = $2;
444 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
445 if (defined($self->{configfilehash}->{'girocco.autogchack'})) {
446 $self->{autogchack} = _boolval($self->{configfilehash}->{'girocco.autogchack'});
449 defined($self->{jsontype}) or $self->{jsontype} = "";
450 $self->{jsontype} = lc($self->{jsontype});
451 $self->{jsontype} eq 'application/x-www-form-urlencoded' || $self->{jsontype} eq 'application/json' or
452 $self->{jsontype} = 'application/x-www-form-urlencoded';
453 defined($self->{jsonsecret}) or $self->{jsonsecret} = "";
454 $self->_cleanup_datetime('lastactivity');
455 $self->_cleanup_description;
456 $self->_cleanup_readme;
457 $self->{rmtype} = _normalize_rmtype($self->{rmtype}, 1);
458 if (!$self->{rmtype}) {
459 # default type is "Markdown" unless README ne '' but READMEDATA eq ''
460 if ($self->{README} ne '' && $self->{READMEDATA} eq '') {
461 # This was the only previously understood format
462 $self->{rmtype} = 'HTML';
463 $self->{READMEDATA} = $self->{README};
464 } else {
465 $self->{rmtype} = _normalize_rmtype(""); # get default type
468 delete $self->{configfilehash};
471 sub _set_bangagain {
472 my $self = shift;
473 my $fd;
474 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
475 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
476 if (open($fd, '>', $self->_bangagain_path)) {
477 close $fd;
478 chmod(0664, $self->_bangagain_path);
483 sub _properties_save {
484 my $self = shift;
485 delete $self->{configfilehash};
486 foreach my $prop (keys %propmap) {
487 $self->_property_fput($prop, $self->{$prop}, 1);
489 $self->_set_bangagain;
492 sub _nofetch_path {
493 my $self = shift;
494 $self->_property_path('.nofetch');
497 sub _nofetch {
498 my $self = shift;
499 my ($nofetch) = @_;
500 my $nf = $self->_nofetch_path;
501 if ($nofetch) {
502 open my $x, '>', $nf or die "nofetch failed: $!";
503 close $x;
504 } else {
505 ! -e $nf or unlink $nf or die "yesfetch failed: $!";
509 sub _banged_path {
510 my $self = shift;
511 $self->_property_path('.banged');
514 sub _bangagain_path {
515 my $self = shift;
516 $self->_property_path('.bangagain');
519 sub _gcp_path {
520 my $self = shift;
521 $self->_property_path('.gc_in_progress');
524 sub _clonelog_path {
525 my $self = shift;
526 $self->_property_path('.clonelog');
529 sub _clonefail_path {
530 my $self = shift;
531 $self->_property_path('.clone_failed');
534 sub _clonep_path {
535 my $self = shift;
536 $self->_property_path('.clone_in_progress');
539 sub _clonep {
540 my $self = shift;
541 my ($nofetch) = @_;
542 my $np = $self->_clonep_path;
543 if ($nofetch) {
544 open my $x, '>', $np or die "clonep failed: $!";
545 close $x;
546 } else {
547 unlink $np or die "clonef failed: $!";
550 sub _alternates_setup {
551 use POSIX qw(:fcntl_h);
552 my $self = shift;
553 return unless $self->{name} =~ m#/#;
554 my $forkee_name = get_forkee_name($self->{name});
555 my $forkee_path = get_forkee_path($self->{name});
556 return unless -d $forkee_path;
557 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
558 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
559 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
560 mkdir $self->{path}.'/objects/pack'; chmod 02775, $self->{path}.'/objects/pack';
562 # If somehow either our objects/pack or the prospective alternate's pack
563 # directory does not exist decline to set up any alternates
564 my $altpath = "$forkee_path/objects";
565 -d $self->{path}.'/objects/pack' && -d $altpath.'/pack' or return;
567 # If our objects/pack and the prospective alternate's pack directory
568 # do not share the same device then decline to set up any alternates
569 my ($selfdev) = stat($self->{path}.'/objects/pack');
570 my ($altdev) = stat($altpath.'/pack');
571 defined($selfdev) && defined($altdev) && $selfdev ne "" && $altdev ne "" && $selfdev == $altdev or return;
573 # We set up both alternates and http_alternates since we cannot use
574 # relative path in alternates - that doesn't work recursively.
576 my $filename = $self->{path}.'/objects/info/alternates';
577 open my $x, '>', $filename or die "alternates failed: $!";
578 print $x "$altpath\n";
579 close $x;
580 chmod 0664, $filename or warn "cannot chmod $filename: $!";
582 if ($Girocco::Config::httppullurl) {
583 $filename = $self->{path}.'/objects/info/http-alternates';
584 open my $x, '>', $filename or die "http-alternates failed: $!";
585 my $upfork = $forkee_name;
586 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
587 close $x;
588 chmod 0664, $filename or warn "cannot chmod $filename: $!";
591 # copy lastactivity from the parent project
592 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
593 my $activity = <$x>;
594 close $x;
595 last unless $activity;
596 open $x, '>', $self->{path}.'/info/lastactivity' or last;
597 print $x $activity;
598 close $x;
599 chomp $activity;
600 $self->{'lastactivity'} = $activity;
603 # copy refs from parent project
604 my $dupout;
605 open $dupout, '>&1' or
606 die "could not dup STDOUT_FILENO: $!";
607 my $packedrefsfd = POSIX::open("$self->{path}/packed-refs", O_WRONLY|O_TRUNC|O_CREAT, 0664);
608 defined($packedrefsfd) && $packedrefsfd >= 0 or die "could not open fork's packed-refs file for writing: $!";
609 POSIX::dup2($packedrefsfd, 1) or
610 die "could not dup2 STDOUT_FILENO: $!";
611 POSIX::close($packedrefsfd);
612 my $result = system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
613 my $resultstr = $!;
614 POSIX::dup2(fileno($dupout), 1);
615 close($dupout);
616 $result == 0 or die "could not create fork's packed-refs file data: $resultstr";
617 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
619 # initialize HEAD
620 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
621 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
622 chomp $HEAD;
623 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
624 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
627 sub _set_changed {
628 my $self = shift;
629 my $fd;
630 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
633 sub _set_forkchange {
634 my $self = shift;
635 my $changedtoo = shift;
636 return unless $self->{name} =~ m#/#;
637 my $forkee_path = get_forkee_path($self->{name});
638 return unless -d $forkee_path;
639 # mark forkee as changed
640 my $fd;
641 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
642 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
643 return if -e $forkee_path.'/htmlcache/summary.forkchange';
644 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
647 sub _ctags_setup {
648 my $self = shift;
649 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
650 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
653 sub _group_add {
654 my $self = shift;
655 my ($xtra) = @_;
656 $xtra .= join(',', @{$self->{users}});
657 my $crypt = $self->{crypt};
658 defined($crypt) or $crypt = 'unknown';
659 filedb_atomic_append(jailed_file('/etc/group'),
660 join(':', $self->{name}, $crypt, '\i', $xtra));
663 sub _group_update {
664 my $self = shift;
665 my $xtra = join(',', @{$self->{users}});
666 filedb_atomic_edit(jailed_file('/etc/group'),
667 sub {
668 $_ = $_[0];
669 chomp;
670 if ($self->{name} eq (split /:/)[0]) {
671 # preserve readonly flag
672 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
673 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
674 } else {
675 return "$_\n";
681 sub _group_remove {
682 my $self = shift;
683 filedb_atomic_edit(jailed_file('/etc/group'),
684 sub {
685 $self->{name} ne (split /:/)[0] and return $_;
690 sub _hook_path {
691 my $self = shift;
692 my ($name) = @_;
693 $self->{path}.'/hooks/'.$name;
696 sub _hook_install {
697 my $self = shift;
698 my ($name) = @_;
699 my $hooksdir = $self->{path}.'/hooks';
700 my $oldmask = umask();
701 umask($oldmask & ~0070);
702 -d $hooksdir or mkdir $hooksdir or
703 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
704 umask($oldmask);
705 my $globalhooks = $Girocco::Config::reporoot . "/_global/hooks";
706 -f "$globalhooks/$name" && -r _ or die "cannot find hook $name: $!";
707 ! -e $self->_hook_path($name) || unlink($self->_hook_path($name)) && ! -e $self->_hook_path($name) or
708 die "hooks directory contains unremovable pre-existing hook $name: $!";
709 symlink("$globalhooks/$name", $self->_hook_path($name)) or
710 die "cannot create hook $name symlink: $!";
713 sub _hooks_install {
714 my $self = shift;
715 foreach my $hook ('pre-auto-gc', 'pre-receive', 'post-commit', 'post-receive', 'update') {
716 $self->_hook_install($hook);
720 # private constructor, do not use
721 sub _new {
722 my $class = shift;
723 my ($name, $base_path, $path, $orphan, $optp) = @_;
724 does_exist(\$name,1) || valid_name(\$name, $orphan, $optp) or die "refusing to create project with invalid name ($name)!";
725 $path ||= "$base_path/$name.git";
726 my $proj = { name => $name, base_path => $base_path, path => $path };
728 bless $proj, $class;
731 # public constructor #0
732 # creates a virtual project not connected to disk image
733 # you can conjure() it later to disk
734 sub ghost {
735 my $class = shift;
736 my ($name, $mirror, $orphan, $optp) = @_;
737 my $self = $class->_new($name, $Girocco::Config::reporoot, undef, $orphan, $optp);
738 $self->{users} = [];
739 $self->{mirror} = $mirror;
740 $self->{email} = $self->{orig_email} = '';
741 $self->{notifyjson} = $self->{orig_notifyjson} = '';
742 $self;
745 # public constructor #1
746 sub load {
747 my $class = shift;
748 my $name = shift || '';
750 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
751 my $r = qr/^\Q$name\E:/;
752 foreach (grep /$r/, <$fd>) {
753 chomp;
755 my $self = $class->_new($name, $Girocco::Config::reporoot);
756 (-d $self->{path} && $self->_readlocalconfigfile(1))
757 or die "invalid path (".$self->{path}.") for project ".$self->{name};
759 my (undef, $crypt, $gid, $ulist) = split /:/;
760 $gid =~ /^(\d+)$/ or next; $self->{gid} = $1;
761 { use bytes;
762 $crypt =~ /^([^:\x00-\x1F\x7F-\xFF]*)$/ or next; $self->{crypt} = $1; }
763 defined($ulist) or $ulist = '';
764 $ulist =~ /^((?:\w+(?:,\w+)*)?)$/ or next;
765 $self->{users} = [split /,/, $1];
766 $self->{HEAD} = $self->get_HEAD;
767 $self->{orig_HEAD} = $self->{HEAD};
768 $self->{orig_users} = [@{$self->{users}}];
769 $self->{mirror} = ! -e $self->_nofetch_path;
770 $self->{banged} = -e $self->_banged_path if $self->{mirror};
771 $self->{gc_in_progress} = -e $self->_gcp_path;
772 $self->{clone_in_progress} = -e $self->_clonep_path;
773 $self->{clone_logged} = -e $self->_clonelog_path;
774 $self->{clone_failed} = -e $self->_clonefail_path;
775 $self->{ccrypt} = $self->{crypt};
777 $self->_properties_load;
778 $self->{orig_email} = $self->{email};
779 $self->{orig_notifyjson} = $self->{notifyjson};
780 $self->{loaded} = 1; # indicates self was loaded from etc/group file
781 close $fd;
782 return $self;
784 close $fd;
785 undef;
788 # $proj may not be in sane state if this returns false!
789 # fields listed in %$metadata_fields that are NOT also
790 # in @Girocco::Config::project_fields are totally ignored!
791 sub cgi_fill {
792 my $self = shift;
793 my ($gcgi, $silent) = @_;
794 my $cgi = $gcgi->cgi;
795 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
796 my $field_enabled = sub {
797 defined($cgi->param($_[0])) &&
798 (!exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]}))};
800 my $pwd = $cgi->param('pwd');
801 my $pwd2 = $cgi->param('pwd2');
802 # in case passwords are disabled
803 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd2 = '';
804 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
805 $gcgi->err("Empty passwords are not permitted.");
807 if ($pwd ne '' or not $self->{crypt}) {
808 $self->{crypt} = scrypt_sha1($pwd);
810 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
811 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
814 $self->{cpwd} = $cgi->param('cpwd');
816 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
817 my $newtype = $forkee ? 'fork' : 'project';
818 length($project) <= 64
819 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
821 if ($Girocco::Config::project_owners eq 'email') {
822 $self->{email} = $gcgi->wparam('email');
823 valid_email($self->{email})
824 or $gcgi->err("Your email sure looks weird...?");
825 length($self->{email}) <= 96
826 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
829 # No setting the url unless we're either new or an existing mirror!
830 unless ($self->{loaded} && !$self->{mirror}) {
831 $self->{url} = $gcgi->wparam('url') ;
832 if ($field_enabled->('cleanmirror')) {
833 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
836 # Always validate the url if we're an existing mirror
837 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
838 # Always allow the url to be left unchanged without validation when editing
839 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
840 valid_repo_url($self->{url})
841 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
842 if ($Girocco::Config::restrict_mirror_hosts) {
843 my $mh = extract_url_hostname($self->{url});
844 is_dns_hostname($mh)
845 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
846 !is_our_hostname($mh)
847 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
851 if ($field_enabled->('desc')) {
852 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
853 length($self->{desc}) <= 1024
854 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
857 if ($field_enabled->('README')) {
858 $self->{rmtype} = $rmtypes{lc($gcgi->wparam('rmtype')||'')};
859 if (!$self->{rmtype}) {
860 $gcgi->err("Invalid README Format. Must be 'Markdown', 'Plain Text' or 'HTML'.");
861 $self->{rmtype} = 'Markdown';
863 $self->{READMEDATA} = _cleanup_readme_str(to_utf8($gcgi->wparam('README'), 1));
864 length($self->{READMEDATA}) <= 8192
865 or $gcgi->err("README length &gt; 8kb!");
866 my ($cnt, $err) = (0);
867 ($cnt, $err) = $self->_lint_readme if $gcgi->ok;
868 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
871 if ($field_enabled->('hp')) {
872 $self->{hp} = $gcgi->wparam('hp');
873 if ($self->{hp}) {
874 valid_web_url($self->{hp})
875 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
879 # No mucking about with users unless we're a push project
880 if (($self->{loaded} && !$self->{mirror}) ||
881 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
882 my %users = ();
883 my @users = ();
884 foreach my $user ($cgi->multi_param('user')) {
885 if (!exists($users{$user})) {
886 $users{$user} = 1;
887 push(@users, $user) if Girocco::User::does_exist($user, 1);
890 $self->{users} = \@users;
893 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
894 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
895 my $newhead;
896 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
897 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
898 if ($newhead eq $self->{orig_HEAD} ||
899 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
900 $self->{HEAD} = $newhead;
901 } else {
902 $gcgi->err("Invalid default branch (no such ref)");
906 # schedule deletion of tags (will be committed by update() after auth)
907 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
909 if ($field_enabled->('notifymail')) {
910 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
911 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
912 $self->{notifymail} = $newaddrs;
913 } else {
914 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
916 if ($field_enabled->('reverseorder')) {
917 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
919 if ($field_enabled->('summaryonly')) {
920 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
924 if ($field_enabled->('notifytag')) {
925 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
926 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
927 $self->{notifytag} = $newaddrs;
928 } else {
929 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
933 if ($field_enabled->('notifyjson')) {
934 $self->{notifyjson} = $gcgi->wparam('notifyjson');
935 if ($self->{notifyjson}) {
936 valid_web_url($self->{notifyjson})
937 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
939 $self->{jsontype} = $gcgi->wparam('jsontype');
940 defined($self->{jsontype}) && $self->{jsontype} ne "" or
941 $self->{jsontype} = 'application/x-www-form-urlencoded';
942 $self->{jsontype} = lc($self->{jsontype});
943 unless ($self->{jsontype} eq 'application/x-www-form-urlencoded' ||
944 $self->{jsontype} eq 'application/json') {
945 if ($self->{notifyjson}) {
946 $gcgi->err("Invalid JSON Content-Type. Must be 'application/x-www-form-urlencoded' or 'application/json'.");
947 } else {
948 $self->{jsontype} = 'application/x-www-form-urlencoded';
951 $self->{jsonsecret} = $gcgi->wparam('jsonsecret');
952 my $origurl = $self->{orig_notifyjson};
953 defined($origurl) or $origurl = '';
954 $self->{notifyjson} eq $origurl ||
955 $self->{notifyjson} eq "" ||
956 Girocco::Notify::json_test_post($self) or
957 $gcgi->err("JSON notify URL failed POST test.");
960 if ($field_enabled->('notifycia')) {
961 $self->{notifycia} = $gcgi->wparam('notifycia');
962 if ($self->{notifycia}) {
963 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
964 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
968 if ($cgi->param('setstatusupdates')) {
969 my $val = $gcgi->wparam('statusupdates') || '0';
970 $self->{statusupdates} = $val ? 1 : 0;
973 $silent ? $gcgi->ok : !$gcgi->err_check;
976 sub form_defaults {
977 my $self = shift;
979 name => $self->{name},
980 email => $self->{email},
981 url => $self->{url},
982 cleanmirror => $self->{cleanmirror},
983 desc => html_esc($self->{desc}),
984 README => html_esc($self->{READMEDATA}),
985 rmtype => $self->{rmtype},
986 hp => $self->{hp},
987 users => $self->{users},
988 notifymail => html_esc($self->{notifymail}),
989 reverseorder => $self->{reverseorder},
990 summaryonly => $self->{summaryonly},
991 notifytag => html_esc($self->{notifytag}),
992 notifyjson => html_esc($self->{notifyjson}),
993 jsontype => html_esc($self->{jsontype}),
994 jsonsecret => html_esc($self->{jsonsecret}),
995 notifycia => html_esc($self->{notifycia}),
997 __project__ => $self
1001 # return true if $enc_passwd is a match for $plain_passwd
1002 my $_check_passwd_match = sub {
1003 my $enc_passwd = shift;
1004 my $plain_passwd = shift;
1005 defined($enc_passwd) or $enc_passwd = '';
1006 defined($plain_passwd) or $plain_passwd = '';
1007 # $enc_passwd may be crypt or crypt_sha1
1008 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
1009 # It's using sha1-crypt
1010 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
1011 } else {
1012 # It's using crypt
1013 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
1017 sub authenticate {
1018 my $self = shift;
1019 my ($gcgi) = @_;
1021 $self->{ccrypt} or die "Can't authenticate against a project with no password";
1022 defined($self->{cpwd}) or $self->{cpwd} = '';
1023 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
1024 $gcgi->err("Your admin password does not match!");
1025 return 0;
1027 return 1;
1030 # return true if the password from the file is empty or consists of all the same
1031 # character. However, if the project was NOT loaded from the group file
1032 # (!self->{loaded}) then the password is never locked.
1033 # This function does NOT check $Girocco::Config::project_passwords, the caller
1034 # is responsible for doing so if desired. Same for $self->{email}.
1035 sub is_password_locked {
1036 my $self = shift;
1038 $self->{loaded} or return 0;
1039 my $testcrypt = $self->{ccrypt}; # The value from the group file
1040 defined($testcrypt) or $testcrypt = '';
1041 $testcrypt ne '' or return 1; # No password at all
1042 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
1043 return 0; # Not locked
1046 sub _setup {
1047 use POSIX qw(strftime);
1048 my $self = shift;
1049 my ($pushers) = @_;
1050 my $fd;
1052 defined($self->{path}) && $self->{path} ne "" or die "invalid setup call";
1053 $self->_mkdir_forkees unless $self->{adopt};
1055 my $gid;
1056 $self->{adopt} || mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
1057 -d $self->{path} or die "unable to setup nonexistent $self->{path}";
1058 if ($Girocco::Config::owning_group) {
1059 $gid = scalar(getgrnam($Girocco::Config::owning_group));
1060 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
1061 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
1062 } else {
1063 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
1065 delete $ENV{GIT_OBJECT_DIRECTORY};
1066 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
1067 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
1068 or die "git init $self->{path} failed: $?";
1069 # we don't need these two, remove them (they will normally be created empty) if they exist
1070 rmdir $self->{path}."/branches";
1071 rmdir $self->{path}."/remotes";
1072 -d $self->{path}."/info" or mkdir $self->{path}."/info"
1073 or die "info directory does not exist and unable to create it: $!";
1074 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
1075 or die "hooks directory does not exist and unable to create it: $!";
1076 # clean out any kruft that may have come in from the initial template directory
1077 foreach my $cleandir (qw(hooks info)) {
1078 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
1079 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
1080 closedir $hooksdir;
1083 if ($Girocco::Config::owning_group) {
1084 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
1086 # hooks never world writable
1087 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
1088 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.compression', '5') == 0
1089 or die "setting core.compression failed: $?";
1090 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
1091 or die "disabling core.logAllRefUpdates failed: $?";
1092 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
1093 or die "disabling core.ignoreCase failed: $?";
1094 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.hooksPath',
1095 ($Girocco::Config::localhooks ? $self->{path}."/hooks" : $Girocco::Config::reporoot . "/_global/hooks")) == 0
1096 or die "setting core.hooksPath failed: $?";
1097 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'extensions.preciousObjects', 'true') == 0
1098 or die "setting extensions.preciousObjects failed: $?";
1099 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
1100 or die "enabling transfer.fsckObjects failed: $?";
1101 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.unpackLimit', '1') == 0
1102 or die "setting transfer.unpackLimit failed: $?";
1103 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.fsckObjects', 'true') == 0
1104 or die "enabling receive.fsckObjects failed: $?";
1105 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
1106 or die "disabling receive.denyNonFastForwards failed: $?";
1107 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
1108 or die "disabling receive.denyDeleteCurrent failed: $?";
1109 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
1110 or die "disabling receive.autogc failed: $?";
1111 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1112 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
1113 or die "enabling receive.updateServerInfo failed: $?";
1114 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
1115 or die "enabling repack.writeBitmaps failed: $?";
1116 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1117 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
1118 or die "setting girocco.creationtime failed: $?";
1119 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
1120 or die "htmlcache directory does not exist and unable to create it: $!";
1121 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
1122 or die "bundles directory does not exist and unable to create it: $!";
1123 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
1124 or die "reflogs directory does not exist and unable to create it: $!";
1125 foreach my $file (qw(info/lastactivity .delaygc)) {
1126 if (open $fd, '>', $self->{path}."/".$file) {
1127 close $fd;
1128 chmod 0664, $self->{path}."/".$file;
1132 # /info must have right permissions,
1133 # and git init didn't do it for some reason.
1134 # config must have correct permissions.
1135 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
1136 # also make sure /refs, /objects and /htmlcache are correct too.
1137 my ($dmode, $dmodestr, $fmode, $fmodestr);
1138 if ($Girocco::Config::owning_group) {
1139 ($dmode, $dmodestr) = (02775, '02775');
1140 ($fmode, $fmodestr) = (0664, '0664');
1141 } else {
1142 ($dmode, $dmodestr) = (02777, '02777');
1143 ($fmode, $fmodestr) = (0666, '0666');
1145 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
1146 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
1148 foreach my $file (qw(config)) {
1149 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
1151 # these ones are probably not strictly required but are nice to have
1152 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
1153 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
1154 chmod($dmode, $self->{path}."/$dir");
1156 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::htmlcache_owning_group) {
1157 my $htmlgid = scalar(getgrnam($Girocco::Config::htmlcache_owning_group));
1158 if (defined($htmlgid) && $htmlgid ne $gid) {
1159 chown(-1, $htmlgid, $self->{path}."/htmlcache") or die "chgrp $htmlgid $self->{path}/htmlcache failed: $!";
1160 chmod($dmode, $self->{path}."/htmlcache") or die "chmod $dmodestr $self->{path}/htmlcache failed: $!";
1163 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::ctags_owning_group) {
1164 my $ctagsgid = scalar(getgrnam($Girocco::Config::ctags_owning_group));
1165 if (defined($ctagsgid) && $ctagsgid ne $gid) {
1166 chown(-1, $ctagsgid, $self->{path}."/ctags") or die "chgrp $ctagsgid $self->{path}/ctags failed: $!";
1167 chmod($dmode, $self->{path}."/ctags") or die "chmod $dmodestr $self->{path}/ctags failed: $!";
1171 $self->_properties_save;
1172 $self->_alternates_setup unless $self->{noalternates} || $self->{adopt};
1173 $self->_ctags_setup;
1174 $self->_group_remove;
1175 $self->_group_add($pushers);
1176 $self->_hooks_install;
1177 $self->_update_index;
1178 $self->_set_changed;
1179 $self->_set_forkchange(1);
1182 sub premirror {
1183 my $self = shift;
1185 delete $self->{adopt};
1186 $self->_setup(':');
1187 $self->_clonep(1);
1188 if ($Girocco::Config::autogchack) {
1189 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1190 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1192 $self->perm_initialize;
1195 sub conjure {
1196 my $self = shift;
1198 delete $self->{adopt};
1199 $self->_setup;
1200 $self->_nofetch(1);
1201 if ($Girocco::Config::autogchack && $Girocco::Config::autogchack ne "mirror") {
1202 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1203 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1205 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1206 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1207 or die "create-personal-mob-area $self->{name} failed";
1209 $self->perm_initialize;
1212 sub clone {
1213 my $self = shift;
1215 unlink ($self->_clonefail_path()); # Ignore EEXIST error
1216 unlink ($self->_clonelog_path()); # Ignore EEXIST error
1218 use IO::Socket;
1219 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
1220 select((select($sock),$|=1)[0]);
1221 $sock->print("clone ".$self->{name}."\n");
1222 # Just ignore reply, we are going to succeed anyway and the I/O
1223 # would apparently get quite hairy.
1224 $sock->flush();
1225 sleep 2; # *cough*
1226 $sock->close();
1229 # call this after ghost instead of conjure or premirror+clone to adopt a pre-existing Git dir
1230 # ghost must be called with the proper value of $mirror for the to-be-adopted project
1231 # for mirrors the $proj->{url} needs to be set and for push projects the $proj->{users} array ref
1232 sub adopt {
1233 my $self = shift;
1234 my $name = $self->{name};
1236 # Sanity check first
1237 defined($name) && $name ne "" && !$self->{loaded} or return undef;
1238 does_exist($name, 1) or return undef;
1239 defined($self->{path}) && $self->{path} eq $Girocco::Config::reporoot."/$name.git" or return undef;
1240 defined($self->{base_path}) && $self->{base_path} eq $Girocco::Config::reporoot or return undef;
1241 defined($self->{email}) && defined($self->{orig_email}) && defined($self->{mirror}) && ref($self->{users}) eq 'ARRAY'
1242 or return undef;
1243 !defined(Girocco::Project->load($name)) or return undef;
1244 is_git_dir($self->{path}) or return undef;
1245 my $config = read_config_file_hash($self->{path}."/config");
1246 defined($config) && _boolval($config->{"core.bare"}) or die "refusing to adopt non-bare repository";
1247 defined(read_HEAD_symref($self->{path})) or die "refusing to adopt non-symref HEAD repository";
1249 # Adopt the project by creating a new $chroot/etc/group entry and setting up anything that's missing
1250 $self->_nofetch(!$self->{mirror});
1251 $self->{adopt} = 1;
1252 $self->_setup($self->{mirror} ? ":" : "");
1253 delete $self->{adopt};
1254 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
1255 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1256 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1258 if (!$self->{mirror} && $Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1259 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1260 or die "create-personal-mob-area $self->{name} failed";
1262 my $result = $self->perm_initialize;
1263 unlink("$self->{path}/.delaygc") unless $self->is_empty;
1264 # Pick up any pre-existing settings
1265 my $p = Girocco::Project->load($name);
1266 %$self = %$p if defined($p) && $p->{loaded};
1267 $result;
1270 sub _update_users {
1271 my $self = shift;
1273 $self->_group_update;
1274 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
1275 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
1276 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
1277 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
1280 sub update {
1281 my $self = shift;
1283 $self->_properties_save;
1284 $self->_update_users;
1286 if (exists($self->{tags_to_delete})) {
1287 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1290 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1292 $self->_update_index if $self->{email} ne $self->{orig_email};
1293 $self->{orig_email} = $self->{email};
1294 $self->_set_changed;
1299 sub update_password {
1300 my $self = shift;
1301 my ($pwd) = @_;
1303 $self->{crypt} = scrypt_sha1($pwd);
1304 $self->_group_update;
1307 # You can explicitly do this just on a ghost() repository too.
1308 sub delete {
1309 my $self = shift;
1311 if (-d $self->{path}) {
1312 system('rm', '-rf', $self->{path}) == 0
1313 or die "rm -rf $self->{path} failed: $?";
1315 # attempt to clean up any empty fork directories by removing them
1316 my @pelems = split('/', $self->{name});
1317 while (@pelems > 1) {
1318 pop @pelems;
1319 # okay to fail
1320 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1322 $self->_group_remove;
1323 $self->_update_index;
1324 $self->_set_forkchange(1);
1329 # If the project's directory actually exists archive it before deleting it
1330 # Return full path to archived project ("" if none)
1331 sub archive_and_delete {
1332 my $self = shift;
1334 unless (-d $self->{path}) {
1335 $self->delete;
1336 return "";
1339 # archive the project before deletion
1340 use POSIX qw(strftime);
1341 my $destdir = $self->{base_path};
1342 $destdir =~ s,(?<=[^/])/+$,,;
1343 $destdir .= "/_recyclebin/";
1344 $destdir .= $1 if $self->{name} =~ m,^(.*/)[^/]+$,;
1345 my $destbase = $self->{name};
1346 $destbase = $1 if $destbase =~ m,^.*/([^/]+)$,;
1347 my $oldmask = umask();
1348 umask($oldmask & ~0070);
1349 system('mkdir', '-p', $destdir) == 0 && -d $destdir
1350 or die "mkdir -p \"$destdir\" failed: $?";
1351 umask($oldmask);
1352 my $suffix = '';
1353 if (-e "$destdir$destbase.git") {
1354 $suffix = 1;
1355 while (-e "$destdir$destbase~$suffix.git") {
1356 ++$suffix;
1357 last if $suffix >= 10000; # don't get too carried away
1359 $suffix = '~'.$suffix;
1361 not -e "$destdir$destbase$suffix.git"
1362 or die "Unable to compute suitable archive path";
1363 system('mv', $self->{path}, "$destdir$destbase$suffix.git") == 0
1364 or die "mv \"$self->{path}\" \"$destdir$destbase$suffix.git\" failed: $?";
1365 if (!$self->{mirror} && @{$self->{users}}) {
1366 # Remember the user list at recycle time
1367 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1368 'config', 'girocco.recycleusers', join(",", @{$self->{users}}));
1370 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1371 my $recycletime = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1372 # We ought to do something if this fails, but the project has already been moved
1373 # so there's really nothing to be done at this point.
1374 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1375 'config', 'girocco.recycletime', $recycletime);
1377 $self->delete;
1378 return $destdir.$destbase.$suffix.".git";
1381 sub _contains_files {
1382 my $dir = shift;
1383 (-d $dir) or return 0;
1384 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1385 while (my $entry = readdir($dh)) {
1386 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1387 closedir($dh), return 1
1388 if -f "$dir/$entry" ||
1389 -d "$dir/$entry" && _contains_files("$dir/$entry");
1391 closedir($dh);
1392 return 0;
1395 sub has_forks {
1396 my $self = shift;
1398 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1401 # Returns an array of 0 or more array refs, one for each bundle:
1402 # ->[0]: bundle creation time (seconds since epoch)
1403 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1404 # ->[2]: bundle size in bytes
1405 sub bundles {
1406 my $self = shift;
1407 use Time::Local;
1409 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1410 my @blist = ();
1411 if (-d $self->{path}.'/bundles') {{
1412 my $prefix = $self->{name};
1413 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1414 opendir(my $dh, $self->{path}.'/bundles') or last;
1415 while (my $bfile = readdir($dh)) {
1416 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1417 my $ctime = eval {timegm(
1418 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1419 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4))};
1420 next unless $ctime;
1421 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1422 my $f1 = <$bh>;
1423 my $f2 = <$bh>;
1424 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1425 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1426 close($bh);
1427 next unless $f1 && $f2 && $f1 ne $f2;
1428 chomp $f1;
1429 chomp $f2;
1430 next unless -e $f1 && -e $f2;
1431 my $s1 = -s $f1 || 0;
1432 my $s2 = -s $f2 || 0;
1433 next unless $s1 || $s2;
1434 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1436 closedir($dh);
1438 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1439 my %seen = ();
1440 my @result = ();
1441 foreach my $bndl (@blist) {
1442 next if $seen{$bndl->[1]};
1443 $seen{$bndl->[1]} = 1;
1444 push(@result, $bndl);
1446 $self->{bundles} = \@result;
1447 return @result;
1450 sub has_alternates {
1451 my $self = shift;
1452 my $af = $self->{path}.'/objects/info/alternates';
1453 -f $af && -s _ or return 0;
1454 my $nb = 0;
1455 open my $fh, '<', $af or return 1;
1456 while (my $line = <$fh>) {
1457 next if $line =~ /^$/ || $line =~ /^#/;
1458 $nb = 1;
1459 last;
1461 close $fh;
1462 return $nb;
1465 sub has_bundle {
1466 my $self = shift;
1468 return scalar($self->bundles);
1471 sub _has_notifyhook {
1472 my $self = shift;
1473 my $val = $Girocco::Config::default_notifyhook;
1474 defined($self->{'notifyhook'}) and $val = $self->{'notifyhook'};
1475 return (defined($val) && $val ne "") ? $val : undef;
1478 # returns true if any of the notify fields are non-empty
1479 sub has_notify {
1480 my $self = shift;
1481 # We do not ckeck notifycia since it's defunct
1482 return
1483 $self->{'notifymail'} || $self->{'notifytag'} ||
1484 $self->{'notifyjson'} ||
1485 !!$self->_has_notifyhook;
1488 sub is_empty {
1489 # A project is considered empty if the git repository does not
1490 # have any refs. This means packed-refs does not exist or is
1491 # empty or only has lines starting with '#' AND there are no
1492 # files in the refs subdirectory hierarchy (no matter how deep).
1494 my $self = shift;
1496 (-d $self->{path}) or return 0;
1497 if (-e $self->{path}.'/packed-refs') {
1498 open(my $pr, '<', $self->{path}.'/packed-refs')
1499 or die "open $self->{path}./packed-refs failed: $!";
1500 my $foundref = 0;
1501 while (my $ref = <$pr>) {
1502 next if $ref =~ /^#/;
1503 $foundref = 1;
1504 last;
1506 close($pr);
1507 return 0 if $foundref;
1509 (-d $self->{path}.'/refs') or return 1;
1510 return !_contains_files($self->{path}.'/refs');
1513 # returns array:
1514 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1515 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1516 # Both values (if not undef) are seconds since epoch
1517 # Result only considers lastgc and min_gc_interval nothing else
1518 sub next_gc {
1519 my $self = shift;
1520 my $lastgcepoch = parse_any_date($self->{lastgc});
1521 return (undef, undef) unless defined $lastgcepoch;
1522 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1523 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1524 $Girocco::Config::min_mirror_interval));
1527 # returns boolean (0 or 1)
1528 # Attempts to determine whether or not a gc (and corresponding build
1529 # of a .bitmap/.bndl file) will actually take place at the next_gc
1530 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1531 # end up being built depends on whether or not the local object graph
1532 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1533 # is not possible because the object graph will be incomplete,
1534 # but it *is* possible that even though the repository has_alternates,
1535 # it does not actually borrow any objects so a .bitmap/.bndl will build
1536 # in spite of the presence of alternates -- but this is expected to be rare.
1537 # The result is a best guess and false return value is not an absolute
1538 # guarantee that gc will not take place at the next interval, but it probably
1539 # will not if nothing changes in the meantime.
1540 sub needs_gc {
1541 my $self = shift;
1542 my $lgc = parse_any_date($self->{lastgc});
1543 my $lrecv = parse_any_date($self->{lastreceive});
1544 my $lpgc = parse_any_date($self->{lastparentgc});
1545 return 1 unless defined($lgc) && defined($lrecv);
1546 if ($self->has_alternates) {
1547 return 1 unless defined($lpgc);
1548 return 1 unless $lpgc < $lgc;
1550 return 1 unless $lrecv < $lgc;
1551 # We don't try running any "is_dirty" check, so if somehow the
1552 # repository became dirty without updating lastreceive we might
1553 # incorrectly return false instead of true.
1554 return 0;
1557 sub delete_ctag {
1558 my $self = shift;
1559 my ($ctag) = @_;
1561 # sanity check, disallow filenames starting with . .. or /
1562 unlink($self->{path}.'/ctags/'.$ctag)
1563 unless !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1566 # returns new tag count value on success (will always be >= 1) otherwise undef
1567 sub add_ctag {
1568 my $self = shift;
1569 my $ctag = valid_tag(shift);
1570 my $nochanged = shift;
1572 # sanity check, disallow filenames starting with . .. or /
1573 return undef if !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1575 my $val = 0;
1576 my $ct;
1577 if (open $ct, '<', $self->{path}."/ctags/$ctag") {
1578 my $count = <$ct>;
1579 close $ct;
1580 defined $count or $count = '';
1581 chomp $count;
1582 $val = $count =~ /^[1-9]\d*$/ ? $count : 1;
1584 ++$val;
1585 my $oldmask = umask();
1586 umask($oldmask & ~0060);
1587 open $ct, '>', $self->{path}."/ctags/$ctag" and print $ct $val."\n" and close $ct;
1588 $self->_set_changed unless $nochanged;
1589 $self->_set_forkchange unless $nochanged;
1590 umask($oldmask);
1591 return $val;
1594 sub get_ctag_names {
1595 my $self = shift;
1596 my @ctags = ();
1597 opendir(my $dh, $self->{path}.'/ctags')
1598 or return @ctags;
1599 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1600 closedir($dh);
1601 return sort({lc($a) cmp lc($b)} @ctags);
1604 sub get_heads {
1605 my $self = shift;
1606 my $fh;
1607 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1608 defined($heads) or $heads = '';
1609 chomp $heads;
1610 my @res = ();
1611 foreach (split(/\n/, $heads)) {
1612 chomp;
1613 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1614 push @res, $1;
1616 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1617 @res;
1620 sub get_HEAD {
1621 my $self = shift;
1622 my $HEAD = read_HEAD_ref($self->{path});
1623 defined($HEAD) && $HEAD ne "" or die "could not get HEAD";
1624 return $1 if $HEAD =~ m{^refs/heads/(.+)$};
1625 return "[other]" if $HEAD =~ m{^refs/};
1626 return "[detached]" if $HEAD =~ m{^[0-9a-fA-F]{4,}$};
1627 return "[invalid]";
1630 sub set_HEAD {
1631 my $self = shift;
1632 my $newHEAD = shift;
1633 # Cursory checks only -- if you want to break your HEAD, be my guest
1634 if ($newHEAD =~ /^\/|^\.|[\x00-\x1f \x7f\[~^'<>*?\\:]|\@\{|\.\.|\.lock$|\.$|\/$/) {
1635 die "grossly invalid new HEAD: $newHEAD";
1637 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1638 die "could not set HEAD" if ($? >> 8);
1639 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1640 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1643 sub gen_auth {
1644 my $self = shift;
1645 my ($type) = @_;
1646 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1648 $self->{authtype} = $type;
1650 no warnings;
1651 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1653 my $expire = time + 24 * 3600;
1654 my $propval = "# ${type}AUTH $self->{auth} $expire";
1655 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1656 $self->{auth};
1659 sub del_auth {
1660 my $self = shift;
1662 delete $self->{auth};
1663 delete $self->{authtype};
1664 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1667 sub remove_user {
1668 my $self = shift;
1669 my ($username) = @_;
1671 my $before_count = @{$self->{users}};
1672 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1673 return @{$self->{users}} != $before_count;
1676 ### static methods
1678 sub get_forkee_name {
1679 local $_ = $_[0];
1680 (m#^(.*)/.*?$#)[0]; #
1683 sub get_forkee_path {
1684 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1685 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1686 -d $forkee ? $forkee : '';
1689 # Ultimately the full project/fork name could end up being part of a Git ref name
1690 # when a project's forks are combined into one giant repository for efficiency.
1691 # That means that the project/fork name must satisfy the Git ref name requirements:
1693 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1694 # 2. The character with an ASCII value of 0x7F is not allowed
1695 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1696 # 4. The character '/' is a separator and is not allowed within a name
1697 # 5. The name may not start with '.' or end with '.'
1698 # 6. The name may not end with '.lock'
1699 # 7. The name may not contain the '..' sequence
1700 # 8. The name may not contain the '@{' sequence
1701 # 9. If multiple components are used (separated by '/'), no empty '' components
1703 # We also prohibit a trailing '.git' on any path component and futher restrict
1704 # the allowed characters to alphanumeric and [+._-] where names must start with
1705 # an alphanumeric.
1707 sub _valid_name_characters {
1708 local $_ = $_[0];
1709 (not m#^[/+._-]#)
1710 and (not m#//#)
1711 and (not m#\.\.#)
1712 and (not m#/[+._-]#)
1713 and (not m#\./#)
1714 and (not m#\.$#)
1715 and (not m#\.git/#i)
1716 and (not m#\.git$#i)
1717 and (not m#\.idx/#i)
1718 and (not m#\.idx$#i)
1719 and (not m#\.lock/#i)
1720 and (not m#\.lock$#i)
1721 and (not m#\.pack/#i)
1722 and (not m#\.pack$#i)
1723 and (not m#\.bundle/#i)
1724 and (not m#\.bundle$#i)
1725 and (not m#/$#)
1726 and (not m/^[a-fA-F0-9]{38}$/)
1727 and m#^[a-zA-Z0-9/+._-]+$#
1728 and !has_reserved_suffix($_, $_[1], $_[2]);
1731 # $_[0] => prospective project name (WITHOUT trailing .git)
1732 # $_[1] => true to allow orphans (i.e. two-or-more-level-deep projects without a parent)
1733 # (the directory in which the orphan will be created must, however, already exist)
1734 # $_[2] => true to allow orphans w/o needed directory if $_[1] also true (like mkdir -p)
1735 # If $_[0] is a SCALAR ref, ${$_[0]} contains the name and will be untainted on success.
1736 sub valid_name {
1737 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1738 local $_ = $_[0];
1739 my $mayberef_name = $_;
1740 ref($_) eq 'SCALAR' and $_ = $$_;
1741 my $rv = (
1742 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1743 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1744 and ((not m#/#) or -d get_forkee_path($_) or ($_[1] and ($_[2] or -d $Girocco::Config::reporoot.'/'.get_forkee_name($_))))
1745 and (! -f $Girocco::Config::reporoot."/$_.git")
1747 $rv && ref($mayberef_name) eq 'SCALAR' && m|^(.+)$| and $$mayberef_name = $1;
1748 return $rv;
1751 # It's possible that some forks have been kept but the forkee is gone.
1752 # In this case the standard valid_name check is too strict.
1753 # If $_[0] is a SCALAR ref, ${$_[0]} contains the name and will be untainted on success.
1754 sub does_exist {
1755 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1756 my ($mayberef_name, $nodie) = @_;
1757 my $name = ref($mayberef_name) eq 'SCALAR' ? $$mayberef_name : $mayberef_name;
1758 my $okay = (
1759 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1760 and ((not $name =~ m#/#)
1761 or -d get_forkee_path($name)
1762 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1763 (!$okay && $nodie) and return undef;
1764 !$okay and die "tried to query for project with invalid name $name!";
1765 -d $Girocco::Config::reporoot."/$name.git" or return undef;
1766 ref($mayberef_name) eq 'SCALAR' && $name =~ m|^(.+)$| and $$mayberef_name = $1;
1767 return 1;
1770 sub get_full_list {
1771 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1772 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1773 close $fd;
1774 @projects;