gc.sh: suppress darcs optimize output
[girocco/readme.git] / Girocco / Project.pm
blobd77cff05e5ac956594971d038698635a372421a8
1 package Girocco::Project;
3 use strict;
4 use warnings;
6 BEGIN {
7 use Girocco::CGI;
8 use Girocco::User;
9 use Girocco::Util;
10 use Girocco::HashUtil;
11 use Girocco::ProjPerm;
12 use Girocco::Config;
13 use base ('Girocco::ProjPerm::'.$Girocco::Config::permission_control); # mwahaha
16 BEGIN {
17 eval {
18 require Digest::SHA;
19 Digest::SHA->import(
20 qw(sha1_hex)
21 );1} ||
22 eval {
23 require Digest::SHA1;
24 Digest::SHA1->import(
25 qw(sha1_hex)
26 );1} ||
27 eval {
28 require Digest::SHA::PurePerl;
29 Digest::SHA::PurePerl->import(
30 qw(sha1_hex)
31 );1} ||
32 die "One of Digest::SHA or Digest::SHA1 or Digest::SHA::PurePerl "
33 . "must be available\n";
36 our $metadata_fields = {
37 homepage => ['Homepage URL', 'hp', 'text'],
38 shortdesc => ['Short description', 'desc', 'text'],
39 README => ['<span style="display:inline-block;vertical-align:top">'.
40 'README (HTML, &lt; 8 KiB)<br />leave blank for automatic</span>',
41 'README', 'textarea', 'Enter only &#x201c;<!-- comments -->&#x201d; '.
42 'to completely suppress any README'],
43 notifymail => ['Commit notify &#x2013; mail to', 'notifymail', 'text',
44 'comma separated address list'],
45 summaryonly => ['Summaries only', 'summaryonly', 'checkbox',
46 'suppress patch/diff output in &#x201c;Commit notify&#x201d; email when showing new revisions'],
47 notifytag => ['Tag notify &#x2013; mail to', 'notifytag', 'text',
48 'comma separated address list &#x2013; if not empty, tag '.
49 'notifications are sent here INSTEAD of to '.
50 '&#x201c;Commit notify &#x2013; mail to&#x201d; address(es)'],
51 notifyjson => ['Commit notify &#x2013; '.
52 '<a title="'.html_esc('single field name is &#x201c;payload&#x201d;', 1).'" href="'.
53 'https://developer.github.com/v3/activity/events/types/#pushevent'.
54 '">POST JSON</a> at', 'notifyjson', 'text'],
55 notifycia => ['Commit notify &#x2013; <a href="http://cia.vc/doc/">CIA project</a> name',
56 'notifycia', 'text', 'CIA is defunct &#x2013; this value is ignored'],
59 sub _mkdir_forkees {
60 my $self = shift;
61 my @pelems = split('/', $self->{name});
62 pop @pelems; # do not create dir for the project itself
63 my $path = $self->{base_path};
64 foreach my $pelem (@pelems) {
65 $path .= "/$pelem";
66 (-d "$path") or mkdir $path or die "mkdir $path: $!";
67 chmod 02775, $path; # ok if fails (dir may already exist and be owned by someone else)
71 # With a leading ':' get from project local config replacing ':' with 'gitweb.'
72 # With a leading '%' get from project local config after removing '%'
73 # Otherwise it's a project file name to be loaded
74 # %propmapro entries are loaded but never written
76 our %propmap = (
77 url => ':baseurl',
78 email => ':owner',
79 desc => 'description',
80 README => 'README.html',
81 hp => ':homepage',
82 notifymail => '%hooks.mailinglist',
83 notifytag => '%hooks.announcelist',
84 notifyjson => '%hooks.jsonurl',
85 notifycia => '%hooks.cianame',
88 our %propmapro = (
89 lastchange => ':lastchange',
90 lastactivity => 'info/lastactivity',
91 lastgc => ':lastgc',
92 lastreceive => ':lastreceive',
93 lastparentgc => ':lastparentgc',
94 lastrefresh => ':lastrefresh',
95 creationtime => '%girocco.creationtime',
96 reposizek => '%girocco.reposizek',
97 origurl => ':baseurl',
100 # Projects with any of these names will be disallowed to avoid possible
101 # collisions with cgi script paths or chroot paths
102 # NOTE: names are checked after using lc on them, so all entries MUST be lowercase
103 our %reservedprojectnames = (
104 admin => 1, # /admin/ links
105 alternates => 1, # .git/objects/info/alternates
106 b => 1, # /b/ -> bundle.cgi
107 blog => 1, # /blog/ links
108 c => 1, # /c/ -> cgit
109 'git-receive-pack' => 1, # smart HTTP
110 'git-upload-archive' => 1, # smart HTTP
111 'git-upload-pack' => 1, # smart HTTP
112 h => 1, # /h/ -> html.cgi
113 head => 1, # .git/HEAD
114 'http-alternates' => 1, # .git/objects/info/http-alternates
115 info => 1, # .git/info
116 objects => 1, # .git/objects
117 packs => 1, # .git/objects/info/packs
118 r => 1, # /r/ -> git http
119 refs => 1, # .git/refs
120 w => 1, # /w/ -> gitweb
121 wiki => 1, # /wiki/ links
122 srv => 1, # /srv/git/ -> chroot ssh git repositories
125 sub _update_index {
126 my $self = shift;
127 system("$Girocco::Config::basedir/gitweb/genindex.sh", $self->{name});
130 sub _readlocalconfigfile {
131 my $self = shift;
132 my $undefonerr = shift || 0;
133 delete $self->{configfilehash};
134 my $configfile = get_git("--git-dir=$self->{path}",
135 'config', '--list', '--local', '--null');
136 my $result = 1;
137 defined($configfile) || $undefonerr or $result = 0, $configfile = '';
138 return undef unless defined($configfile);
139 my %config = map({split(/\n/, $_=~/\n/?$_:"$_\ntrue", 2)} split(/\x00/, $configfile));
140 $self->{configfilehash} = \%config;
141 return $result;
144 # @_[0]: argument to convert to boolean result (0 or 1)
145 # @_[1]: value to use if argument is undef (default is 0)
146 # Returns 0 or 1
147 sub _boolval {
148 my ($val, $def) = @_;
149 defined($def) or $def = 0;
150 defined($val) or $val = $def;
151 $val =~ s/\s+//gs;
152 $val = lc($val);
153 return 0 if $val eq '' || $val eq 'false' || $val eq 'off' || $val eq 'no' || $val =~ /^0+$/;
154 return 1;
157 sub _property_path {
158 my $self = shift;
159 my ($name) = @_;
160 $self->{path}.'/'.$name;
163 sub _property_fget {
164 my $self = shift;
165 my ($name) = @_;
166 my $pname = $propmap{$name};
167 $pname = $propmapro{$name} unless $pname;
168 $pname or die "unknown property: $name";
169 if ($pname =~ /^([:%])(.*)$/) {
170 my ($where, $pname) = ($1,lc($2));
171 $self->_readlocalconfigfile
172 unless ref($self->{configfilehash}) eq 'HASH';
173 my $val = $where eq ':' ?
174 $self->{configfilehash}->{"gitweb.$pname"} :
175 $self->{configfilehash}->{$pname};
176 defined($val) or $val = '';
177 chomp $val;
178 return $val;
181 open my $p, '<', $self->_property_path($pname) or return undef;
182 my @value = <$p>;
183 close $p;
184 my $value = join('', @value); chomp $value;
185 $value;
188 sub _property_fput {
189 my $self = shift;
190 my ($name, $value) = @_;
191 my $pname = $propmap{$name};
192 $pname or die "unknown property: $name";
193 $value ||= '';
194 if ($pname =~ s/^://) {
195 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
196 return;
197 } elsif ($pname =~ s/^%//) {
198 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
199 return;
202 my $P = lock_file($self->_property_path($pname));
203 chomp $value;
204 $value ne '' and print $P "$value\n";
205 close $P;
206 unlock_file($self->_property_path($pname));
209 sub _cleanup_readme {
210 my $self = shift;
211 defined($self->{README}) or $self->{README} = '';
212 $self->{README} =~ s/\r\n?/\n/gs;
213 $self->{README} =~ s/^\s+//s;
214 $self->{README} =~ s/\s+$//s;
215 $self->{README} eq '' or $self->{README} .= "\n";
218 sub _lint_readme {
219 my $self = shift;
220 return 0 unless defined($self->{README}) && $self->{README} ne '';
221 my $test = '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>';
222 $test .= $self->{README};
223 $test .= '</div></body></html>';
224 my ($code, $errors) = capture_command(2, $test, 'xmllint', '--nonet',
225 '--noout', '--nowarning', '-');
226 return 0 unless $code;
227 my $cnt = 0;
228 my @errs = ();
229 for my $line (split(/\n+/, $errors)) {
230 $line = html_esc($line);
231 $line =~ s/ /\&#160;/gs;
232 ++$cnt, $line = 'README'.$1 if $line =~ /^-(:\d+:.*)$/;
233 push @errs, '<tt>' . $line . '</tt>';
235 return ($cnt, join("<br />\n", @errs));
238 sub _properties_load {
239 my $self = shift;
240 foreach my $prop (keys %propmap) {
241 $self->{$prop} = $self->_property_fget($prop);
243 foreach my $prop (keys %propmapro) {
244 $self->{$prop} = $self->_property_fget($prop);
246 $self->_readlocalconfigfile
247 unless ref($self->{configfilehash}) eq 'HASH';
248 $self->{statusupdates} = _boolval($self->{configfilehash}->{'gitweb.statusupdates'}, 1);
249 $self->{summaryonly} = _boolval($self->{configfilehash}->{'hooks.summaryonly'}, 0);
250 delete $self->{auth};
251 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
252 defined($val) or $val = '';
253 chomp $val;
254 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
255 my $expire = $3;
256 if (time < $expire) {
257 $self->{authtype} = $1;
258 $self->{auth} = $2;
261 $self->_cleanup_readme;
262 delete $self->{configfilehash};
265 sub _properties_save {
266 my $self = shift;
267 my $fd;
268 foreach my $prop (keys %propmap) {
269 $self->_property_fput($prop, $self->{$prop});
271 $self->{statusupdates} = 1
272 unless defined($self->{statusupdates}) && $self->{statusupdates} =~ /^\d+$/;
273 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool',
274 "gitweb.statusupdates", $self->{statusupdates});
275 $self->{summaryonly} = 0
276 unless defined($self->{summaryonly}) && $self->{summaryonly} =~ /^\d+$/;
277 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool',
278 "hooks.summaryonly", $self->{summaryonly});
279 if (defined($self->{origurl}) && defined($self->{url}) &&
280 $self->{origurl} ne $self->{url} && -e $self->_property_path(".banged")) {
281 if (open($fd, '>', $self->_property_path(".bangagain"))) {
282 close $fd;
283 chmod(0664, $self->_property_path(".bangagain"));
288 sub _nofetch_path {
289 my $self = shift;
290 $self->_property_path('.nofetch');
293 sub _nofetch {
294 my $self = shift;
295 my ($nofetch) = @_;
296 my $nf = $self->_nofetch_path;
297 if ($nofetch) {
298 open my $x, '>', $nf or die "nofetch failed: $!";
299 close $x;
300 } else {
301 unlink $nf or die "yesfetch failed: $!";
305 sub _gcp_path {
306 my $self = shift;
307 $self->_property_path('.gc_in_progress');
310 sub _clonelog_path {
311 my $self = shift;
312 $self->_property_path('.clonelog');
315 sub _clonefail_path {
316 my $self = shift;
317 $self->_property_path('.clone_failed');
320 sub _clonep_path {
321 my $self = shift;
322 $self->_property_path('.clone_in_progress');
325 sub _clonep {
326 my $self = shift;
327 my ($nofetch) = @_;
328 my $np = $self->_clonep_path;
329 if ($nofetch) {
330 open my $x, '>', $np or die "clonep failed: $!";
331 close $x;
332 } else {
333 unlink $np or die "clonef failed: $!";
336 sub _alternates_setup {
337 my $self = shift;
338 return unless $self->{name} =~ m#/#;
339 my $forkee_name = get_forkee_name($self->{name});
340 my $forkee_path = get_forkee_path($self->{name});
341 return unless -d $forkee_path;
342 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
343 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
344 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
346 # We set up both alternates and http_alternates since we cannot use
347 # relative path in alternates - that doesn't work recursively.
349 my $filename = $self->{path}.'/objects/info/alternates';
350 open my $x, '>', $filename or die "alternates failed: $!";
351 print $x "$forkee_path/objects\n";
352 close $x;
353 chmod 0664, $filename or warn "cannot chmod $filename: $!";
355 if ($Girocco::Config::httppullurl) {
356 $filename = $self->{path}.'/objects/info/http-alternates';
357 open my $x, '>', $filename or die "http-alternates failed: $!";
358 my $upfork = $forkee_name;
359 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
360 close $x;
361 chmod 0664, $filename or warn "cannot chmod $filename: $!";
364 # copy lastactivity from the parent project
365 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
366 my $activity = <$x>;
367 close $x;
368 last unless $activity;
369 open $x, '>', $self->{path}.'/info/lastactivity' or last;
370 print $x $activity;
371 close $x;
372 chomp $activity;
373 $self->{'lastactivity'} = $activity;
376 # copy refs from parent project
377 local *SAVEOUT;
378 open(SAVEOUT, ">&STDOUT") || die "couldn't dup STDOUT: $!";
379 my $result = open(STDOUT, '>', "$self->{path}/packed-refs");
380 my $resultstr = $!;
381 if (!$result) {
382 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
383 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
384 die "could not write fork's packed-refs file: $resultstr";
386 system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
387 $result = close(STDOUT);
388 $resultstr = $!;
389 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
390 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
391 $result or die "could not close fork's packed-refs file: $resultstr";
392 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
394 # initialize HEAD
395 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
396 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
397 chomp $HEAD;
398 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
399 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
402 sub _set_changed {
403 my $self = shift;
404 my $fd;
405 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
408 sub _set_forkchange {
409 my $self = shift;
410 my $changedtoo = shift;
411 return unless $self->{name} =~ m#/#;
412 my $forkee_path = get_forkee_path($self->{name});
413 return unless -d $forkee_path;
414 # mark forkee as changed
415 my $fd;
416 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
417 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
418 return if -e $forkee_path.'/htmlcache/summary.forkchange';
419 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
422 sub _ctags_setup {
423 my $self = shift;
424 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
425 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
428 sub _group_add {
429 my $self = shift;
430 my ($xtra) = @_;
431 $xtra .= join(',', @{$self->{users}});
432 filedb_atomic_append(jailed_file('/etc/group'),
433 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
436 sub _group_update {
437 my $self = shift;
438 my $xtra = join(',', @{$self->{users}});
439 filedb_atomic_edit(jailed_file('/etc/group'),
440 sub {
441 $_ = $_[0];
442 chomp;
443 if ($self->{name} eq (split /:/)[0]) {
444 # preserve readonly flag
445 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
446 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
447 } else {
448 return "$_\n";
454 sub _group_remove {
455 my $self = shift;
456 filedb_atomic_edit(jailed_file('/etc/group'),
457 sub {
458 $self->{name} ne (split /:/)[0] and return $_;
463 sub _hook_path {
464 my $self = shift;
465 my ($name) = @_;
466 $self->{path}.'/hooks/'.$name;
469 sub _hook_install {
470 my $self = shift;
471 my ($name) = @_;
472 my $hooksdir = $self->{path}.'/hooks';
473 my $oldmask = umask();
474 umask($oldmask & ~0070);
475 -d $hooksdir or mkdir $hooksdir or
476 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
477 umask($oldmask);
478 open my $src, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
479 open my $dst, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
480 while (<$src>) { print $dst $_; }
481 close $dst;
482 close $src;
483 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
486 sub _hooks_install {
487 my $self = shift;
488 foreach my $hook ('pre-receive', 'post-receive', 'update') {
489 $self->_hook_install($hook);
493 # private constructor, do not use
494 sub _new {
495 my $class = shift;
496 my ($name, $base_path, $path) = @_;
497 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
498 $path ||= "$base_path/$name.git";
499 my $proj = { name => $name, base_path => $base_path, path => $path };
501 bless $proj, $class;
504 # public constructor #0
505 # creates a virtual project not connected to disk image
506 # you can conjure() it later to disk
507 sub ghost {
508 my $class = shift;
509 my ($name, $mirror) = @_;
510 my $self = $class->_new($name, $Girocco::Config::reporoot);
511 $self->{users} = [];
512 $self->{mirror} = $mirror;
513 $self->{email} = $self->{orig_email} = '';
514 $self;
517 # public constructor #1
518 sub load {
519 my $class = shift;
520 my $name = shift || '';
522 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
523 my $r = qr/^\Q$name\E:/;
524 foreach (grep /$r/, <$fd>) {
525 chomp;
527 my $self = $class->_new($name, $Girocco::Config::reporoot);
528 (-d $self->{path} && $self->_readlocalconfigfile(1))
529 or die "invalid path (".$self->{path}.") for project ".$self->{name};
531 my $ulist;
532 (undef, $self->{crypt}, $self->{gid}, $ulist) = split /:/;
533 $ulist ||= '';
534 $self->{users} = [split /,/, $ulist];
535 $self->{HEAD} = $self->get_HEAD;
536 $self->{orig_HEAD} = $self->{HEAD};
537 $self->{orig_users} = [@{$self->{users}}];
538 $self->{mirror} = ! -e $self->_nofetch_path;
539 $self->{gc_in_progress} = -e $self->_gcp_path;
540 $self->{clone_in_progress} = -e $self->_clonep_path;
541 $self->{clone_logged} = -e $self->_clonelog_path;
542 $self->{clone_failed} = -e $self->_clonefail_path;
543 $self->{ccrypt} = $self->{crypt};
545 $self->_properties_load;
546 $self->{orig_email} = $self->{email};
547 $self->{loaded} = 1; # indicates self was loaded from etc/group file
548 close $fd;
549 return $self;
551 close $fd;
552 undef;
555 # $proj may not be in sane state if this returns false!
556 # fields listed in %$metadata_fields that are NOT also
557 # in @Girocco::Config::project_fields are totally ignored!
558 sub cgi_fill {
559 my $self = shift;
560 my ($gcgi) = @_;
561 my $cgi = $gcgi->cgi;
562 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
563 my $field_enabled = sub {
564 !exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]})};
566 my $pwd = $cgi->param('pwd');
567 my $pwd2 = $cgi->param('pwd2');
568 # in case passwords are disabled
569 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
570 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
571 $gcgi->err("Empty passwords are not permitted.");
573 if ($pwd ne '' or not $self->{crypt}) {
574 $self->{crypt} = scrypt_sha1($pwd);
576 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
577 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
580 $self->{cpwd} = $cgi->param('cpwd');
582 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
583 my $newtype = $forkee ? 'fork' : 'project';
584 length($project) <= 64
585 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
587 if ($Girocco::Config::project_owners eq 'email') {
588 $self->{email} = $gcgi->wparam('email');
589 valid_email($self->{email})
590 or $gcgi->err("Your email sure looks weird...?");
591 length($self->{email}) <= 96
592 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
595 # No setting the url unless we're either new or an existing mirror!
596 $self->{url} = $gcgi->wparam('url') unless $self->{loaded} && !$self->{mirror};
597 # Always validate the url if we're an existing mirror
598 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
599 # Always allow the url to be left unchanged without validation when editing
600 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
601 valid_repo_url($self->{url})
602 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
603 if ($Girocco::Config::restrict_mirror_hosts) {
604 my $mh = extract_url_hostname($self->{url});
605 is_dns_hostname($mh)
606 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
607 !is_our_hostname($mh)
608 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
612 if ($field_enabled->('desc')) {
613 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
614 length($self->{desc}) <= 1024
615 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
618 if ($field_enabled->('README')) {
619 $self->{README} = to_utf8($gcgi->wparam('README'), 1);
620 $self->_cleanup_readme;
621 length($self->{README}) <= 8192
622 or $gcgi->err("README length &gt; 8kb!");
623 my ($cnt, $err) = (0);
624 ($cnt, $err) = $self->_lint_readme if $gcgi->ok && $Girocco::Config::xmllint_readme;
625 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
628 if ($field_enabled->('hp')) {
629 $self->{hp} = $gcgi->wparam('hp');
630 if ($self->{hp}) {
631 valid_web_url($self->{hp})
632 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
636 # No mucking about with users unless we're a push project
637 if (($self->{loaded} && !$self->{mirror}) ||
638 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
639 my %users = ();
640 my @users = ();
641 foreach my $user ($cgi->multi_param('user')) {
642 if (!exists($users{$user})) {
643 $users{$user} = 1;
644 push(@users, $user) if Girocco::User::does_exist($user, 1);
647 $self->{users} = \@users;
650 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
651 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
652 my $newhead;
653 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
654 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
655 if ($newhead eq $self->{orig_HEAD} ||
656 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
657 $self->{HEAD} = $newhead;
658 } else {
659 $gcgi->err("Invalid default branch (no such ref)");
663 # schedule deletion of tags (will be committed by update() after auth)
664 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
666 if ($field_enabled->('notifymail')) {
667 $self->{notifymail} = $gcgi->wparam('notifymail');
668 if ($self->{notifymail}) {
669 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
670 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
672 if ($field_enabled->('summaryonly')) {
673 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
677 if ($field_enabled->('notifytag')) {
678 $self->{notifytag} = $gcgi->wparam('notifytag');
679 if ($self->{notifytag}) {
680 (valid_email_multi($self->{notifytag}) and length($self->{notifytag}) <= 512)
681 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
685 if ($field_enabled->('notifyjson')) {
686 $self->{notifyjson} = $gcgi->wparam('notifyjson');
687 if ($self->{notifyjson}) {
688 valid_web_url($self->{notifyjson})
689 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
693 if ($field_enabled->('notifycia')) {
694 $self->{notifycia} = $gcgi->wparam('notifycia');
695 if ($self->{notifycia}) {
696 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
697 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
701 if ($cgi->param('setstatusupdates')) {
702 my $val = $gcgi->wparam('statusupdates') || '0';
703 $self->{statusupdates} = $val ? 1 : 0;
706 not $gcgi->err_check;
709 sub form_defaults {
710 my $self = shift;
712 name => $self->{name},
713 email => $self->{email},
714 url => $self->{url},
715 desc => html_esc($self->{desc}),
716 README => html_esc($self->{README}),
717 hp => $self->{hp},
718 users => $self->{users},
719 notifymail => html_esc($self->{notifymail}),
720 summaryonly => html_esc($self->{summaryonly}),
721 notifytag => html_esc($self->{notifytag}),
722 notifyjson => html_esc($self->{notifyjson}),
723 notifycia => html_esc($self->{notifycia}),
727 # return true if $enc_passwd is a match for $plain_passwd
728 my $_check_passwd_match = sub {
729 my $enc_passwd = shift;
730 my $plain_passwd = shift;
731 defined($enc_passwd) or $enc_passwd = '';
732 defined($plain_passwd) or $plain_passwd = '';
733 # $enc_passwd may be crypt or crypt_sha1
734 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
735 # It's using sha1-crypt
736 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
737 } else {
738 # It's using crypt
739 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
743 sub authenticate {
744 my $self = shift;
745 my ($gcgi) = @_;
747 $self->{ccrypt} or die "Can't authenticate against a project with no password";
748 defined($self->{cpwd}) or $self->{cpwd} = '';
749 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
750 $gcgi->err("Your admin password does not match!");
751 return 0;
753 return 1;
756 # return true if the password from the file is empty or consists of all the same
757 # character. However, if the project was NOT loaded from the group file
758 # (!self->{loaded}) then the password is never locked.
759 # This function does NOT check $Girocco::Config::project_passwords, the caller
760 # is responsible for doing so if desired. Same for $self->{email}.
761 sub is_password_locked {
762 my $self = shift;
764 $self->{loaded} or return 0;
765 my $testcrypt = $self->{ccrypt}; # The value from the group file
766 defined($testcrypt) or $testcrypt = '';
767 $testcrypt ne '' or return 1; # No password at all
768 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
769 return 0; # Not locked
772 sub _setup {
773 use POSIX qw(strftime);
774 my $self = shift;
775 my ($pushers) = @_;
776 my $fd;
778 $self->_mkdir_forkees;
780 my $gid;
781 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
782 if ($Girocco::Config::owning_group) {
783 $gid = scalar(getgrnam($Girocco::Config::owning_group));
784 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
785 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
786 } else {
787 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
789 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
790 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
791 or die "git init $self->{path} failed: $?";
792 # we don't need these two, remove them (they will normally be created empty) if they exist
793 rmdir $self->{path}."/branches";
794 rmdir $self->{path}."/remotes";
795 -d $self->{path}."/info" or mkdir $self->{path}."/info"
796 or die "info directory does not exist and unable to create it: $!";
797 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
798 or die "hooks directory does not exist and unable to create it: $!";
799 # clean out any kruft that may have come in from the initial template directory
800 foreach my $cleandir (qw(hooks info)) {
801 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
802 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
803 closedir $hooksdir;
806 if ($Girocco::Config::owning_group) {
807 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
809 # hooks never world writable
810 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
811 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logallrefupdates', 'false') == 0
812 or die "disabling core.logallrefupdates failed: $?";
813 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
814 or die "disabling core.ignoreCase failed: $?";
815 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
816 or die "enabling transfer.fsckObjects failed: $?";
817 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastforwards', 'false') == 0
818 or die "disabling receive.denyNonFastforwards failed: $?";
819 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
820 or die "disabling gc.auto failed: $?";
821 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
822 or die "disabling receive.autogc failed: $?";
823 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
824 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateserverinfo', 'true') == 0
825 or die "enabling receive.updateserverinfo failed: $?";
826 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writebitmaps', 'true') == 0
827 or die "enabling repack.writebitmaps failed: $?";
828 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
829 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
830 or die "setting girocco.creationtime failed: $?";
831 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
832 or die "htmlcache directory does not exist and unable to create it: $!";
833 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
834 or die "bundles directory does not exist and unable to create it: $!";
835 foreach my $file (qw(info/lastactivity .delaygc)) {
836 if (open $fd, '>', $self->{path}."/".$file) {
837 close $fd;
838 chmod 0664, $self->{path}."/".$file;
842 # /info must have right permissions,
843 # and git init didn't do it for some reason.
844 # config must have correct permissions.
845 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
846 # also make sure /refs, /objects and /htmlcache are correct too.
847 my ($dmode, $dmodestr, $fmode, $fmodestr);
848 if ($Girocco::Config::owning_group) {
849 ($dmode, $dmodestr) = (02775, '02775');
850 ($fmode, $fmodestr) = (0664, '0664');
851 } else {
852 ($dmode, $dmodestr) = (02777, '02777');
853 ($fmode, $fmodestr) = (0666, '0666');
855 foreach my $dir (qw(info refs objects htmlcache bundles)) {
856 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
858 foreach my $file (qw(config)) {
859 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
861 # these ones are probably not strictly required but are nice to have
862 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
863 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
864 chmod($dmode, $self->{path}."/$dir");
867 $self->_properties_save;
868 $self->_alternates_setup;
869 $self->_ctags_setup;
870 $self->_group_remove;
871 $self->_group_add($pushers);
872 $self->_hooks_install;
873 $self->_update_index;
874 $self->_set_changed;
875 $self->_set_forkchange(1);
878 sub premirror {
879 my $self = shift;
881 $self->_setup(':');
882 $self->_clonep(1);
883 $self->perm_initialize;
886 sub conjure {
887 my $self = shift;
889 $self->_setup;
890 $self->_nofetch(1);
891 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
892 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
893 or die "create-personal-mob-area $self->{name} failed";
895 $self->perm_initialize;
898 sub clone {
899 my $self = shift;
901 unlink ($self->_clonefail_path()); # Ignore EEXIST error
902 unlink ($self->_clonelog_path()); # Ignore EEXIST error
904 use IO::Socket;
905 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
906 select((select($sock),$|=1)[0]);
907 $sock->print("clone ".$self->{name}."\n");
908 # Just ignore reply, we are going to succeed anyway and the I/O
909 # would apparently get quite hairy.
910 $sock->flush();
911 sleep 2; # *cough*
912 $sock->close();
915 sub update {
916 my $self = shift;
918 $self->_properties_save;
919 $self->_group_update;
921 if (exists($self->{tags_to_delete})) {
922 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
925 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
927 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
928 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
929 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
930 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
932 $self->_update_index if $self->{email} ne $self->{orig_email};
933 $self->{orig_email} = $self->{email};
934 $self->_set_changed;
939 sub update_password {
940 my $self = shift;
941 my ($pwd) = @_;
943 $self->{crypt} = scrypt_sha1($pwd);
944 $self->_group_update;
947 # You can explicitly do this just on a ghost() repository too.
948 sub delete {
949 my $self = shift;
951 if (-d $self->{path}) {
952 system('rm', '-rf', $self->{path}) == 0
953 or die "rm -rf $self->{path} failed: $?";
955 # attempt to clean up any empty fork directories by removing them
956 my @pelems = split('/', $self->{name});
957 while (@pelems > 1) {
958 pop @pelems;
959 # okay to fail
960 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
962 $self->_group_remove;
963 $self->_update_index;
964 $self->_set_forkchange(1);
969 sub _contains_files {
970 my $dir = shift;
971 (-d $dir) or return 0;
972 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
973 while (my $entry = readdir($dh)) {
974 next if $entry eq '' || $entry eq '.' || $entry eq '..';
975 closedir($dh), return 1
976 if -f "$dir/$entry" ||
977 -d "$dir/$entry" && _contains_files("$dir/$entry");
979 closedir($dh);
980 return 0;
983 sub has_forks {
984 my $self = shift;
986 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
989 # Returns an array of 0 or more array refs, one for each bundle:
990 # ->[0]: bundle creation time (seconds since epoch)
991 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
992 # ->[2]: bundle size in bytes
993 sub bundles {
994 my $self = shift;
995 use Time::Local;
997 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
998 my @blist = ();
999 if (-d $self->{path}.'/bundles') {{
1000 my $prefix = $self->{name};
1001 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1002 opendir(my $dh, $self->{path}.'/bundles') or last;
1003 while (my $bfile = readdir($dh)) {
1004 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1005 my $ctime = eval {timegm(
1006 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1007 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4)-1900)};
1008 next unless $ctime;
1009 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1010 my $f1 = <$bh>;
1011 my $f2 = <$bh>;
1012 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1013 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1014 close($bh);
1015 next unless $f1 && $f2 && $f1 ne $f2;
1016 chomp $f1;
1017 chomp $f2;
1018 next unless -e $f1 && -e $f2;
1019 my $s1 = -s $f1 || 0;
1020 my $s2 = -s $f2 || 0;
1021 next unless $s1 || $s2;
1022 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1024 closedir($dh);
1026 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1027 my %seen = ();
1028 my @result = ();
1029 foreach my $bndl (@blist) {
1030 next if $seen{$bndl->[1]};
1031 $seen{$bndl->[1]} = 1;
1032 push(@result, $bndl);
1034 $self->{bundles} = \@result;
1035 return @result;
1038 sub has_alternates {
1039 my $self = shift;
1040 return -s $self->{path}.'/objects/info/alternates' ? 1 : 0;
1043 sub has_bundle {
1044 my $self = shift;
1046 return scalar($self->bundles);
1049 # returns true if any of the notify fields are non-empty
1050 sub has_notify {
1051 my $self = shift;
1052 # We do not ckeck notifycia since it's defunct
1053 return $self->{'notifymail'} || $self->{'notifytag'} || $self->{'notifyjson'};
1056 sub is_empty {
1057 # A project is considered empty if the git repository does not
1058 # have any refs. This means packed-refs does not exist or is
1059 # empty or only has lines starting with '#' AND there are no
1060 # files in the refs subdirectory hierarchy (no matter how deep).
1062 my $self = shift;
1064 (-d $self->{path}) or return 0;
1065 if (-e $self->{path}.'/packed-refs') {
1066 open(my $pr, '<', $self->{path}.'/packed-refs')
1067 or die "open $self->{path}./packed-refs failed: $!";
1068 my $foundref = 0;
1069 while (my $ref = <$pr>) {
1070 next if $ref =~ /^#/;
1071 $foundref = 1;
1072 last;
1074 close($pr);
1075 return 0 if $foundref;
1077 (-d $self->{path}.'/refs') or return 1;
1078 return !_contains_files($self->{path}.'/refs');
1081 # returns array:
1082 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1083 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1084 # Both values (if not undef) are seconds since epoch
1085 # Result only considers lastgc and min_gc_interval nothing else
1086 sub next_gc {
1087 my $self = shift;
1088 my $lastgcepoch = parse_any_date($self->{lastgc});
1089 return (undef, undef) unless defined $lastgcepoch;
1090 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1091 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1092 $Girocco::Config::min_mirror_interval));
1095 # returns boolean (0 or 1)
1096 # Attempts to determine whether or not a gc (and corresponding build
1097 # of a .bitmap/.bndl file) will actually take place at the next_gc
1098 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1099 # end up being built depends on whether or not the local object graph
1100 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1101 # is not possible because the object graph will be incomplete,
1102 # but it *is* possible that even though the repository has_alternates,
1103 # it does not actually borrow any objects so a .bitmap/.bndl will build
1104 # in spite of the presence of alternates -- but this is expected to be rare.
1105 # The result is a best guess and false return value is not an absolute
1106 # guarantee that gc will not take place at the next interval, but it probably
1107 # will not if nothing changes in the meantime.
1108 sub needs_gc {
1109 my $self = shift;
1110 my $lgc = parse_any_date($self->{lastgc});
1111 my $lrecv = parse_any_date($self->{lastreceive});
1112 my $lpgc = parse_any_date($self->{lastparentgc});
1113 return 1 unless defined($lgc) && defined($lrecv);
1114 if ($self->has_alternates) {
1115 return 1 unless defined($lpgc);
1116 return 1 unless $lpgc < $lgc;
1118 return 1 unless $lrecv < $lgc;
1119 # We don't try running any "is_dirty" check, so if somehow the
1120 # repository became dirty without updating lastreceive we might
1121 # incorrectly return false instead of true.
1122 return 0;
1125 sub delete_ctag {
1126 my $self = shift;
1127 my ($ctag) = @_;
1129 # sanity check, disallow filenames starting with . .. or /
1130 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
1133 sub get_ctag_names {
1134 my $self = shift;
1135 my @ctags = ();
1136 opendir(my $dh, $self->{path}.'/ctags')
1137 or return @ctags;
1138 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1139 closedir($dh);
1140 return sort({lc($a) cmp lc($b)} @ctags);
1143 sub get_heads {
1144 my $self = shift;
1145 my $fh;
1146 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1147 defined($heads) or $heads = '';
1148 chomp $heads;
1149 my @res = ();
1150 foreach (split(/\n/, $heads)) {
1151 chomp;
1152 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1153 push @res, $1;
1155 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1156 @res;
1159 sub get_HEAD {
1160 my $self = shift;
1161 my $HEAD = get_git("--git-dir=$self->{path}", 'symbolic-ref', 'HEAD');
1162 defined($HEAD) or $HEAD = '';
1163 chomp $HEAD;
1164 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
1165 return $1;
1168 sub set_HEAD {
1169 my $self = shift;
1170 my $newHEAD = shift;
1171 # Cursory checks only -- if you want to break your HEAD, be my guest
1172 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
1173 die "grossly invalid new HEAD: $newHEAD";
1175 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1176 die "could not set HEAD" if ($? >> 8);
1177 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1178 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1181 sub gen_auth {
1182 my $self = shift;
1183 my ($type) = @_;
1184 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1186 $self->{authtype} = $type;
1188 no warnings;
1189 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1191 my $expire = time + 24 * 3600;
1192 my $propval = "# ${type}AUTH $self->{auth} $expire";
1193 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1194 $self->{auth};
1197 sub del_auth {
1198 my $self = shift;
1200 delete $self->{auth};
1201 delete $self->{authtype};
1202 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1205 sub remove_user {
1206 my $self = shift;
1207 my ($username) = @_;
1209 my $before_count = @{$self->{users}};
1210 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1211 return @{$self->{users}} != $before_count;
1214 ### static methods
1216 sub get_forkee_name {
1217 local $_ = $_[0];
1218 (m#^(.*)/.*?$#)[0]; #
1221 sub get_forkee_path {
1222 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1223 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1224 -d $forkee ? $forkee : '';
1227 # Ultimately the full project/fork name could end up being part of a Git ref name
1228 # when a project's forks are combined into one giant repository for efficiency.
1229 # That means that the project/fork name must satisfy the Git ref name requirements:
1231 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1232 # 2. The character with an ASCII value of 0x7F is not allowed
1233 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1234 # 4. The character '/' is a separator and is not allowed within a name
1235 # 5. The name may not start with '.' or end with '.'
1236 # 6. The name may not end with '.lock'
1237 # 7. The name may not contain the '..' sequence
1238 # 8. The name may not contain the '@{' sequence
1239 # 9. If multiple components are used (separated by '/'), no empty '' components
1241 # We also prohibit a trailing '.git' on any path component and futher restrict
1242 # the allowed characters to alphanumeric and [+._-] where names must start with
1243 # an alphanumeric.
1245 sub _valid_name_characters {
1246 local $_ = $_[0];
1247 (not m#^[/+._-]#)
1248 and (not m#//#)
1249 and (not m#\.\.#)
1250 and (not m#/[+._-]#)
1251 and (not m#\./#)
1252 and (not m#\.$#)
1253 and (not m#\.git/#i)
1254 and (not m#\.git$#i)
1255 and (not m#\.idx/#i)
1256 and (not m#\.idx$#i)
1257 and (not m#\.lock/#i)
1258 and (not m#\.lock$#i)
1259 and (not m#\.pack/#i)
1260 and (not m#\.pack$#i)
1261 and (not m#\.bundle/#i)
1262 and (not m#\.bundle$#i)
1263 and (not m#/$#)
1264 and (not m/^[a-fA-F0-9]{38}$/)
1265 and m#^[a-zA-Z0-9/+._-]+$#
1266 and !has_reserved_suffix($_, $_[1], $_[2]);
1269 sub valid_name {
1270 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1271 local $_ = $_[0];
1272 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1273 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1274 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
1277 # It's possible that some forks have been kept but the forkee is gone.
1278 # In this case the standard valid_name check is too strict.
1279 sub does_exist {
1280 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1281 my ($name, $nodie) = @_;
1282 my $okay = (
1283 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1284 and ((not $name =~ m#/#)
1285 or -d get_forkee_path($name)
1286 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1287 (!$okay && $nodie) and return undef;
1288 !$okay and die "tried to query for project with invalid name $name!";
1289 (-d $Girocco::Config::reporoot."/$name.git");
1292 sub get_full_list {
1293 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1294 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1295 close $fd;
1296 @projects;