Project.pm: clean up email address lists
[girocco/readme.git] / Girocco / Project.pm
blob00af75e31268a0803c9e1997eb5b74007e0aeaca
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 cleanmirror => ['Mirror refs', 'cleanmirror', 'placeholder'],
38 homepage => ['Homepage URL', 'hp', 'text'],
39 shortdesc => ['Short description', 'desc', 'text'],
40 README => ['<span style="display:inline-block;vertical-align:top">'.
41 'README (HTML, &lt; 8 KiB)<br />leave blank for automatic</span>',
42 'README', 'textarea', 'Enter only &#x201c;<!-- comments -->&#x201d; '.
43 'to completely suppress any README'],
44 notifymail => ['Commit notify &#x2013; mail to', 'notifymail', 'text',
45 'comma separated address list'],
46 reverseorder => ['Show oldest first', 'reverseorder', 'checkbox',
47 'show new revisions in oldest to newest order (instead of the default newest to oldest older)'.
48 ' in &#x201c;Commit notify&#x201d; email when showing new revisions'],
49 summaryonly => ['Summaries only', 'summaryonly', 'checkbox',
50 'suppress patch/diff output in &#x201c;Commit notify&#x201d; email when showing new revisions'],
51 notifytag => ['Tag notify &#x2013; mail to', 'notifytag', 'text',
52 'comma separated address list &#x2013; if not empty, tag '.
53 'notifications are sent here INSTEAD of to '.
54 '&#x201c;Commit notify &#x2013; mail to&#x201d; address(es)'],
55 notifyjson => ['Commit notify &#x2013; '.
56 '<a title="'.html_esc('single field name is &#x201c;payload&#x201d;', 1).'" href="'.
57 'https://developer.github.com/v3/activity/events/types/#pushevent'.
58 '">POST JSON</a> at', 'notifyjson', 'text'],
59 notifycia => ['Commit notify &#x2013; <a href="http://cia.vc/doc/">CIA project</a> name',
60 'notifycia', 'text', 'CIA is defunct &#x2013; this value is ignored'],
63 sub _mkdir_forkees {
64 my $self = shift;
65 my @pelems = split('/', $self->{name});
66 pop @pelems; # do not create dir for the project itself
67 my $path = $self->{base_path};
68 foreach my $pelem (@pelems) {
69 $path .= "/$pelem";
70 (-d "$path") or mkdir $path or die "mkdir $path: $!";
71 chmod 02775, $path; # ok if fails (dir may already exist and be owned by someone else)
75 # With a leading ':' get from project local config replacing ':' with 'gitweb.'
76 # With a leading '%' get from project local config after removing '%'
77 # With a leading '!' get boolean from project local config after removing '!' (prefixed with 'gitweb.' if no '.')
78 # With a leading [:%!] a trailing ':defval' may be added to select the default value to use if unset
79 # Otherwise it's a project file name to be loaded
80 # %propmapro entries are loaded but never written
81 # %propmapromirror entries are loaded only for mirrors but never written
83 our %propmap = (
84 url => ':baseurl',
85 email => ':owner',
86 desc => 'description',
87 README => 'README.html',
88 hp => ':homepage',
89 notifymail => '%hooks.mailinglist',
90 notifytag => '%hooks.announcelist',
91 notifyjson => '%hooks.jsonurl',
92 notifycia => '%hooks.cianame',
93 cleanmirror => '!girocco.cleanmirror',
94 statusupdates => '!statusupdates:1',
95 reverseorder => '!hooks.reverseorder',
96 summaryonly => '!hooks.summaryonly',
99 our %propmapro = (
100 lastchange => ':lastchange',
101 lastactivity => 'info/lastactivity',
102 lastgc => ':lastgc',
103 lastreceive => ':lastreceive',
104 lastparentgc => ':lastparentgc',
105 lastrefresh => ':lastrefresh',
106 creationtime => '%girocco.creationtime',
107 reposizek => '%girocco.reposizek',
108 origurl => ':baseurl',
111 our %propmapromirror = (
112 bangcount => '%girocco.bang.count',
113 bangfirstfail => '%girocco.bang.firstfail',
114 bangmessagesent => '!girocco.bang.messagesent',
117 # Projects with any of these names will be disallowed to avoid possible
118 # collisions with cgi script paths or chroot paths
119 # NOTE: names are checked after using lc on them, so all entries MUST be lowercase
120 our %reservedprojectnames = (
121 admin => 1, # /admin/ links
122 alternates => 1, # .git/objects/info/alternates
123 b => 1, # /b/ -> bundle.cgi
124 blog => 1, # /blog/ links
125 c => 1, # /c/ -> cgit
126 'git-receive-pack' => 1, # smart HTTP
127 'git-upload-archive' => 1, # smart HTTP
128 'git-upload-pack' => 1, # smart HTTP
129 h => 1, # /h/ -> html.cgi
130 head => 1, # .git/HEAD
131 'http-alternates' => 1, # .git/objects/info/http-alternates
132 info => 1, # .git/info
133 objects => 1, # .git/objects
134 packs => 1, # .git/objects/info/packs
135 r => 1, # /r/ -> git http
136 refs => 1, # .git/refs
137 w => 1, # /w/ -> gitweb
138 wiki => 1, # /wiki/ links
139 srv => 1, # /srv/git/ -> chroot ssh git repositories
142 sub _update_index {
143 my $self = shift;
144 system("$Girocco::Config::basedir/gitweb/genindex.sh", $self->{name});
147 sub _readlocalconfigfile {
148 my $self = shift;
149 my $undefonerr = shift || 0;
150 delete $self->{configfilehash};
151 my $configfile = get_git("--git-dir=$self->{path}",
152 'config', '--list', '--local', '--null');
153 my $result = 1;
154 defined($configfile) || $undefonerr or $result = 0, $configfile = '';
155 return undef unless defined($configfile);
156 my %config = map({split(/\n/, $_=~/\n/?$_:"$_\ntrue", 2)} split(/\x00/, $configfile));
157 $self->{configfilehash} = \%config;
158 return $result;
161 # @_[0]: argument to convert to boolean result (0 or 1)
162 # @_[1]: value to use if argument is undef (default is 0)
163 # Returns 0 or 1
164 sub _boolval {
165 my ($val, $def) = @_;
166 defined($def) or $def = 0;
167 defined($val) or $val = $def;
168 $val =~ s/\s+//gs;
169 $val = lc($val);
170 return 0 if $val eq '' || $val eq 'false' || $val eq 'off' || $val eq 'no' || $val =~ /^0+$/;
171 return 1;
174 sub _property_path {
175 my $self = shift;
176 my ($name) = @_;
177 $self->{path}.'/'.$name;
180 sub _property_fget {
181 my $self = shift;
182 my ($name, $nodef) = @_;
183 my $pname = $propmap{$name};
184 $pname = $propmapro{$name} unless $pname;
185 $pname = $propmapromirror{$name} unless $pname;
186 $pname or die "unknown property: $name";
187 if ($pname =~ /^([:%!])([^:]+)(:.*)?$/) {
188 my ($where, $pname, $defval) = ($1, lc($2), substr(($3||":"),1));
189 $defval = '' if $nodef;
190 $self->_readlocalconfigfile
191 unless ref($self->{configfilehash}) eq 'HASH';
192 $pname = "gitweb." . $pname if $where eq ':' or $where eq '!' && $pname !~ /[.]/;
193 my $val = $self->{configfilehash}->{$pname};
194 defined($val) or $val = $defval;
195 chomp $val;
196 $val = _boolval($val, $defval) if $where eq '!';
197 return $nodef && !exists($self->{configfilehash}->{$pname}) ? undef : $val;
200 open my $p, '<', $self->_property_path($pname) or return undef;
201 my @value = <$p>;
202 close $p;
203 my $value = join('', @value); chomp $value;
204 $value;
207 sub _prop_is_same {
208 my $self = shift;
209 my ($name, $value) = @_;
210 my $existing = $self->_property_fget($name, 1);
211 defined($value) or $value = '';
212 return defined($existing) && $existing eq $value;
215 sub _property_fput {
216 my $self = shift;
217 my ($name, $value, $nosetsame) = @_;
218 my $pname = $propmap{$name};
219 $pname or die "unknown property: $name";
220 my $defval = '';
221 ($pname, $defval) = ($1, substr(($2||":"),1)) if $pname =~ /^([:%!][^:]+)(:.*)?$/;
222 defined($value) or $value = $defval;
223 if ($pname =~ s/^://) {
224 return if $nosetsame && $self->_prop_is_same($name, $value);
225 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', "gitweb.$pname", $value);
226 return;
227 } elsif ($pname =~ s/^%//) {
228 return if $nosetsame && $self->_prop_is_same($name, $value);
229 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', $pname, $value);
230 return;
231 } elsif ($pname =~ s/^!//) {
232 $pname = "gitweb." . $pname unless $pname =~ /[.]/;
233 $value = _boolval($value, $defval);
234 return if $nosetsame && $self->_prop_is_same($name, $value);
235 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--bool', $pname, $value);
236 return;
239 my $P = lock_file($self->_property_path($pname));
240 chomp $value;
241 $value ne '' and print $P "$value\n";
242 close $P;
243 unlock_file($self->_property_path($pname));
246 sub _cleanup_readme {
247 my $self = shift;
248 defined($self->{README}) or $self->{README} = '';
249 $self->{README} =~ s/\r\n?/\n/gs;
250 $self->{README} =~ s/^\s+//s;
251 $self->{README} =~ s/\s+$//s;
252 $self->{README} eq '' or $self->{README} .= "\n";
255 sub _lint_readme {
256 my $self = shift;
257 return 0 unless defined($self->{README}) && $self->{README} ne '';
258 my $test = '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>';
259 $test .= $self->{README};
260 $test .= '</div></body></html>';
261 my ($code, $errors) = capture_command(2, $test, 'xmllint', '--nonet',
262 '--noout', '--nowarning', '-');
263 return 0 unless $code;
264 my $cnt = 0;
265 my @errs = ();
266 for my $line (split(/\n+/, $errors)) {
267 $line = html_esc($line);
268 $line =~ s/ /\&#160;/gs;
269 ++$cnt, $line = 'README'.$1 if $line =~ /^-(:\d+:.*)$/;
270 push @errs, '<tt>' . $line . '</tt>';
272 return ($cnt, join("<br />\n", @errs));
275 sub _properties_load {
276 my $self = shift;
277 foreach my $prop (keys %propmap) {
278 $self->{$prop} = $self->_property_fget($prop);
280 foreach my $prop (keys %propmapro) {
281 $self->{$prop} = $self->_property_fget($prop);
283 if ($self->{mirror}) {
284 foreach my $prop (keys %propmapromirror) {
285 $self->{$prop} = $self->_property_fget($prop);
288 $self->_readlocalconfigfile
289 unless ref($self->{configfilehash}) eq 'HASH';
290 delete $self->{auth};
291 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
292 defined($val) or $val = '';
293 chomp $val;
294 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
295 my $expire = $3;
296 if (time < $expire) {
297 $self->{authtype} = $1;
298 $self->{auth} = $2;
301 $self->_cleanup_readme;
302 delete $self->{configfilehash};
305 sub _set_bangagain {
306 my $self = shift;
307 my $fd;
308 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
309 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
310 if (open($fd, '>', $self->_bangagain_path)) {
311 close $fd;
312 chmod(0664, $self->_bangagain_path);
317 sub _properties_save {
318 my $self = shift;
319 delete $self->{configfilehash};
320 foreach my $prop (keys %propmap) {
321 $self->_property_fput($prop, $self->{$prop}, 1);
323 $self->_set_bangagain;
326 sub _nofetch_path {
327 my $self = shift;
328 $self->_property_path('.nofetch');
331 sub _nofetch {
332 my $self = shift;
333 my ($nofetch) = @_;
334 my $nf = $self->_nofetch_path;
335 if ($nofetch) {
336 open my $x, '>', $nf or die "nofetch failed: $!";
337 close $x;
338 } else {
339 unlink $nf or die "yesfetch failed: $!";
343 sub _banged_path {
344 my $self = shift;
345 $self->_property_path('.banged');
348 sub _bangagain_path {
349 my $self = shift;
350 $self->_property_path('.bangagain');
353 sub _gcp_path {
354 my $self = shift;
355 $self->_property_path('.gc_in_progress');
358 sub _clonelog_path {
359 my $self = shift;
360 $self->_property_path('.clonelog');
363 sub _clonefail_path {
364 my $self = shift;
365 $self->_property_path('.clone_failed');
368 sub _clonep_path {
369 my $self = shift;
370 $self->_property_path('.clone_in_progress');
373 sub _clonep {
374 my $self = shift;
375 my ($nofetch) = @_;
376 my $np = $self->_clonep_path;
377 if ($nofetch) {
378 open my $x, '>', $np or die "clonep failed: $!";
379 close $x;
380 } else {
381 unlink $np or die "clonef failed: $!";
384 sub _alternates_setup {
385 my $self = shift;
386 return unless $self->{name} =~ m#/#;
387 my $forkee_name = get_forkee_name($self->{name});
388 my $forkee_path = get_forkee_path($self->{name});
389 return unless -d $forkee_path;
390 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
391 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
392 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
394 # We set up both alternates and http_alternates since we cannot use
395 # relative path in alternates - that doesn't work recursively.
397 my $filename = $self->{path}.'/objects/info/alternates';
398 open my $x, '>', $filename or die "alternates failed: $!";
399 print $x "$forkee_path/objects\n";
400 close $x;
401 chmod 0664, $filename or warn "cannot chmod $filename: $!";
403 if ($Girocco::Config::httppullurl) {
404 $filename = $self->{path}.'/objects/info/http-alternates';
405 open my $x, '>', $filename or die "http-alternates failed: $!";
406 my $upfork = $forkee_name;
407 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
408 close $x;
409 chmod 0664, $filename or warn "cannot chmod $filename: $!";
412 # copy lastactivity from the parent project
413 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
414 my $activity = <$x>;
415 close $x;
416 last unless $activity;
417 open $x, '>', $self->{path}.'/info/lastactivity' or last;
418 print $x $activity;
419 close $x;
420 chomp $activity;
421 $self->{'lastactivity'} = $activity;
424 # copy refs from parent project
425 local *SAVEOUT;
426 open(SAVEOUT, ">&STDOUT") || die "couldn't dup STDOUT: $!";
427 my $result = open(STDOUT, '>', "$self->{path}/packed-refs");
428 my $resultstr = $!;
429 if (!$result) {
430 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
431 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
432 die "could not write fork's packed-refs file: $resultstr";
434 system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
435 $result = close(STDOUT);
436 $resultstr = $!;
437 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
438 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
439 $result or die "could not close fork's packed-refs file: $resultstr";
440 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
442 # initialize HEAD
443 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
444 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
445 chomp $HEAD;
446 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
447 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
450 sub _set_changed {
451 my $self = shift;
452 my $fd;
453 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
456 sub _set_forkchange {
457 my $self = shift;
458 my $changedtoo = shift;
459 return unless $self->{name} =~ m#/#;
460 my $forkee_path = get_forkee_path($self->{name});
461 return unless -d $forkee_path;
462 # mark forkee as changed
463 my $fd;
464 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
465 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
466 return if -e $forkee_path.'/htmlcache/summary.forkchange';
467 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
470 sub _ctags_setup {
471 my $self = shift;
472 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
473 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
476 sub _group_add {
477 my $self = shift;
478 my ($xtra) = @_;
479 $xtra .= join(',', @{$self->{users}});
480 filedb_atomic_append(jailed_file('/etc/group'),
481 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
484 sub _group_update {
485 my $self = shift;
486 my $xtra = join(',', @{$self->{users}});
487 filedb_atomic_edit(jailed_file('/etc/group'),
488 sub {
489 $_ = $_[0];
490 chomp;
491 if ($self->{name} eq (split /:/)[0]) {
492 # preserve readonly flag
493 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
494 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
495 } else {
496 return "$_\n";
502 sub _group_remove {
503 my $self = shift;
504 filedb_atomic_edit(jailed_file('/etc/group'),
505 sub {
506 $self->{name} ne (split /:/)[0] and return $_;
511 sub _hook_path {
512 my $self = shift;
513 my ($name) = @_;
514 $self->{path}.'/hooks/'.$name;
517 sub _hook_install {
518 my $self = shift;
519 my ($name) = @_;
520 my $hooksdir = $self->{path}.'/hooks';
521 my $oldmask = umask();
522 umask($oldmask & ~0070);
523 -d $hooksdir or mkdir $hooksdir or
524 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
525 umask($oldmask);
526 open my $src, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
527 open my $dst, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
528 while (<$src>) { print $dst $_; }
529 close $dst;
530 close $src;
531 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
534 sub _hooks_install {
535 my $self = shift;
536 foreach my $hook ('pre-receive', 'post-receive', 'update') {
537 $self->_hook_install($hook);
541 # private constructor, do not use
542 sub _new {
543 my $class = shift;
544 my ($name, $base_path, $path) = @_;
545 does_exist($name,1) || valid_name($name) or die "refusing to create project with invalid name ($name)!";
546 $path ||= "$base_path/$name.git";
547 my $proj = { name => $name, base_path => $base_path, path => $path };
549 bless $proj, $class;
552 # public constructor #0
553 # creates a virtual project not connected to disk image
554 # you can conjure() it later to disk
555 sub ghost {
556 my $class = shift;
557 my ($name, $mirror) = @_;
558 my $self = $class->_new($name, $Girocco::Config::reporoot);
559 $self->{users} = [];
560 $self->{mirror} = $mirror;
561 $self->{email} = $self->{orig_email} = '';
562 $self;
565 # public constructor #1
566 sub load {
567 my $class = shift;
568 my $name = shift || '';
570 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
571 my $r = qr/^\Q$name\E:/;
572 foreach (grep /$r/, <$fd>) {
573 chomp;
575 my $self = $class->_new($name, $Girocco::Config::reporoot);
576 (-d $self->{path} && $self->_readlocalconfigfile(1))
577 or die "invalid path (".$self->{path}.") for project ".$self->{name};
579 my $ulist;
580 (undef, $self->{crypt}, $self->{gid}, $ulist) = split /:/;
581 $ulist ||= '';
582 $self->{users} = [split /,/, $ulist];
583 $self->{HEAD} = $self->get_HEAD;
584 $self->{orig_HEAD} = $self->{HEAD};
585 $self->{orig_users} = [@{$self->{users}}];
586 $self->{mirror} = ! -e $self->_nofetch_path;
587 $self->{banged} = -e $self->_banged_path if $self->{mirror};
588 $self->{gc_in_progress} = -e $self->_gcp_path;
589 $self->{clone_in_progress} = -e $self->_clonep_path;
590 $self->{clone_logged} = -e $self->_clonelog_path;
591 $self->{clone_failed} = -e $self->_clonefail_path;
592 $self->{ccrypt} = $self->{crypt};
594 $self->_properties_load;
595 $self->{orig_email} = $self->{email};
596 $self->{loaded} = 1; # indicates self was loaded from etc/group file
597 close $fd;
598 return $self;
600 close $fd;
601 undef;
604 # $proj may not be in sane state if this returns false!
605 # fields listed in %$metadata_fields that are NOT also
606 # in @Girocco::Config::project_fields are totally ignored!
607 sub cgi_fill {
608 my $self = shift;
609 my ($gcgi) = @_;
610 my $cgi = $gcgi->cgi;
611 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
612 my $field_enabled = sub {
613 !exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]})};
615 my $pwd = $cgi->param('pwd');
616 my $pwd2 = $cgi->param('pwd2');
617 # in case passwords are disabled
618 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
619 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
620 $gcgi->err("Empty passwords are not permitted.");
622 if ($pwd ne '' or not $self->{crypt}) {
623 $self->{crypt} = scrypt_sha1($pwd);
625 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
626 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
629 $self->{cpwd} = $cgi->param('cpwd');
631 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
632 my $newtype = $forkee ? 'fork' : 'project';
633 length($project) <= 64
634 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
636 if ($Girocco::Config::project_owners eq 'email') {
637 $self->{email} = $gcgi->wparam('email');
638 valid_email($self->{email})
639 or $gcgi->err("Your email sure looks weird...?");
640 length($self->{email}) <= 96
641 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
644 # No setting the url unless we're either new or an existing mirror!
645 unless ($self->{loaded} && !$self->{mirror}) {
646 $self->{url} = $gcgi->wparam('url') ;
647 if ($field_enabled->('cleanmirror')) {
648 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
651 # Always validate the url if we're an existing mirror
652 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
653 # Always allow the url to be left unchanged without validation when editing
654 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
655 valid_repo_url($self->{url})
656 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
657 if ($Girocco::Config::restrict_mirror_hosts) {
658 my $mh = extract_url_hostname($self->{url});
659 is_dns_hostname($mh)
660 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
661 !is_our_hostname($mh)
662 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
666 if ($field_enabled->('desc')) {
667 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
668 length($self->{desc}) <= 1024
669 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
672 if ($field_enabled->('README')) {
673 $self->{README} = to_utf8($gcgi->wparam('README'), 1);
674 $self->_cleanup_readme;
675 length($self->{README}) <= 8192
676 or $gcgi->err("README length &gt; 8kb!");
677 my ($cnt, $err) = (0);
678 ($cnt, $err) = $self->_lint_readme if $gcgi->ok && $Girocco::Config::xmllint_readme;
679 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
682 if ($field_enabled->('hp')) {
683 $self->{hp} = $gcgi->wparam('hp');
684 if ($self->{hp}) {
685 valid_web_url($self->{hp})
686 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
690 # No mucking about with users unless we're a push project
691 if (($self->{loaded} && !$self->{mirror}) ||
692 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
693 my %users = ();
694 my @users = ();
695 foreach my $user ($cgi->multi_param('user')) {
696 if (!exists($users{$user})) {
697 $users{$user} = 1;
698 push(@users, $user) if Girocco::User::does_exist($user, 1);
701 $self->{users} = \@users;
704 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
705 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
706 my $newhead;
707 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
708 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
709 if ($newhead eq $self->{orig_HEAD} ||
710 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
711 $self->{HEAD} = $newhead;
712 } else {
713 $gcgi->err("Invalid default branch (no such ref)");
717 # schedule deletion of tags (will be committed by update() after auth)
718 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
720 if ($field_enabled->('notifymail')) {
721 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
722 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
723 $self->{notifymail} = $newaddrs;
724 } else {
725 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
727 if ($field_enabled->('reverseorder')) {
728 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
730 if ($field_enabled->('summaryonly')) {
731 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
735 if ($field_enabled->('notifytag')) {
736 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
737 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
738 $self->{notifytag} = $newaddrs;
739 } else {
740 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
744 if ($field_enabled->('notifyjson')) {
745 $self->{notifyjson} = $gcgi->wparam('notifyjson');
746 if ($self->{notifyjson}) {
747 valid_web_url($self->{notifyjson})
748 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
752 if ($field_enabled->('notifycia')) {
753 $self->{notifycia} = $gcgi->wparam('notifycia');
754 if ($self->{notifycia}) {
755 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
756 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
760 if ($cgi->param('setstatusupdates')) {
761 my $val = $gcgi->wparam('statusupdates') || '0';
762 $self->{statusupdates} = $val ? 1 : 0;
765 not $gcgi->err_check;
768 sub form_defaults {
769 my $self = shift;
771 name => $self->{name},
772 email => $self->{email},
773 url => $self->{url},
774 cleanmirror => $self->{cleanmirror},
775 desc => html_esc($self->{desc}),
776 README => html_esc($self->{README}),
777 hp => $self->{hp},
778 users => $self->{users},
779 notifymail => html_esc($self->{notifymail}),
780 reverseorder => $self->{reverseorder},
781 summaryonly => $self->{summaryonly},
782 notifytag => html_esc($self->{notifytag}),
783 notifyjson => html_esc($self->{notifyjson}),
784 notifycia => html_esc($self->{notifycia}),
788 # return true if $enc_passwd is a match for $plain_passwd
789 my $_check_passwd_match = sub {
790 my $enc_passwd = shift;
791 my $plain_passwd = shift;
792 defined($enc_passwd) or $enc_passwd = '';
793 defined($plain_passwd) or $plain_passwd = '';
794 # $enc_passwd may be crypt or crypt_sha1
795 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
796 # It's using sha1-crypt
797 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
798 } else {
799 # It's using crypt
800 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
804 sub authenticate {
805 my $self = shift;
806 my ($gcgi) = @_;
808 $self->{ccrypt} or die "Can't authenticate against a project with no password";
809 defined($self->{cpwd}) or $self->{cpwd} = '';
810 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
811 $gcgi->err("Your admin password does not match!");
812 return 0;
814 return 1;
817 # return true if the password from the file is empty or consists of all the same
818 # character. However, if the project was NOT loaded from the group file
819 # (!self->{loaded}) then the password is never locked.
820 # This function does NOT check $Girocco::Config::project_passwords, the caller
821 # is responsible for doing so if desired. Same for $self->{email}.
822 sub is_password_locked {
823 my $self = shift;
825 $self->{loaded} or return 0;
826 my $testcrypt = $self->{ccrypt}; # The value from the group file
827 defined($testcrypt) or $testcrypt = '';
828 $testcrypt ne '' or return 1; # No password at all
829 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
830 return 0; # Not locked
833 sub _setup {
834 use POSIX qw(strftime);
835 my $self = shift;
836 my ($pushers) = @_;
837 my $fd;
839 $self->_mkdir_forkees;
841 my $gid;
842 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
843 if ($Girocco::Config::owning_group) {
844 $gid = scalar(getgrnam($Girocco::Config::owning_group));
845 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
846 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
847 } else {
848 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
850 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
851 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
852 or die "git init $self->{path} failed: $?";
853 # we don't need these two, remove them (they will normally be created empty) if they exist
854 rmdir $self->{path}."/branches";
855 rmdir $self->{path}."/remotes";
856 -d $self->{path}."/info" or mkdir $self->{path}."/info"
857 or die "info directory does not exist and unable to create it: $!";
858 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
859 or die "hooks directory does not exist and unable to create it: $!";
860 # clean out any kruft that may have come in from the initial template directory
861 foreach my $cleandir (qw(hooks info)) {
862 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
863 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
864 closedir $hooksdir;
867 if ($Girocco::Config::owning_group) {
868 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
870 # hooks never world writable
871 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
872 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
873 or die "disabling core.logAllRefUpdates failed: $?";
874 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
875 or die "disabling core.ignoreCase failed: $?";
876 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
877 or die "enabling transfer.fsckObjects failed: $?";
878 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
879 or die "disabling receive.denyNonFastForwards failed: $?";
880 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
881 or die "disabling receive.denyDeleteCurrent failed: $?";
882 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
883 or die "disabling gc.auto failed: $?";
884 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
885 or die "disabling receive.autogc failed: $?";
886 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
887 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
888 or die "enabling receive.updateServerInfo failed: $?";
889 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
890 or die "enabling repack.writeBitmaps failed: $?";
891 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
892 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
893 or die "setting girocco.creationtime failed: $?";
894 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
895 or die "htmlcache directory does not exist and unable to create it: $!";
896 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
897 or die "bundles directory does not exist and unable to create it: $!";
898 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
899 or die "reflogs directory does not exist and unable to create it: $!";
900 foreach my $file (qw(info/lastactivity .delaygc)) {
901 if (open $fd, '>', $self->{path}."/".$file) {
902 close $fd;
903 chmod 0664, $self->{path}."/".$file;
907 # /info must have right permissions,
908 # and git init didn't do it for some reason.
909 # config must have correct permissions.
910 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
911 # also make sure /refs, /objects and /htmlcache are correct too.
912 my ($dmode, $dmodestr, $fmode, $fmodestr);
913 if ($Girocco::Config::owning_group) {
914 ($dmode, $dmodestr) = (02775, '02775');
915 ($fmode, $fmodestr) = (0664, '0664');
916 } else {
917 ($dmode, $dmodestr) = (02777, '02777');
918 ($fmode, $fmodestr) = (0666, '0666');
920 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
921 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
923 foreach my $file (qw(config)) {
924 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
926 # these ones are probably not strictly required but are nice to have
927 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
928 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
929 chmod($dmode, $self->{path}."/$dir");
932 $self->_properties_save;
933 $self->_alternates_setup;
934 $self->_ctags_setup;
935 $self->_group_remove;
936 $self->_group_add($pushers);
937 $self->_hooks_install;
938 $self->_update_index;
939 $self->_set_changed;
940 $self->_set_forkchange(1);
943 sub premirror {
944 my $self = shift;
946 $self->_setup(':');
947 $self->_clonep(1);
948 $self->perm_initialize;
951 sub conjure {
952 my $self = shift;
954 $self->_setup;
955 $self->_nofetch(1);
956 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
957 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
958 or die "create-personal-mob-area $self->{name} failed";
960 $self->perm_initialize;
963 sub clone {
964 my $self = shift;
966 unlink ($self->_clonefail_path()); # Ignore EEXIST error
967 unlink ($self->_clonelog_path()); # Ignore EEXIST error
969 use IO::Socket;
970 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
971 select((select($sock),$|=1)[0]);
972 $sock->print("clone ".$self->{name}."\n");
973 # Just ignore reply, we are going to succeed anyway and the I/O
974 # would apparently get quite hairy.
975 $sock->flush();
976 sleep 2; # *cough*
977 $sock->close();
980 sub _update_users {
981 my $self = shift;
983 $self->_group_update;
984 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
985 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
986 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
987 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
990 sub update {
991 my $self = shift;
993 $self->_properties_save;
994 $self->_update_users;
996 if (exists($self->{tags_to_delete})) {
997 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1000 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1002 $self->_update_index if $self->{email} ne $self->{orig_email};
1003 $self->{orig_email} = $self->{email};
1004 $self->_set_changed;
1009 sub update_password {
1010 my $self = shift;
1011 my ($pwd) = @_;
1013 $self->{crypt} = scrypt_sha1($pwd);
1014 $self->_group_update;
1017 # You can explicitly do this just on a ghost() repository too.
1018 sub delete {
1019 my $self = shift;
1021 if (-d $self->{path}) {
1022 system('rm', '-rf', $self->{path}) == 0
1023 or die "rm -rf $self->{path} failed: $?";
1025 # attempt to clean up any empty fork directories by removing them
1026 my @pelems = split('/', $self->{name});
1027 while (@pelems > 1) {
1028 pop @pelems;
1029 # okay to fail
1030 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1032 $self->_group_remove;
1033 $self->_update_index;
1034 $self->_set_forkchange(1);
1039 sub _contains_files {
1040 my $dir = shift;
1041 (-d $dir) or return 0;
1042 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1043 while (my $entry = readdir($dh)) {
1044 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1045 closedir($dh), return 1
1046 if -f "$dir/$entry" ||
1047 -d "$dir/$entry" && _contains_files("$dir/$entry");
1049 closedir($dh);
1050 return 0;
1053 sub has_forks {
1054 my $self = shift;
1056 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1059 # Returns an array of 0 or more array refs, one for each bundle:
1060 # ->[0]: bundle creation time (seconds since epoch)
1061 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1062 # ->[2]: bundle size in bytes
1063 sub bundles {
1064 my $self = shift;
1065 use Time::Local;
1067 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1068 my @blist = ();
1069 if (-d $self->{path}.'/bundles') {{
1070 my $prefix = $self->{name};
1071 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1072 opendir(my $dh, $self->{path}.'/bundles') or last;
1073 while (my $bfile = readdir($dh)) {
1074 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1075 my $ctime = eval {timegm(
1076 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1077 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4)-1900)};
1078 next unless $ctime;
1079 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1080 my $f1 = <$bh>;
1081 my $f2 = <$bh>;
1082 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1083 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1084 close($bh);
1085 next unless $f1 && $f2 && $f1 ne $f2;
1086 chomp $f1;
1087 chomp $f2;
1088 next unless -e $f1 && -e $f2;
1089 my $s1 = -s $f1 || 0;
1090 my $s2 = -s $f2 || 0;
1091 next unless $s1 || $s2;
1092 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1094 closedir($dh);
1096 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1097 my %seen = ();
1098 my @result = ();
1099 foreach my $bndl (@blist) {
1100 next if $seen{$bndl->[1]};
1101 $seen{$bndl->[1]} = 1;
1102 push(@result, $bndl);
1104 $self->{bundles} = \@result;
1105 return @result;
1108 sub has_alternates {
1109 my $self = shift;
1110 return -s $self->{path}.'/objects/info/alternates' ? 1 : 0;
1113 sub has_bundle {
1114 my $self = shift;
1116 return scalar($self->bundles);
1119 # returns true if any of the notify fields are non-empty
1120 sub has_notify {
1121 my $self = shift;
1122 # We do not ckeck notifycia since it's defunct
1123 return $self->{'notifymail'} || $self->{'notifytag'} || $self->{'notifyjson'};
1126 sub is_empty {
1127 # A project is considered empty if the git repository does not
1128 # have any refs. This means packed-refs does not exist or is
1129 # empty or only has lines starting with '#' AND there are no
1130 # files in the refs subdirectory hierarchy (no matter how deep).
1132 my $self = shift;
1134 (-d $self->{path}) or return 0;
1135 if (-e $self->{path}.'/packed-refs') {
1136 open(my $pr, '<', $self->{path}.'/packed-refs')
1137 or die "open $self->{path}./packed-refs failed: $!";
1138 my $foundref = 0;
1139 while (my $ref = <$pr>) {
1140 next if $ref =~ /^#/;
1141 $foundref = 1;
1142 last;
1144 close($pr);
1145 return 0 if $foundref;
1147 (-d $self->{path}.'/refs') or return 1;
1148 return !_contains_files($self->{path}.'/refs');
1151 # returns array:
1152 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1153 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1154 # Both values (if not undef) are seconds since epoch
1155 # Result only considers lastgc and min_gc_interval nothing else
1156 sub next_gc {
1157 my $self = shift;
1158 my $lastgcepoch = parse_any_date($self->{lastgc});
1159 return (undef, undef) unless defined $lastgcepoch;
1160 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1161 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1162 $Girocco::Config::min_mirror_interval));
1165 # returns boolean (0 or 1)
1166 # Attempts to determine whether or not a gc (and corresponding build
1167 # of a .bitmap/.bndl file) will actually take place at the next_gc
1168 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1169 # end up being built depends on whether or not the local object graph
1170 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1171 # is not possible because the object graph will be incomplete,
1172 # but it *is* possible that even though the repository has_alternates,
1173 # it does not actually borrow any objects so a .bitmap/.bndl will build
1174 # in spite of the presence of alternates -- but this is expected to be rare.
1175 # The result is a best guess and false return value is not an absolute
1176 # guarantee that gc will not take place at the next interval, but it probably
1177 # will not if nothing changes in the meantime.
1178 sub needs_gc {
1179 my $self = shift;
1180 my $lgc = parse_any_date($self->{lastgc});
1181 my $lrecv = parse_any_date($self->{lastreceive});
1182 my $lpgc = parse_any_date($self->{lastparentgc});
1183 return 1 unless defined($lgc) && defined($lrecv);
1184 if ($self->has_alternates) {
1185 return 1 unless defined($lpgc);
1186 return 1 unless $lpgc < $lgc;
1188 return 1 unless $lrecv < $lgc;
1189 # We don't try running any "is_dirty" check, so if somehow the
1190 # repository became dirty without updating lastreceive we might
1191 # incorrectly return false instead of true.
1192 return 0;
1195 sub delete_ctag {
1196 my $self = shift;
1197 my ($ctag) = @_;
1199 # sanity check, disallow filenames starting with . .. or /
1200 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
1203 sub get_ctag_names {
1204 my $self = shift;
1205 my @ctags = ();
1206 opendir(my $dh, $self->{path}.'/ctags')
1207 or return @ctags;
1208 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1209 closedir($dh);
1210 return sort({lc($a) cmp lc($b)} @ctags);
1213 sub get_heads {
1214 my $self = shift;
1215 my $fh;
1216 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1217 defined($heads) or $heads = '';
1218 chomp $heads;
1219 my @res = ();
1220 foreach (split(/\n/, $heads)) {
1221 chomp;
1222 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1223 push @res, $1;
1225 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1226 @res;
1229 sub get_HEAD {
1230 my $self = shift;
1231 my $HEAD = get_git("--git-dir=$self->{path}", 'symbolic-ref', 'HEAD');
1232 defined($HEAD) or $HEAD = '';
1233 chomp $HEAD;
1234 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
1235 return $1;
1238 sub set_HEAD {
1239 my $self = shift;
1240 my $newHEAD = shift;
1241 # Cursory checks only -- if you want to break your HEAD, be my guest
1242 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
1243 die "grossly invalid new HEAD: $newHEAD";
1245 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1246 die "could not set HEAD" if ($? >> 8);
1247 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1248 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1251 sub gen_auth {
1252 my $self = shift;
1253 my ($type) = @_;
1254 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1256 $self->{authtype} = $type;
1258 no warnings;
1259 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1261 my $expire = time + 24 * 3600;
1262 my $propval = "# ${type}AUTH $self->{auth} $expire";
1263 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1264 $self->{auth};
1267 sub del_auth {
1268 my $self = shift;
1270 delete $self->{auth};
1271 delete $self->{authtype};
1272 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1275 sub remove_user {
1276 my $self = shift;
1277 my ($username) = @_;
1279 my $before_count = @{$self->{users}};
1280 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1281 return @{$self->{users}} != $before_count;
1284 ### static methods
1286 sub get_forkee_name {
1287 local $_ = $_[0];
1288 (m#^(.*)/.*?$#)[0]; #
1291 sub get_forkee_path {
1292 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1293 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1294 -d $forkee ? $forkee : '';
1297 # Ultimately the full project/fork name could end up being part of a Git ref name
1298 # when a project's forks are combined into one giant repository for efficiency.
1299 # That means that the project/fork name must satisfy the Git ref name requirements:
1301 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1302 # 2. The character with an ASCII value of 0x7F is not allowed
1303 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1304 # 4. The character '/' is a separator and is not allowed within a name
1305 # 5. The name may not start with '.' or end with '.'
1306 # 6. The name may not end with '.lock'
1307 # 7. The name may not contain the '..' sequence
1308 # 8. The name may not contain the '@{' sequence
1309 # 9. If multiple components are used (separated by '/'), no empty '' components
1311 # We also prohibit a trailing '.git' on any path component and futher restrict
1312 # the allowed characters to alphanumeric and [+._-] where names must start with
1313 # an alphanumeric.
1315 sub _valid_name_characters {
1316 local $_ = $_[0];
1317 (not m#^[/+._-]#)
1318 and (not m#//#)
1319 and (not m#\.\.#)
1320 and (not m#/[+._-]#)
1321 and (not m#\./#)
1322 and (not m#\.$#)
1323 and (not m#\.git/#i)
1324 and (not m#\.git$#i)
1325 and (not m#\.idx/#i)
1326 and (not m#\.idx$#i)
1327 and (not m#\.lock/#i)
1328 and (not m#\.lock$#i)
1329 and (not m#\.pack/#i)
1330 and (not m#\.pack$#i)
1331 and (not m#\.bundle/#i)
1332 and (not m#\.bundle$#i)
1333 and (not m#/$#)
1334 and (not m/^[a-fA-F0-9]{38}$/)
1335 and m#^[a-zA-Z0-9/+._-]+$#
1336 and !has_reserved_suffix($_, $_[1], $_[2]);
1339 sub valid_name {
1340 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1341 local $_ = $_[0];
1342 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1343 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1344 and ((not m#/#) or -d get_forkee_path($_)) # will also catch ^/
1345 and (! -f $Girocco::Config::reporoot."/$_.git");
1348 # It's possible that some forks have been kept but the forkee is gone.
1349 # In this case the standard valid_name check is too strict.
1350 sub does_exist {
1351 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1352 my ($name, $nodie) = @_;
1353 my $okay = (
1354 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1355 and ((not $name =~ m#/#)
1356 or -d get_forkee_path($name)
1357 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1358 (!$okay && $nodie) and return undef;
1359 !$okay and die "tried to query for project with invalid name $name!";
1360 (-d $Girocco::Config::reporoot."/$name.git");
1363 sub get_full_list {
1364 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1365 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1366 close $fd;
1367 @projects;