toolbox/update-all-config.pl: quiet means quiet
[girocco.git] / Girocco / Project.pm
blob559f773064ba5a1798a434850c92e30502854f36
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 $propfile = $self->_property_path($pname);
262 my $P = lock_file($propfile);
263 chomp $value;
264 $value ne '' and $value .= "\n";
265 if ($nosetsame && -e $propfile && -f _) {
266 if (open my $fd, '<', $propfile) {
267 my $contents = undef;
268 {local $/ = undef; $contents = <$fd>;}
269 close $fd;
270 if (defined($contents) && $contents eq $value) {
271 close $P;
272 unlock_file($propfile, 1);
273 return;
277 $value ne '' and print $P $value;
278 close $P;
279 unlock_file($propfile);
282 sub _cleanup_datetime {
283 my $self = shift;
284 my $k = shift;
285 defined($k) && $k ne "" or return;
286 local $_ = $self->{$k}; defined($_) or $_ = '';
287 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
288 s/\s+/ /gs;
289 s/^\s+//s;
290 s/\s+$//s;
291 my $ts = parse_any_date($_);
292 defined($ts) or $_ = '';
293 /^(.*)$/ and $self->{$k} = $1;
296 sub _cleanup_description {
297 my $self = shift;
298 local $_ = $self->{desc}; defined($_) or $_ = '';
299 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
300 s/\r\n?/\n/gs;
301 s/^\s+//s;
302 s/\s+$//s;
303 /\A(.*)$/m and $self->{desc} = $1;
306 sub _cleanup_readme_str {
307 local $_ = shift; defined($_) or $_ = '';
308 {use bytes; s/[\x00-\x08\x0e-\x1f\x7f]+//gs;}
309 s/\r\n?/\n/gs;
310 s/^\s+//s;
311 s/\s+$//s;
312 $_ eq '' or $_ .= "\n";
313 /^(.*)$/s and $_ = $1;
314 return $_;
317 sub _cleanup_readme {
318 my $self = shift;
319 $self->{README} = _cleanup_readme_str($self->{README});
320 $self->{READMEDATA} = _cleanup_readme_str($self->{READMEDATA});
323 my %rmtypes;
324 BEGIN { %rmtypes = (
325 default => 'Markdown',
327 'text/markdown' => 'Markdown',
328 'text/x-markdown' => 'Markdown',
329 markdown => 'Markdown',
330 md => 'Markdown',
332 'text/plain' => 'Plain Text',
333 'plain text' => 'Plain Text',
334 'plain-text' => 'Plain Text',
335 plain_text => 'Plain Text',
336 plaintext => 'Plain Text',
337 plain => 'Plain Text',
338 text => 'Plain Text',
339 txt => 'Plain Text',
341 'text/html' => 'HTML',
342 html => 'HTML',
343 htm => 'HTML'
346 # if $_[1] is true, return "" instead of default for unknown type
347 sub _normalize_rmtype {
348 my $rmtype = shift;
349 my $nodefault = shift;
350 defined($rmtype) and $rmtype = $rmtypes{lc($rmtype)};
351 defined($rmtype) && $rmtype ne '' or
352 $rmtype = $nodefault ? "" : $rmtypes{'default'};
353 return $rmtype;
356 sub _lint_readme {
357 my $self = shift;
358 my $htmlfrag = shift;
359 defined($htmlfrag) or $htmlfrag = 1;
360 defined($self->{READMEDATA}) or $self->{READMEDATA} = '';
361 $self->{rmtype} = _normalize_rmtype($self->{rmtype});
362 # Empty always just becomes empty with no errors
363 if ($self->{READMEDATA} eq '') {
364 $self->{README} = '';
365 return 0;
367 if ($self->{rmtype} eq 'Plain Text') {
368 # Never any errors with this one
369 my $esc = $self->{READMEDATA};
370 $esc =~ s/&/&amp;/gs;
371 $esc =~ s/</&lt;/gs;
372 $self->{README} = '<pre class="plaintext">' . $esc . '</pre>';
373 return 0;
375 eval { require Markdown; 1 } or do {
376 return (1, "README: Markdown/HTML formats temporarily unavailable");
378 my @errs = ();
379 if ($self->{rmtype} eq 'HTML') {
380 # Legacy HTML support but now sanitized with possible auto-fixup
381 my $output;
382 eval { $output = Markdown::ProcessRaw($self->{READMEDATA},
383 sanitize => 1, xmlcheck => 2, htmlauto => 0); 1; } or
384 do {
385 @errs = split(/\n+/, $@);
386 @errs or push(@errs, 'Invalid HTML');
388 # Make one more attempt with htmlauto in case
389 # that's good enough to fix up the HTML and make it valid
390 eval { $output = Markdown::ProcessRaw($self->{READMEDATA},
391 sanitize => 1, xmlcheck => 2, htmlauto => 1); 1; } and
392 do {
393 @errs = ();
396 !@errs and $self->{README} = (chomp($output),$output);
397 } else {
398 # Markdown format
399 my $output;
400 my $gwbase = url_path($Girocco::Config::gitweburl,1).$self->{name}.'.git';
401 my %mdopts = (
402 sanitize => 1,
403 xmlcheck => 2,
404 yamlmode => 1,
405 yamlvis => 0,
406 keepabs => 1,
407 base_prefix => $self->{name}.'.git',
408 url_prefix => $gwbase . '/blob/HEAD:',
409 img_prefix => $gwbase . '/blob_plain/HEAD:'
411 eval { $output = Markdown::Markdown($self->{READMEDATA}, %mdopts); 1; } or
412 do {
413 @errs = split(/\n+/, $@);
414 @errs or push(@errs, 'Invalid Markdown');
416 !@errs and $self->{README} = (chomp($output),$output);
418 return 0 unless @errs;
419 my @fmterrs = ();
420 foreach (@errs) {
421 $_ = html_esc($_) if $htmlfrag;
422 s/ /\&#160;/gs if $htmlfrag;
423 if ($htmlfrag) {
424 push @fmterrs, 'README: <tt>' . $_ . '</tt>';
425 } else {
426 push @fmterrs, 'README: ' . $_ . "\n";
429 if ($htmlfrag) {
430 return (scalar(@fmterrs), join("<br />\n", @fmterrs));
431 } else {
432 return (scalar(@fmterrs), join("", @fmterrs));
436 sub _properties_load {
437 my $self = shift;
438 my $setprop = sub {
439 my $propval = $self->_property_fget($_);
440 defined($propval) and $self->{$_} = $propval;
442 &$setprop foreach keys %propmap;
443 &$setprop foreach keys %propmapro;
444 do {&$setprop foreach keys %propmapromirror} if $self->{mirror};
445 $self->_readlocalconfigfile
446 unless ref($self->{configfilehash}) eq 'HASH';
447 delete $self->{auth};
448 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
449 defined($val) or $val = '';
450 chomp $val;
451 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
452 my $expire = $3;
453 if (time < $expire) {
454 $self->{authtype} = $1;
455 $self->{auth} = $2;
458 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
459 if (defined($self->{configfilehash}->{'girocco.autogchack'})) {
460 $self->{autogchack} = _boolval($self->{configfilehash}->{'girocco.autogchack'});
463 defined($self->{jsontype}) or $self->{jsontype} = "";
464 $self->{jsontype} = lc($self->{jsontype});
465 $self->{jsontype} eq 'application/x-www-form-urlencoded' || $self->{jsontype} eq 'application/json' or
466 $self->{jsontype} = 'application/x-www-form-urlencoded';
467 defined($self->{jsonsecret}) or $self->{jsonsecret} = "";
468 $self->_cleanup_datetime('lastactivity');
469 $self->_cleanup_description;
470 $self->_cleanup_readme;
471 $self->{rmtype} = _normalize_rmtype($self->{rmtype}, 1);
472 if (!$self->{rmtype}) {
473 # default type is "Markdown" unless README ne '' but READMEDATA eq ''
474 if ($self->{README} ne '' && $self->{READMEDATA} eq '') {
475 # This was the only previously understood format
476 $self->{rmtype} = 'HTML';
477 $self->{READMEDATA} = $self->{README};
478 } else {
479 $self->{rmtype} = _normalize_rmtype(""); # get default type
482 delete $self->{configfilehash};
485 sub _set_bangagain {
486 my $self = shift;
487 my $fd;
488 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
489 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
490 if (open($fd, '>', $self->_bangagain_path)) {
491 close $fd;
492 chmod(0664, $self->_bangagain_path);
497 sub _properties_save {
498 my $self = shift;
499 delete $self->{configfilehash};
500 foreach my $prop (keys %propmap) {
501 $self->_property_fput($prop, $self->{$prop}, 1);
503 $self->_set_bangagain;
506 sub _nofetch_path {
507 my $self = shift;
508 $self->_property_path('.nofetch');
511 sub _nofetch {
512 my $self = shift;
513 my ($nofetch) = @_;
514 my $nf = $self->_nofetch_path;
515 if ($nofetch) {
516 open my $x, '>', $nf or die "nofetch failed: $!";
517 close $x;
518 } else {
519 ! -e $nf or unlink $nf or die "yesfetch failed: $!";
523 sub _banged_path {
524 my $self = shift;
525 $self->_property_path('.banged');
528 sub _bangagain_path {
529 my $self = shift;
530 $self->_property_path('.bangagain');
533 sub _gcp_path {
534 my $self = shift;
535 $self->_property_path('.gc_in_progress');
538 sub _clonelog_path {
539 my $self = shift;
540 $self->_property_path('.clonelog');
543 sub _clonefail_path {
544 my $self = shift;
545 $self->_property_path('.clone_failed');
548 sub _clonep_path {
549 my $self = shift;
550 $self->_property_path('.clone_in_progress');
553 sub _clonep {
554 my $self = shift;
555 my ($nofetch) = @_;
556 my $np = $self->_clonep_path;
557 if ($nofetch) {
558 open my $x, '>', $np or die "clonep failed: $!";
559 close $x;
560 } else {
561 unlink $np or die "clonef failed: $!";
564 sub _alternates_setup {
565 use POSIX qw(:fcntl_h);
566 my $self = shift;
567 return unless $self->{name} =~ m#/#;
568 my $forkee_name = get_forkee_name($self->{name});
569 my $forkee_path = get_forkee_path($self->{name});
570 return unless -d $forkee_path;
571 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
572 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
573 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
574 mkdir $self->{path}.'/objects/pack'; chmod 02775, $self->{path}.'/objects/pack';
576 # If somehow either our objects/pack or the prospective alternate's pack
577 # directory does not exist decline to set up any alternates
578 my $altpath = "$forkee_path/objects";
579 -d $self->{path}.'/objects/pack' && -d $altpath.'/pack' or return;
581 # If our objects/pack and the prospective alternate's pack directory
582 # do not share the same device then decline to set up any alternates
583 my ($selfdev) = stat($self->{path}.'/objects/pack');
584 my ($altdev) = stat($altpath.'/pack');
585 defined($selfdev) && defined($altdev) && $selfdev ne "" && $altdev ne "" && $selfdev == $altdev or return;
587 # We set up both alternates and http_alternates since we cannot use
588 # relative path in alternates - that doesn't work recursively.
590 my $filename = $self->{path}.'/objects/info/alternates';
591 open my $x, '>', $filename or die "alternates failed: $!";
592 print $x "$altpath\n";
593 close $x;
594 chmod 0664, $filename or warn "cannot chmod $filename: $!";
596 if ($Girocco::Config::httppullurl) {
597 $filename = $self->{path}.'/objects/info/http-alternates';
598 open my $x, '>', $filename or die "http-alternates failed: $!";
599 my $upfork = $forkee_name;
600 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
601 close $x;
602 chmod 0664, $filename or warn "cannot chmod $filename: $!";
605 # copy lastactivity from the parent project
606 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
607 my $activity = <$x>;
608 close $x;
609 last unless $activity;
610 open $x, '>', $self->{path}.'/info/lastactivity' or last;
611 print $x $activity;
612 close $x;
613 chomp $activity;
614 $self->{'lastactivity'} = $activity;
617 # copy refs from parent project
618 my $dupout;
619 open $dupout, '>&1' or
620 die "could not dup STDOUT_FILENO: $!";
621 my $packedrefsfd = POSIX::open("$self->{path}/packed-refs", O_WRONLY|O_TRUNC|O_CREAT, 0664);
622 defined($packedrefsfd) && $packedrefsfd >= 0 or die "could not open fork's packed-refs file for writing: $!";
623 POSIX::dup2($packedrefsfd, 1) or
624 die "could not dup2 STDOUT_FILENO: $!";
625 POSIX::close($packedrefsfd);
626 my $result = system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
627 my $resultstr = $!;
628 POSIX::dup2(fileno($dupout), 1);
629 close($dupout);
630 $result == 0 or die "could not create fork's packed-refs file data: $resultstr";
631 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
633 # initialize HEAD
634 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
635 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
636 chomp $HEAD;
637 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
638 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
641 sub _set_changed {
642 my $self = shift;
643 my $fd;
644 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
647 sub _set_forkchange {
648 my $self = shift;
649 my $changedtoo = shift;
650 return unless $self->{name} =~ m#/#;
651 my $forkee_path = get_forkee_path($self->{name});
652 return unless -d $forkee_path;
653 # mark forkee as changed
654 my $fd;
655 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
656 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
657 return if -e $forkee_path.'/htmlcache/summary.forkchange';
658 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
661 sub _ctags_setup {
662 my $self = shift;
663 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
664 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
667 sub _group_add {
668 my $self = shift;
669 my ($xtra) = @_;
670 $xtra .= join(',', @{$self->{users}});
671 my $crypt = $self->{crypt};
672 defined($crypt) or $crypt = 'unknown';
673 filedb_atomic_append(jailed_file('/etc/group'),
674 join(':', $self->{name}, $crypt, '\i', $xtra));
677 sub _group_update {
678 my $self = shift;
679 my $xtra = join(',', @{$self->{users}});
680 filedb_atomic_edit(jailed_file('/etc/group'),
681 sub {
682 $_ = $_[0];
683 chomp;
684 if ($self->{name} eq (split /:/)[0]) {
685 # preserve readonly flag
686 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
687 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
688 } else {
689 return "$_\n";
695 sub _group_remove {
696 my $self = shift;
697 filedb_atomic_edit(jailed_file('/etc/group'),
698 sub {
699 $self->{name} ne (split /:/)[0] and return $_;
704 sub _hook_path {
705 my $self = shift;
706 my ($name) = @_;
707 $self->{path}.'/hooks/'.$name;
710 sub _hook_install {
711 my $self = shift;
712 my ($name) = @_;
713 my $hooksdir = $self->{path}.'/hooks';
714 my $oldmask = umask();
715 umask($oldmask & ~0070);
716 -d $hooksdir or mkdir $hooksdir or
717 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
718 umask($oldmask);
719 my $globalhooks = $Girocco::Config::reporoot . "/_global/hooks";
720 -f "$globalhooks/$name" && -r _ or die "cannot find hook $name: $!";
721 ! -e $self->_hook_path($name) || unlink($self->_hook_path($name)) && ! -e $self->_hook_path($name) or
722 die "hooks directory contains unremovable pre-existing hook $name: $!";
723 symlink("$globalhooks/$name", $self->_hook_path($name)) or
724 die "cannot create hook $name symlink: $!";
727 sub _hooks_install {
728 my $self = shift;
729 foreach my $hook ('pre-auto-gc', 'pre-receive', 'post-commit', 'post-receive', 'update') {
730 $self->_hook_install($hook);
734 # private constructor, do not use
735 sub _new {
736 my $class = shift;
737 my ($name, $base_path, $path, $orphan, $optp) = @_;
738 does_exist(\$name,1) || valid_name(\$name, $orphan, $optp) or die "refusing to create project with invalid name ($name)!";
739 $path ||= "$base_path/$name.git";
740 my $proj = { name => $name, base_path => $base_path, path => $path };
742 bless $proj, $class;
745 # public constructor #0
746 # creates a virtual project not connected to disk image
747 # you can conjure() it later to disk
748 sub ghost {
749 my $class = shift;
750 my ($name, $mirror, $orphan, $optp) = @_;
751 my $self = $class->_new($name, $Girocco::Config::reporoot, undef, $orphan, $optp);
752 $self->{users} = [];
753 $self->{mirror} = $mirror;
754 $self->{email} = $self->{orig_email} = '';
755 $self->{notifyjson} = $self->{orig_notifyjson} = '';
756 $self;
759 # public constructor #1
760 sub load {
761 my $class = shift;
762 my $name = shift || '';
764 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
765 my $r = qr/^\Q$name\E:/;
766 foreach (grep /$r/, <$fd>) {
767 chomp;
769 my $self = $class->_new($name, $Girocco::Config::reporoot);
770 (-d $self->{path} && $self->_readlocalconfigfile(1))
771 or die "invalid path (".$self->{path}.") for project ".$self->{name};
773 my (undef, $crypt, $gid, $ulist) = split /:/;
774 $gid =~ /^(\d+)$/ or next; $self->{gid} = $1;
775 { use bytes;
776 $crypt =~ /^([^:\x00-\x1F\x7F-\xFF]*)$/ or next; $self->{crypt} = $1; }
777 defined($ulist) or $ulist = '';
778 $ulist =~ /^((?:[a-zA-Z0-9][a-zA-Z0-9+._-]*(?:,[a-zA-Z0-9][a-zA-Z0-9+._-]*)*)?)$/ or next;
779 $self->{users} = [split /,/, $1];
780 $self->{HEAD} = $self->get_HEAD;
781 $self->{orig_HEAD} = $self->{HEAD};
782 $self->{orig_users} = [@{$self->{users}}];
783 $self->{mirror} = ! -e $self->_nofetch_path;
784 $self->{banged} = -e $self->_banged_path if $self->{mirror};
785 $self->{gc_in_progress} = -e $self->_gcp_path;
786 $self->{clone_in_progress} = -e $self->_clonep_path;
787 $self->{clone_logged} = -e $self->_clonelog_path;
788 $self->{clone_failed} = -e $self->_clonefail_path;
789 $self->{ccrypt} = $self->{crypt};
791 $self->_properties_load;
792 $self->{orig_email} = $self->{email};
793 $self->{orig_notifyjson} = $self->{notifyjson};
794 $self->{loaded} = 1; # indicates self was loaded from etc/group file
795 close $fd;
796 return $self;
798 close $fd;
799 undef;
802 # $proj may not be in sane state if this returns false!
803 # fields listed in %$metadata_fields that are NOT also
804 # in @Girocco::Config::project_fields are totally ignored!
805 sub cgi_fill {
806 my $self = shift;
807 my ($gcgi, $silent) = @_;
808 my $cgi = $gcgi->cgi;
809 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
810 my $field_enabled = sub {
811 defined($cgi->param($_[0])) &&
812 (!exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]}))};
814 my $pwd = $cgi->param('pwd');
815 my $pwd2 = $cgi->param('pwd2');
816 # in case passwords are disabled
817 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd2 = '';
818 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
819 $gcgi->err("Empty passwords are not permitted.");
821 if ($pwd ne '' or not $self->{crypt}) {
822 $self->{crypt} = scrypt_sha1($pwd);
824 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
825 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
828 $self->{cpwd} = $cgi->param('cpwd');
830 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
831 my $newtype = $forkee ? 'fork' : 'project';
832 length($project) <= 64
833 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
835 if ($Girocco::Config::project_owners eq 'email') {
836 $self->{email} = $gcgi->wparam('email');
837 valid_email($self->{email})
838 or $gcgi->err("Your email sure looks weird...?");
839 length($self->{email}) <= 96
840 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
843 # No setting the url unless we're either new or an existing mirror!
844 unless ($self->{loaded} && !$self->{mirror}) {
845 $self->{url} = $gcgi->wparam('url') ;
846 if ($field_enabled->('cleanmirror')) {
847 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
850 # Always validate the url if we're an existing mirror
851 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
852 # Always allow the url to be left unchanged without validation when editing
853 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
854 valid_repo_url($self->{url})
855 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
856 if ($Girocco::Config::restrict_mirror_hosts) {
857 my $mh = extract_url_hostname($self->{url});
858 is_dns_hostname($mh)
859 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
860 !is_our_hostname($mh)
861 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
865 if ($field_enabled->('desc')) {
866 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
867 length($self->{desc}) <= 1024
868 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
871 if ($field_enabled->('README')) {
872 $self->{rmtype} = $rmtypes{lc($gcgi->wparam('rmtype')||'')};
873 if (!$self->{rmtype}) {
874 $gcgi->err("Invalid README Format. Must be 'Markdown', 'Plain Text' or 'HTML'.");
875 $self->{rmtype} = 'Markdown';
877 $self->{READMEDATA} = _cleanup_readme_str(to_utf8($gcgi->wparam('README'), 1));
878 length($self->{READMEDATA}) <= 8192
879 or $gcgi->err("README length &gt; 8kb!");
880 my ($cnt, $err) = (0);
881 ($cnt, $err) = $self->_lint_readme if $gcgi->ok;
882 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
885 if ($field_enabled->('hp')) {
886 $self->{hp} = $gcgi->wparam('hp');
887 if ($self->{hp}) {
888 valid_web_url($self->{hp})
889 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
893 # No mucking about with users unless we're a push project
894 if (($self->{loaded} && !$self->{mirror}) ||
895 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
896 my %users = ();
897 my @users = ();
898 foreach my $user ($cgi->multi_param('user')) {
899 if (!exists($users{$user})) {
900 $users{$user} = 1;
901 push(@users, $user) if Girocco::User::does_exist($user, 1);
904 $self->{users} = \@users;
907 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
908 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
909 my $newhead;
910 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
911 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
912 if ($newhead eq $self->{orig_HEAD} ||
913 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
914 $self->{HEAD} = $newhead;
915 } else {
916 $gcgi->err("Invalid default branch (no such ref)");
920 # schedule deletion of tags (will be committed by update() after auth)
921 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
923 if ($field_enabled->('notifymail')) {
924 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
925 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
926 $self->{notifymail} = $newaddrs;
927 } else {
928 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
930 if ($field_enabled->('reverseorder')) {
931 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
933 if ($field_enabled->('summaryonly')) {
934 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
938 if ($field_enabled->('notifytag')) {
939 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
940 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
941 $self->{notifytag} = $newaddrs;
942 } else {
943 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
947 if ($field_enabled->('notifyjson')) {
948 $self->{notifyjson} = $gcgi->wparam('notifyjson');
949 if ($self->{notifyjson}) {
950 valid_web_url($self->{notifyjson})
951 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
953 $self->{jsontype} = $gcgi->wparam('jsontype');
954 defined($self->{jsontype}) && $self->{jsontype} ne "" or
955 $self->{jsontype} = 'application/x-www-form-urlencoded';
956 $self->{jsontype} = lc($self->{jsontype});
957 unless ($self->{jsontype} eq 'application/x-www-form-urlencoded' ||
958 $self->{jsontype} eq 'application/json') {
959 if ($self->{notifyjson}) {
960 $gcgi->err("Invalid JSON Content-Type. Must be 'application/x-www-form-urlencoded' or 'application/json'.");
961 } else {
962 $self->{jsontype} = 'application/x-www-form-urlencoded';
965 $self->{jsonsecret} = $gcgi->wparam('jsonsecret');
966 my $origurl = $self->{orig_notifyjson};
967 defined($origurl) or $origurl = '';
968 $self->{notifyjson} eq $origurl ||
969 $self->{notifyjson} eq "" ||
970 Girocco::Notify::json_test_post($self) or
971 $gcgi->err("JSON notify URL failed POST test.");
974 if ($field_enabled->('notifycia')) {
975 $self->{notifycia} = $gcgi->wparam('notifycia');
976 if ($self->{notifycia}) {
977 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
978 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
982 if ($cgi->param('setstatusupdates')) {
983 my $val = $gcgi->wparam('statusupdates') || '0';
984 $self->{statusupdates} = $val ? 1 : 0;
987 $silent ? $gcgi->ok : !$gcgi->err_check;
990 sub form_defaults {
991 my $self = shift;
993 name => $self->{name},
994 email => $self->{email},
995 url => $self->{url},
996 cleanmirror => $self->{cleanmirror},
997 desc => html_esc($self->{desc}),
998 README => html_esc($self->{READMEDATA}),
999 rmtype => $self->{rmtype},
1000 hp => $self->{hp},
1001 users => $self->{users},
1002 notifymail => html_esc($self->{notifymail}),
1003 reverseorder => $self->{reverseorder},
1004 summaryonly => $self->{summaryonly},
1005 notifytag => html_esc($self->{notifytag}),
1006 notifyjson => html_esc($self->{notifyjson}),
1007 jsontype => html_esc($self->{jsontype}),
1008 jsonsecret => html_esc($self->{jsonsecret}),
1009 notifycia => html_esc($self->{notifycia}),
1011 __project__ => $self
1015 # return true if $enc_passwd is a match for $plain_passwd
1016 my $_check_passwd_match = sub {
1017 my $enc_passwd = shift;
1018 my $plain_passwd = shift;
1019 defined($enc_passwd) or $enc_passwd = '';
1020 defined($plain_passwd) or $plain_passwd = '';
1021 # $enc_passwd may be crypt or crypt_sha1
1022 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
1023 # It's using sha1-crypt
1024 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
1025 } else {
1026 # It's using crypt
1027 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
1031 sub authenticate {
1032 my $self = shift;
1033 my ($gcgi) = @_;
1035 $self->{ccrypt} or die "Can't authenticate against a project with no password";
1036 defined($self->{cpwd}) or $self->{cpwd} = '';
1037 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
1038 $gcgi->err("Your admin password does not match!");
1039 return 0;
1041 return 1;
1044 # return true if the password from the file is empty or consists of all the same
1045 # character. However, if the project was NOT loaded from the group file
1046 # (!self->{loaded}) then the password is never locked.
1047 # This function does NOT check $Girocco::Config::project_passwords, the caller
1048 # is responsible for doing so if desired. Same for $self->{email}.
1049 sub is_password_locked {
1050 my $self = shift;
1052 $self->{loaded} or return 0;
1053 my $testcrypt = $self->{ccrypt}; # The value from the group file
1054 defined($testcrypt) or $testcrypt = '';
1055 $testcrypt ne '' or return 1; # No password at all
1056 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
1057 return 0; # Not locked
1060 sub _setup {
1061 use POSIX qw(strftime);
1062 my $self = shift;
1063 my ($pushers) = @_;
1064 my $fd;
1066 defined($self->{path}) && $self->{path} ne "" or die "invalid setup call";
1067 $self->_mkdir_forkees unless $self->{adopt};
1069 my $gid;
1070 $self->{adopt} || mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
1071 -d $self->{path} or die "unable to setup nonexistent $self->{path}";
1072 if ($Girocco::Config::owning_group) {
1073 $gid = scalar(getgrnam($Girocco::Config::owning_group));
1074 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
1075 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
1076 } else {
1077 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
1079 delete $ENV{GIT_OBJECT_DIRECTORY};
1080 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
1081 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
1082 or die "git init $self->{path} failed: $?";
1083 # we don't need these two, remove them (they will normally be created empty) if they exist
1084 rmdir $self->{path}."/branches";
1085 rmdir $self->{path}."/remotes";
1086 -d $self->{path}."/info" or mkdir $self->{path}."/info"
1087 or die "info directory does not exist and unable to create it: $!";
1088 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
1089 or die "hooks directory does not exist and unable to create it: $!";
1090 # clean out any kruft that may have come in from the initial template directory
1091 foreach my $cleandir (qw(hooks info)) {
1092 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
1093 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
1094 closedir $hooksdir;
1097 if ($Girocco::Config::owning_group) {
1098 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
1100 # hooks never world writable
1101 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
1102 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.compression', '5') == 0
1103 or die "setting core.compression failed: $?";
1104 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
1105 or die "disabling core.logAllRefUpdates failed: $?";
1106 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
1107 or die "disabling core.ignoreCase failed: $?";
1108 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.hooksPath',
1109 ($Girocco::Config::localhooks ? $self->{path}."/hooks" : $Girocco::Config::reporoot . "/_global/hooks")) == 0
1110 or die "setting core.hooksPath failed: $?";
1111 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'extensions.preciousObjects', 'true') == 0
1112 or die "setting extensions.preciousObjects failed: $?";
1113 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
1114 or die "enabling transfer.fsckObjects failed: $?";
1115 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.unpackLimit', '1') == 0
1116 or die "setting transfer.unpackLimit failed: $?";
1117 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.fsckObjects', 'true') == 0
1118 or die "enabling receive.fsckObjects failed: $?";
1119 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
1120 or die "disabling receive.denyNonFastForwards failed: $?";
1121 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
1122 or die "disabling receive.denyDeleteCurrent failed: $?";
1123 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
1124 or die "disabling receive.autogc failed: $?";
1125 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1126 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
1127 or die "enabling receive.updateServerInfo failed: $?";
1128 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
1129 or die "enabling repack.writeBitmaps failed: $?";
1130 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1131 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
1132 or die "setting girocco.creationtime failed: $?";
1133 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
1134 or die "htmlcache directory does not exist and unable to create it: $!";
1135 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
1136 or die "bundles directory does not exist and unable to create it: $!";
1137 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
1138 or die "reflogs directory does not exist and unable to create it: $!";
1139 foreach my $file (qw(info/lastactivity .delaygc)) {
1140 if (open $fd, '>', $self->{path}."/".$file) {
1141 close $fd;
1142 chmod 0664, $self->{path}."/".$file;
1146 # /info must have right permissions,
1147 # and git init didn't do it for some reason.
1148 # config must have correct permissions.
1149 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
1150 # also make sure /refs, /objects and /htmlcache are correct too.
1151 my ($dmode, $dmodestr, $fmode, $fmodestr);
1152 if ($Girocco::Config::owning_group) {
1153 ($dmode, $dmodestr) = (02775, '02775');
1154 ($fmode, $fmodestr) = (0664, '0664');
1155 } else {
1156 ($dmode, $dmodestr) = (02777, '02777');
1157 ($fmode, $fmodestr) = (0666, '0666');
1159 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
1160 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
1162 foreach my $file (qw(config)) {
1163 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
1165 # these ones are probably not strictly required but are nice to have
1166 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
1167 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
1168 chmod($dmode, $self->{path}."/$dir");
1170 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::htmlcache_owning_group) {
1171 my $htmlgid = scalar(getgrnam($Girocco::Config::htmlcache_owning_group));
1172 if (defined($htmlgid) && $htmlgid ne $gid) {
1173 chown(-1, $htmlgid, $self->{path}."/htmlcache") or die "chgrp $htmlgid $self->{path}/htmlcache failed: $!";
1174 chmod($dmode, $self->{path}."/htmlcache") or die "chmod $dmodestr $self->{path}/htmlcache failed: $!";
1177 if ($Girocco::Config::owning_group && defined($gid) && $Girocco::Config::ctags_owning_group) {
1178 my $ctagsgid = scalar(getgrnam($Girocco::Config::ctags_owning_group));
1179 if (defined($ctagsgid) && $ctagsgid ne $gid) {
1180 chown(-1, $ctagsgid, $self->{path}."/ctags") or die "chgrp $ctagsgid $self->{path}/ctags failed: $!";
1181 chmod($dmode, $self->{path}."/ctags") or die "chmod $dmodestr $self->{path}/ctags failed: $!";
1185 $self->_properties_save;
1186 $self->_alternates_setup unless $self->{noalternates} || $self->{adopt};
1187 $self->_ctags_setup;
1188 $self->_group_remove;
1189 $self->_group_add($pushers);
1190 $self->_hooks_install;
1191 $self->_update_index;
1192 $self->_set_changed;
1193 $self->_set_forkchange(1);
1196 sub premirror {
1197 my $self = shift;
1199 delete $self->{adopt};
1200 $self->_setup(':');
1201 $self->_clonep(1);
1202 if ($Girocco::Config::autogchack) {
1203 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1204 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1206 $self->perm_initialize;
1209 sub conjure {
1210 my $self = shift;
1212 delete $self->{adopt};
1213 $self->_setup;
1214 $self->_nofetch(1);
1215 if ($Girocco::Config::autogchack && $Girocco::Config::autogchack ne "mirror") {
1216 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1217 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1219 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1220 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1221 or die "create-personal-mob-area $self->{name} failed";
1223 $self->perm_initialize;
1226 sub clone {
1227 my $self = shift;
1229 unlink ($self->_clonefail_path()); # Ignore EEXIST error
1230 unlink ($self->_clonelog_path()); # Ignore EEXIST error
1232 use IO::Socket;
1233 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
1234 select((select($sock),$|=1)[0]);
1235 $sock->print("clone ".$self->{name}."\n");
1236 # Just ignore reply, we are going to succeed anyway and the I/O
1237 # would apparently get quite hairy.
1238 $sock->flush();
1239 sleep 2; # *cough*
1240 $sock->close();
1243 # call this after ghost instead of conjure or premirror+clone to adopt a pre-existing Git dir
1244 # ghost must be called with the proper value of $mirror for the to-be-adopted project
1245 # for mirrors the $proj->{url} needs to be set and for push projects the $proj->{users} array ref
1246 sub adopt {
1247 my $self = shift;
1248 my $name = $self->{name};
1250 # Sanity check first
1251 defined($name) && $name ne "" && !$self->{loaded} or return undef;
1252 does_exist($name, 1) or return undef;
1253 defined($self->{path}) && $self->{path} eq $Girocco::Config::reporoot."/$name.git" or return undef;
1254 defined($self->{base_path}) && $self->{base_path} eq $Girocco::Config::reporoot or return undef;
1255 defined($self->{email}) && defined($self->{orig_email}) && defined($self->{mirror}) && ref($self->{users}) eq 'ARRAY'
1256 or return undef;
1257 !defined(Girocco::Project->load($name)) or return undef;
1258 is_git_dir($self->{path}) or return undef;
1259 my $config = read_config_file_hash($self->{path}."/config");
1260 defined($config) && _boolval($config->{"core.bare"}) or die "refusing to adopt non-bare repository";
1261 defined(read_HEAD_symref($self->{path})) or die "refusing to adopt non-symref HEAD repository";
1263 # Adopt the project by creating a new $chroot/etc/group entry and setting up anything that's missing
1264 $self->_nofetch(!$self->{mirror});
1265 $self->{adopt} = 1;
1266 $self->_setup($self->{mirror} ? ":" : "");
1267 delete $self->{adopt};
1268 if ($Girocco::Config::autogchack && ($self->{mirror} || $Girocco::Config::autogchack ne "mirror")) {
1269 system("$Girocco::Config::basedir/jobd/maintain-auto-gc-hack.sh", $self->{name}) == 0
1270 or die "maintain-auto-gc-hack.sh $self->{name} failed";
1272 if (!$self->{mirror} && $Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
1273 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
1274 or die "create-personal-mob-area $self->{name} failed";
1276 my $result = $self->perm_initialize;
1277 unlink("$self->{path}/.delaygc") unless $self->is_empty;
1278 # Pick up any pre-existing settings
1279 my $p = Girocco::Project->load($name);
1280 %$self = %$p if defined($p) && $p->{loaded};
1281 $result;
1284 sub _update_users {
1285 my $self = shift;
1287 $self->_group_update;
1288 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
1289 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
1290 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
1291 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
1294 sub update {
1295 my $self = shift;
1297 $self->_properties_save;
1298 $self->_update_users;
1300 if (exists($self->{tags_to_delete})) {
1301 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1304 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1306 $self->_update_index if $self->{email} ne $self->{orig_email};
1307 $self->{orig_email} = $self->{email};
1308 $self->_set_changed;
1313 sub update_password {
1314 my $self = shift;
1315 my ($pwd) = @_;
1317 $self->{crypt} = scrypt_sha1($pwd);
1318 $self->_group_update;
1321 # You can explicitly do this just on a ghost() repository too.
1322 sub delete {
1323 my $self = shift;
1325 if (-d $self->{path}) {
1326 system('rm', '-rf', $self->{path}) == 0
1327 or die "rm -rf $self->{path} failed: $?";
1329 # attempt to clean up any empty fork directories by removing them
1330 my @pelems = split('/', $self->{name});
1331 while (@pelems > 1) {
1332 pop @pelems;
1333 # okay to fail
1334 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1336 $self->_group_remove;
1337 $self->_update_index;
1338 $self->_set_forkchange(1);
1343 # If the project's directory actually exists archive it before deleting it
1344 # Return full path to archived project ("" if none)
1345 sub archive_and_delete {
1346 my $self = shift;
1348 unless (-d $self->{path}) {
1349 $self->delete;
1350 return "";
1353 # archive the project before deletion
1354 use POSIX qw(strftime);
1355 my $destdir = $self->{base_path};
1356 $destdir =~ s,(?<=[^/])/+$,,;
1357 $destdir .= "/_recyclebin/";
1358 $destdir .= $1 if $self->{name} =~ m,^(.*/)[^/]+$,;
1359 my $destbase = $self->{name};
1360 $destbase = $1 if $destbase =~ m,^.*/([^/]+)$,;
1361 my $oldmask = umask();
1362 umask($oldmask & ~0070);
1363 system('mkdir', '-p', $destdir) == 0 && -d $destdir
1364 or die "mkdir -p \"$destdir\" failed: $?";
1365 umask($oldmask);
1366 my $suffix = '';
1367 if (-e "$destdir$destbase.git") {
1368 $suffix = 1;
1369 while (-e "$destdir$destbase~$suffix.git") {
1370 ++$suffix;
1371 last if $suffix >= 10000; # don't get too carried away
1373 $suffix = '~'.$suffix;
1375 not -e "$destdir$destbase$suffix.git"
1376 or die "Unable to compute suitable archive path";
1377 system('mv', $self->{path}, "$destdir$destbase$suffix.git") == 0
1378 or die "mv \"$self->{path}\" \"$destdir$destbase$suffix.git\" failed: $?";
1379 if (!$self->{mirror} && @{$self->{users}}) {
1380 # Remember the user list at recycle time
1381 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1382 'config', 'girocco.recycleusers', join(",", @{$self->{users}}));
1384 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
1385 my $recycletime = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
1386 # We ought to do something if this fails, but the project has already been moved
1387 # so there's really nothing to be done at this point.
1388 system($Girocco::Config::git_bin, '--git-dir='.$destdir.$destbase.$suffix.".git",
1389 'config', 'girocco.recycletime', $recycletime);
1391 $self->delete;
1392 return $destdir.$destbase.$suffix.".git";
1395 sub _contains_files {
1396 my $dir = shift;
1397 (-d $dir) or return 0;
1398 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1399 while (my $entry = readdir($dh)) {
1400 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1401 closedir($dh), return 1
1402 if -f "$dir/$entry" ||
1403 -d "$dir/$entry" && _contains_files("$dir/$entry");
1405 closedir($dh);
1406 return 0;
1409 sub has_forks {
1410 my $self = shift;
1412 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1415 # Returns an array of 0 or more array refs, one for each bundle:
1416 # ->[0]: bundle creation time (seconds since epoch)
1417 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1418 # ->[2]: bundle size in bytes
1419 sub bundles {
1420 my $self = shift;
1421 use Time::Local;
1423 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1424 my @blist = ();
1425 if (-d $self->{path}.'/bundles') {{
1426 my $prefix = $self->{name};
1427 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1428 opendir(my $dh, $self->{path}.'/bundles') or last;
1429 while (my $bfile = readdir($dh)) {
1430 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1431 my $ctime = eval {timegm(
1432 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1433 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4))};
1434 next unless $ctime;
1435 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1436 my $f1 = <$bh>;
1437 my $f2 = <$bh>;
1438 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1439 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1440 close($bh);
1441 next unless $f1 && $f2 && $f1 ne $f2;
1442 chomp $f1;
1443 chomp $f2;
1444 next unless -e $f1 && -e $f2;
1445 my $s1 = -s $f1 || 0;
1446 my $s2 = -s $f2 || 0;
1447 next unless $s1 || $s2;
1448 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1450 closedir($dh);
1452 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1453 my %seen = ();
1454 my @result = ();
1455 foreach my $bndl (@blist) {
1456 next if $seen{$bndl->[1]};
1457 $seen{$bndl->[1]} = 1;
1458 push(@result, $bndl);
1460 $self->{bundles} = \@result;
1461 return @result;
1464 sub has_alternates {
1465 my $self = shift;
1466 my $af = $self->{path}.'/objects/info/alternates';
1467 -f $af && -s _ or return 0;
1468 my $nb = 0;
1469 open my $fh, '<', $af or return 1;
1470 while (my $line = <$fh>) {
1471 next if $line =~ /^$/ || $line =~ /^#/;
1472 $nb = 1;
1473 last;
1475 close $fh;
1476 return $nb;
1479 sub has_bundle {
1480 my $self = shift;
1482 return scalar($self->bundles);
1485 sub _has_notifyhook {
1486 my $self = shift;
1487 my $val = $Girocco::Config::default_notifyhook;
1488 defined($self->{'notifyhook'}) and $val = $self->{'notifyhook'};
1489 return (defined($val) && $val ne "") ? $val : undef;
1492 # returns true if any of the notify fields are non-empty
1493 sub has_notify {
1494 my $self = shift;
1495 # We do not ckeck notifycia since it's defunct
1496 return
1497 $self->{'notifymail'} || $self->{'notifytag'} ||
1498 $self->{'notifyjson'} ||
1499 !!$self->_has_notifyhook;
1502 sub is_empty {
1503 # A project is considered empty if the git repository does not
1504 # have any refs. This means packed-refs does not exist or is
1505 # empty or only has lines starting with '#' AND there are no
1506 # files in the refs subdirectory hierarchy (no matter how deep).
1508 my $self = shift;
1510 (-d $self->{path}) or return 0;
1511 if (-e $self->{path}.'/packed-refs') {
1512 open(my $pr, '<', $self->{path}.'/packed-refs')
1513 or die "open $self->{path}./packed-refs failed: $!";
1514 my $foundref = 0;
1515 while (my $ref = <$pr>) {
1516 next if $ref =~ /^#/;
1517 $foundref = 1;
1518 last;
1520 close($pr);
1521 return 0 if $foundref;
1523 (-d $self->{path}.'/refs') or return 1;
1524 return !_contains_files($self->{path}.'/refs');
1527 # returns array:
1528 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1529 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1530 # Both values (if not undef) are seconds since epoch
1531 # Result only considers lastgc and min_gc_interval nothing else
1532 sub next_gc {
1533 my $self = shift;
1534 my $lastgcepoch = parse_any_date($self->{lastgc});
1535 return (undef, undef) unless defined $lastgcepoch;
1536 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1537 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1538 $Girocco::Config::min_mirror_interval));
1541 # returns boolean (0 or 1)
1542 # Attempts to determine whether or not a gc (and corresponding build
1543 # of a .bitmap/.bndl file) will actually take place at the next_gc
1544 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1545 # end up being built depends on whether or not the local object graph
1546 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1547 # is not possible because the object graph will be incomplete,
1548 # but it *is* possible that even though the repository has_alternates,
1549 # it does not actually borrow any objects so a .bitmap/.bndl will build
1550 # in spite of the presence of alternates -- but this is expected to be rare.
1551 # The result is a best guess and false return value is not an absolute
1552 # guarantee that gc will not take place at the next interval, but it probably
1553 # will not if nothing changes in the meantime.
1554 sub needs_gc {
1555 my $self = shift;
1556 my $lgc = parse_any_date($self->{lastgc});
1557 my $lrecv = parse_any_date($self->{lastreceive});
1558 my $lpgc = parse_any_date($self->{lastparentgc});
1559 return 1 unless defined($lgc) && defined($lrecv);
1560 if ($self->has_alternates) {
1561 return 1 unless defined($lpgc);
1562 return 1 unless $lpgc < $lgc;
1564 return 1 unless $lrecv < $lgc;
1565 # We don't try running any "is_dirty" check, so if somehow the
1566 # repository became dirty without updating lastreceive we might
1567 # incorrectly return false instead of true.
1568 return 0;
1571 sub delete_ctag {
1572 my $self = shift;
1573 my ($ctag) = @_;
1575 # sanity check, disallow filenames starting with . .. or /
1576 unlink($self->{path}.'/ctags/'.$ctag)
1577 unless !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1580 # returns new tag count value on success (will always be >= 1) otherwise undef
1581 sub add_ctag {
1582 my $self = shift;
1583 my $ctag = valid_tag(shift);
1584 my $nochanged = shift;
1586 # sanity check, disallow filenames starting with . .. or /
1587 return undef if !defined($ctag) || $ctag =~ m|^/| || $ctag =~ m{(?:^|/)(?:\.\.?)(?:/|$)};
1589 my $val = 0;
1590 my $ct;
1591 if (open $ct, '<', $self->{path}."/ctags/$ctag") {
1592 my $count = <$ct>;
1593 close $ct;
1594 defined $count or $count = '';
1595 chomp $count;
1596 $val = $count =~ /^[1-9]\d*$/ ? $count : 1;
1598 ++$val;
1599 my $oldmask = umask();
1600 umask($oldmask & ~0060);
1601 open $ct, '>', $self->{path}."/ctags/$ctag" and print $ct $val."\n" and close $ct;
1602 $self->_set_changed unless $nochanged;
1603 $self->_set_forkchange unless $nochanged;
1604 umask($oldmask);
1605 return $val;
1608 sub get_ctag_names {
1609 my $self = shift;
1610 my @ctags = ();
1611 opendir(my $dh, $self->{path}.'/ctags')
1612 or return @ctags;
1613 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1614 closedir($dh);
1615 return sort({lc($a) cmp lc($b)} @ctags);
1618 sub get_heads {
1619 my $self = shift;
1620 my $fh;
1621 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1622 defined($heads) or $heads = '';
1623 chomp $heads;
1624 my @res = ();
1625 foreach (split(/\n/, $heads)) {
1626 chomp;
1627 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1628 push @res, $1;
1630 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1631 @res;
1634 sub get_HEAD {
1635 my $self = shift;
1636 my $HEAD = read_HEAD_ref($self->{path});
1637 defined($HEAD) && $HEAD ne "" or die "could not get HEAD";
1638 return $1 if $HEAD =~ m{^refs/heads/(.+)$};
1639 return "[other]" if $HEAD =~ m{^refs/};
1640 return "[detached]" if $HEAD =~ m{^[0-9a-fA-F]{4,}$};
1641 return "[invalid]";
1644 sub set_HEAD {
1645 my $self = shift;
1646 my $newHEAD = shift;
1647 # Cursory checks only -- if you want to break your HEAD, be my guest
1648 if ($newHEAD =~ /^\/|^\.|[\x00-\x1f \x7f\[~^'<>*?\\:]|\@\{|\.\.|\.lock$|\.$|\/$/) {
1649 die "grossly invalid new HEAD: $newHEAD";
1651 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1652 die "could not set HEAD" if ($? >> 8);
1653 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1654 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1657 sub gen_auth {
1658 my $self = shift;
1659 my ($type) = @_;
1660 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1662 $self->{authtype} = $type;
1664 no warnings;
1665 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1667 my $expire = time + 24 * 3600;
1668 my $propval = "# ${type}AUTH $self->{auth} $expire";
1669 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1670 $self->{auth};
1673 sub del_auth {
1674 my $self = shift;
1676 delete $self->{auth};
1677 delete $self->{authtype};
1678 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1681 sub remove_user {
1682 my $self = shift;
1683 my ($username) = @_;
1685 my $before_count = @{$self->{users}};
1686 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1687 return @{$self->{users}} != $before_count;
1690 ### static methods
1692 sub get_forkee_name {
1693 local $_ = $_[0];
1694 (m#^(.*)/.*?$#)[0]; #
1697 sub get_forkee_path {
1698 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1699 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1700 -d $forkee ? $forkee : '';
1703 # Ultimately the full project/fork name could end up being part of a Git ref name
1704 # when a project's forks are combined into one giant repository for efficiency.
1705 # That means that the project/fork name must satisfy the Git ref name requirements:
1707 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1708 # 2. The character with an ASCII value of 0x7F is not allowed
1709 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1710 # 4. The character '/' is a separator and is not allowed within a name
1711 # 5. The name may not start with '.' or end with '.'
1712 # 6. The name may not end with '.lock'
1713 # 7. The name may not contain the '..' sequence
1714 # 8. The name may not contain the '@{' sequence
1715 # 9. If multiple components are used (separated by '/'), no empty '' components
1717 # We also prohibit a trailing '.git' on any path component and futher restrict
1718 # the allowed characters to alphanumeric and [+._-] where names must start with
1719 # an alphanumeric.
1721 sub _valid_name_characters {
1722 local $_ = $_[0];
1723 (not m#^[/+._-]#)
1724 and (not m#//#)
1725 and (not m#\.\.#)
1726 and (not m#/[+._-]#)
1727 and (not m#\./#)
1728 and (not m#\.$#)
1729 and (not m#\.git/#i)
1730 and (not m#\.git$#i)
1731 and (not m#\.idx/#i)
1732 and (not m#\.idx$#i)
1733 and (not m#\.lock/#i)
1734 and (not m#\.lock$#i)
1735 and (not m#\.pack/#i)
1736 and (not m#\.pack$#i)
1737 and (not m#\.bundle/#i)
1738 and (not m#\.bundle$#i)
1739 and (not m#/$#)
1740 and (not m/^[a-fA-F0-9]{38}$/)
1741 and m#^[a-zA-Z0-9/+._-]+$#
1742 and !has_reserved_suffix($_, $_[1], $_[2]);
1745 # $_[0] => prospective project name (WITHOUT trailing .git)
1746 # $_[1] => true to allow orphans (i.e. two-or-more-level-deep projects without a parent)
1747 # (the directory in which the orphan will be created must, however, already exist)
1748 # $_[2] => true to allow orphans w/o needed directory if $_[1] also true (like mkdir -p)
1749 # If $_[0] is a SCALAR ref, ${$_[0]} contains the name and will be untainted on success.
1750 sub valid_name {
1751 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1752 local $_ = $_[0];
1753 my $mayberef_name = $_;
1754 ref($_) eq 'SCALAR' and $_ = $$_;
1755 my $rv = (
1756 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1757 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1758 and ((not m#/#) or -d get_forkee_path($_) or ($_[1] and ($_[2] or -d $Girocco::Config::reporoot.'/'.get_forkee_name($_))))
1759 and (! -f $Girocco::Config::reporoot."/$_.git")
1761 $rv && ref($mayberef_name) eq 'SCALAR' && m|^(.+)$| and $$mayberef_name = $1;
1762 return $rv;
1765 # It's possible that some forks have been kept but the forkee is gone.
1766 # In this case the standard valid_name check is too strict.
1767 # If $_[0] is a SCALAR ref, ${$_[0]} contains the name and will be untainted on success.
1768 sub does_exist {
1769 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1770 my ($mayberef_name, $nodie) = @_;
1771 my $name = ref($mayberef_name) eq 'SCALAR' ? $$mayberef_name : $mayberef_name;
1772 my $okay = (
1773 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1774 and ((not $name =~ m#/#)
1775 or -d get_forkee_path($name)
1776 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1777 (!$okay && $nodie) and return undef;
1778 !$okay and die "tried to query for project with invalid name $name!";
1779 -d $Girocco::Config::reporoot."/$name.git" or return undef;
1780 ref($mayberef_name) eq 'SCALAR' && $name =~ m|^(.+)$| and $$mayberef_name = $1;
1781 return 1;
1784 # returns array of names only taken strictly from the group file
1785 # only entries with non-invalid names and gid >= 10000 are returned
1786 # a "non-invalid" name is 1 or more non-whitespace or '#' chars, NOT starting with '_'
1787 sub get_full_list {
1788 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1789 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:[1-9]\d{4,}:/ ? $1 : ()} <$fd>;
1790 close $fd;
1791 @projects;
1794 # returns array of array refs containing all fields (at least 3) of each entry from group file
1795 # only entries with non-invalid names and gid >= 10000 are returned
1796 # a "non-invalid" name is 1 or more non-whitespace or '#' chars, NOT starting with '_'
1797 # using
1798 # join(':',@{<array_ref>})
1799 # will recover the _exact_ original line from the group file for that entry
1800 sub get_full_list_extended {
1801 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1802 my @projects = map {chomp; /^([^:_\s#][^:\s#]*:[^:]*:[1-9]\d{4,}:.*)$/ ? [split(/:/,$1,-1)] : ()} <$fd>;
1803 close $fd;
1804 @projects;