Project.pm: load a few more values for mirrors
[girocco/readme.git] / Girocco / Project.pm
blob3cdcec632ef57e4f57cda86a0f0f0b3eeae52aef
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 $self->{notifymail} = $gcgi->wparam('notifymail');
722 if ($self->{notifymail}) {
723 (valid_email_multi($self->{notifymail}) and length($self->{notifymail}) <= 512)
724 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
726 if ($field_enabled->('reverseorder')) {
727 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
729 if ($field_enabled->('summaryonly')) {
730 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
734 if ($field_enabled->('notifytag')) {
735 $self->{notifytag} = $gcgi->wparam('notifytag');
736 if ($self->{notifytag}) {
737 (valid_email_multi($self->{notifytag}) and length($self->{notifytag}) <= 512)
738 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
742 if ($field_enabled->('notifyjson')) {
743 $self->{notifyjson} = $gcgi->wparam('notifyjson');
744 if ($self->{notifyjson}) {
745 valid_web_url($self->{notifyjson})
746 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
750 if ($field_enabled->('notifycia')) {
751 $self->{notifycia} = $gcgi->wparam('notifycia');
752 if ($self->{notifycia}) {
753 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
754 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
758 if ($cgi->param('setstatusupdates')) {
759 my $val = $gcgi->wparam('statusupdates') || '0';
760 $self->{statusupdates} = $val ? 1 : 0;
763 not $gcgi->err_check;
766 sub form_defaults {
767 my $self = shift;
769 name => $self->{name},
770 email => $self->{email},
771 url => $self->{url},
772 cleanmirror => $self->{cleanmirror},
773 desc => html_esc($self->{desc}),
774 README => html_esc($self->{README}),
775 hp => $self->{hp},
776 users => $self->{users},
777 notifymail => html_esc($self->{notifymail}),
778 reverseorder => $self->{reverseorder},
779 summaryonly => $self->{summaryonly},
780 notifytag => html_esc($self->{notifytag}),
781 notifyjson => html_esc($self->{notifyjson}),
782 notifycia => html_esc($self->{notifycia}),
786 # return true if $enc_passwd is a match for $plain_passwd
787 my $_check_passwd_match = sub {
788 my $enc_passwd = shift;
789 my $plain_passwd = shift;
790 defined($enc_passwd) or $enc_passwd = '';
791 defined($plain_passwd) or $plain_passwd = '';
792 # $enc_passwd may be crypt or crypt_sha1
793 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
794 # It's using sha1-crypt
795 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
796 } else {
797 # It's using crypt
798 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
802 sub authenticate {
803 my $self = shift;
804 my ($gcgi) = @_;
806 $self->{ccrypt} or die "Can't authenticate against a project with no password";
807 defined($self->{cpwd}) or $self->{cpwd} = '';
808 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
809 $gcgi->err("Your admin password does not match!");
810 return 0;
812 return 1;
815 # return true if the password from the file is empty or consists of all the same
816 # character. However, if the project was NOT loaded from the group file
817 # (!self->{loaded}) then the password is never locked.
818 # This function does NOT check $Girocco::Config::project_passwords, the caller
819 # is responsible for doing so if desired. Same for $self->{email}.
820 sub is_password_locked {
821 my $self = shift;
823 $self->{loaded} or return 0;
824 my $testcrypt = $self->{ccrypt}; # The value from the group file
825 defined($testcrypt) or $testcrypt = '';
826 $testcrypt ne '' or return 1; # No password at all
827 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
828 return 0; # Not locked
831 sub _setup {
832 use POSIX qw(strftime);
833 my $self = shift;
834 my ($pushers) = @_;
835 my $fd;
837 $self->_mkdir_forkees;
839 my $gid;
840 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
841 if ($Girocco::Config::owning_group) {
842 $gid = scalar(getgrnam($Girocco::Config::owning_group));
843 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
844 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
845 } else {
846 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
848 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
849 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
850 or die "git init $self->{path} failed: $?";
851 # we don't need these two, remove them (they will normally be created empty) if they exist
852 rmdir $self->{path}."/branches";
853 rmdir $self->{path}."/remotes";
854 -d $self->{path}."/info" or mkdir $self->{path}."/info"
855 or die "info directory does not exist and unable to create it: $!";
856 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
857 or die "hooks directory does not exist and unable to create it: $!";
858 # clean out any kruft that may have come in from the initial template directory
859 foreach my $cleandir (qw(hooks info)) {
860 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
861 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
862 closedir $hooksdir;
865 if ($Girocco::Config::owning_group) {
866 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
868 # hooks never world writable
869 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
870 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
871 or die "disabling core.logAllRefUpdates failed: $?";
872 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
873 or die "disabling core.ignoreCase failed: $?";
874 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
875 or die "enabling transfer.fsckObjects failed: $?";
876 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
877 or die "disabling receive.denyNonFastForwards failed: $?";
878 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
879 or die "disabling receive.denyDeleteCurrent failed: $?";
880 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
881 or die "disabling gc.auto failed: $?";
882 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
883 or die "disabling receive.autogc failed: $?";
884 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
885 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
886 or die "enabling receive.updateServerInfo failed: $?";
887 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
888 or die "enabling repack.writeBitmaps failed: $?";
889 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
890 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
891 or die "setting girocco.creationtime failed: $?";
892 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
893 or die "htmlcache directory does not exist and unable to create it: $!";
894 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
895 or die "bundles directory does not exist and unable to create it: $!";
896 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
897 or die "reflogs directory does not exist and unable to create it: $!";
898 foreach my $file (qw(info/lastactivity .delaygc)) {
899 if (open $fd, '>', $self->{path}."/".$file) {
900 close $fd;
901 chmod 0664, $self->{path}."/".$file;
905 # /info must have right permissions,
906 # and git init didn't do it for some reason.
907 # config must have correct permissions.
908 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
909 # also make sure /refs, /objects and /htmlcache are correct too.
910 my ($dmode, $dmodestr, $fmode, $fmodestr);
911 if ($Girocco::Config::owning_group) {
912 ($dmode, $dmodestr) = (02775, '02775');
913 ($fmode, $fmodestr) = (0664, '0664');
914 } else {
915 ($dmode, $dmodestr) = (02777, '02777');
916 ($fmode, $fmodestr) = (0666, '0666');
918 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
919 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
921 foreach my $file (qw(config)) {
922 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
924 # these ones are probably not strictly required but are nice to have
925 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
926 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
927 chmod($dmode, $self->{path}."/$dir");
930 $self->_properties_save;
931 $self->_alternates_setup;
932 $self->_ctags_setup;
933 $self->_group_remove;
934 $self->_group_add($pushers);
935 $self->_hooks_install;
936 $self->_update_index;
937 $self->_set_changed;
938 $self->_set_forkchange(1);
941 sub premirror {
942 my $self = shift;
944 $self->_setup(':');
945 $self->_clonep(1);
946 $self->perm_initialize;
949 sub conjure {
950 my $self = shift;
952 $self->_setup;
953 $self->_nofetch(1);
954 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
955 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
956 or die "create-personal-mob-area $self->{name} failed";
958 $self->perm_initialize;
961 sub clone {
962 my $self = shift;
964 unlink ($self->_clonefail_path()); # Ignore EEXIST error
965 unlink ($self->_clonelog_path()); # Ignore EEXIST error
967 use IO::Socket;
968 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
969 select((select($sock),$|=1)[0]);
970 $sock->print("clone ".$self->{name}."\n");
971 # Just ignore reply, we are going to succeed anyway and the I/O
972 # would apparently get quite hairy.
973 $sock->flush();
974 sleep 2; # *cough*
975 $sock->close();
978 sub update {
979 my $self = shift;
981 $self->_properties_save;
982 $self->_group_update;
984 if (exists($self->{tags_to_delete})) {
985 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
988 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
990 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
991 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
992 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
993 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
995 $self->_update_index if $self->{email} ne $self->{orig_email};
996 $self->{orig_email} = $self->{email};
997 $self->_set_changed;
1002 sub update_password {
1003 my $self = shift;
1004 my ($pwd) = @_;
1006 $self->{crypt} = scrypt_sha1($pwd);
1007 $self->_group_update;
1010 # You can explicitly do this just on a ghost() repository too.
1011 sub delete {
1012 my $self = shift;
1014 if (-d $self->{path}) {
1015 system('rm', '-rf', $self->{path}) == 0
1016 or die "rm -rf $self->{path} failed: $?";
1018 # attempt to clean up any empty fork directories by removing them
1019 my @pelems = split('/', $self->{name});
1020 while (@pelems > 1) {
1021 pop @pelems;
1022 # okay to fail
1023 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1025 $self->_group_remove;
1026 $self->_update_index;
1027 $self->_set_forkchange(1);
1032 sub _contains_files {
1033 my $dir = shift;
1034 (-d $dir) or return 0;
1035 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1036 while (my $entry = readdir($dh)) {
1037 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1038 closedir($dh), return 1
1039 if -f "$dir/$entry" ||
1040 -d "$dir/$entry" && _contains_files("$dir/$entry");
1042 closedir($dh);
1043 return 0;
1046 sub has_forks {
1047 my $self = shift;
1049 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1052 # Returns an array of 0 or more array refs, one for each bundle:
1053 # ->[0]: bundle creation time (seconds since epoch)
1054 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1055 # ->[2]: bundle size in bytes
1056 sub bundles {
1057 my $self = shift;
1058 use Time::Local;
1060 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1061 my @blist = ();
1062 if (-d $self->{path}.'/bundles') {{
1063 my $prefix = $self->{name};
1064 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1065 opendir(my $dh, $self->{path}.'/bundles') or last;
1066 while (my $bfile = readdir($dh)) {
1067 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1068 my $ctime = eval {timegm(
1069 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1070 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4)-1900)};
1071 next unless $ctime;
1072 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1073 my $f1 = <$bh>;
1074 my $f2 = <$bh>;
1075 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1076 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1077 close($bh);
1078 next unless $f1 && $f2 && $f1 ne $f2;
1079 chomp $f1;
1080 chomp $f2;
1081 next unless -e $f1 && -e $f2;
1082 my $s1 = -s $f1 || 0;
1083 my $s2 = -s $f2 || 0;
1084 next unless $s1 || $s2;
1085 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1087 closedir($dh);
1089 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1090 my %seen = ();
1091 my @result = ();
1092 foreach my $bndl (@blist) {
1093 next if $seen{$bndl->[1]};
1094 $seen{$bndl->[1]} = 1;
1095 push(@result, $bndl);
1097 $self->{bundles} = \@result;
1098 return @result;
1101 sub has_alternates {
1102 my $self = shift;
1103 return -s $self->{path}.'/objects/info/alternates' ? 1 : 0;
1106 sub has_bundle {
1107 my $self = shift;
1109 return scalar($self->bundles);
1112 # returns true if any of the notify fields are non-empty
1113 sub has_notify {
1114 my $self = shift;
1115 # We do not ckeck notifycia since it's defunct
1116 return $self->{'notifymail'} || $self->{'notifytag'} || $self->{'notifyjson'};
1119 sub is_empty {
1120 # A project is considered empty if the git repository does not
1121 # have any refs. This means packed-refs does not exist or is
1122 # empty or only has lines starting with '#' AND there are no
1123 # files in the refs subdirectory hierarchy (no matter how deep).
1125 my $self = shift;
1127 (-d $self->{path}) or return 0;
1128 if (-e $self->{path}.'/packed-refs') {
1129 open(my $pr, '<', $self->{path}.'/packed-refs')
1130 or die "open $self->{path}./packed-refs failed: $!";
1131 my $foundref = 0;
1132 while (my $ref = <$pr>) {
1133 next if $ref =~ /^#/;
1134 $foundref = 1;
1135 last;
1137 close($pr);
1138 return 0 if $foundref;
1140 (-d $self->{path}.'/refs') or return 1;
1141 return !_contains_files($self->{path}.'/refs');
1144 # returns array:
1145 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1146 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1147 # Both values (if not undef) are seconds since epoch
1148 # Result only considers lastgc and min_gc_interval nothing else
1149 sub next_gc {
1150 my $self = shift;
1151 my $lastgcepoch = parse_any_date($self->{lastgc});
1152 return (undef, undef) unless defined $lastgcepoch;
1153 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1154 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1155 $Girocco::Config::min_mirror_interval));
1158 # returns boolean (0 or 1)
1159 # Attempts to determine whether or not a gc (and corresponding build
1160 # of a .bitmap/.bndl file) will actually take place at the next_gc
1161 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1162 # end up being built depends on whether or not the local object graph
1163 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1164 # is not possible because the object graph will be incomplete,
1165 # but it *is* possible that even though the repository has_alternates,
1166 # it does not actually borrow any objects so a .bitmap/.bndl will build
1167 # in spite of the presence of alternates -- but this is expected to be rare.
1168 # The result is a best guess and false return value is not an absolute
1169 # guarantee that gc will not take place at the next interval, but it probably
1170 # will not if nothing changes in the meantime.
1171 sub needs_gc {
1172 my $self = shift;
1173 my $lgc = parse_any_date($self->{lastgc});
1174 my $lrecv = parse_any_date($self->{lastreceive});
1175 my $lpgc = parse_any_date($self->{lastparentgc});
1176 return 1 unless defined($lgc) && defined($lrecv);
1177 if ($self->has_alternates) {
1178 return 1 unless defined($lpgc);
1179 return 1 unless $lpgc < $lgc;
1181 return 1 unless $lrecv < $lgc;
1182 # We don't try running any "is_dirty" check, so if somehow the
1183 # repository became dirty without updating lastreceive we might
1184 # incorrectly return false instead of true.
1185 return 0;
1188 sub delete_ctag {
1189 my $self = shift;
1190 my ($ctag) = @_;
1192 # sanity check, disallow filenames starting with . .. or /
1193 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
1196 sub get_ctag_names {
1197 my $self = shift;
1198 my @ctags = ();
1199 opendir(my $dh, $self->{path}.'/ctags')
1200 or return @ctags;
1201 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1202 closedir($dh);
1203 return sort({lc($a) cmp lc($b)} @ctags);
1206 sub get_heads {
1207 my $self = shift;
1208 my $fh;
1209 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1210 defined($heads) or $heads = '';
1211 chomp $heads;
1212 my @res = ();
1213 foreach (split(/\n/, $heads)) {
1214 chomp;
1215 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1216 push @res, $1;
1218 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1219 @res;
1222 sub get_HEAD {
1223 my $self = shift;
1224 my $HEAD = get_git("--git-dir=$self->{path}", 'symbolic-ref', 'HEAD');
1225 defined($HEAD) or $HEAD = '';
1226 chomp $HEAD;
1227 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
1228 return $1;
1231 sub set_HEAD {
1232 my $self = shift;
1233 my $newHEAD = shift;
1234 # Cursory checks only -- if you want to break your HEAD, be my guest
1235 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
1236 die "grossly invalid new HEAD: $newHEAD";
1238 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1239 die "could not set HEAD" if ($? >> 8);
1240 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1241 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1244 sub gen_auth {
1245 my $self = shift;
1246 my ($type) = @_;
1247 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1249 $self->{authtype} = $type;
1251 no warnings;
1252 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1254 my $expire = time + 24 * 3600;
1255 my $propval = "# ${type}AUTH $self->{auth} $expire";
1256 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1257 $self->{auth};
1260 sub del_auth {
1261 my $self = shift;
1263 delete $self->{auth};
1264 delete $self->{authtype};
1265 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1268 sub remove_user {
1269 my $self = shift;
1270 my ($username) = @_;
1272 my $before_count = @{$self->{users}};
1273 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1274 return @{$self->{users}} != $before_count;
1277 ### static methods
1279 sub get_forkee_name {
1280 local $_ = $_[0];
1281 (m#^(.*)/.*?$#)[0]; #
1284 sub get_forkee_path {
1285 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1286 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1287 -d $forkee ? $forkee : '';
1290 # Ultimately the full project/fork name could end up being part of a Git ref name
1291 # when a project's forks are combined into one giant repository for efficiency.
1292 # That means that the project/fork name must satisfy the Git ref name requirements:
1294 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1295 # 2. The character with an ASCII value of 0x7F is not allowed
1296 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1297 # 4. The character '/' is a separator and is not allowed within a name
1298 # 5. The name may not start with '.' or end with '.'
1299 # 6. The name may not end with '.lock'
1300 # 7. The name may not contain the '..' sequence
1301 # 8. The name may not contain the '@{' sequence
1302 # 9. If multiple components are used (separated by '/'), no empty '' components
1304 # We also prohibit a trailing '.git' on any path component and futher restrict
1305 # the allowed characters to alphanumeric and [+._-] where names must start with
1306 # an alphanumeric.
1308 sub _valid_name_characters {
1309 local $_ = $_[0];
1310 (not m#^[/+._-]#)
1311 and (not m#//#)
1312 and (not m#\.\.#)
1313 and (not m#/[+._-]#)
1314 and (not m#\./#)
1315 and (not m#\.$#)
1316 and (not m#\.git/#i)
1317 and (not m#\.git$#i)
1318 and (not m#\.idx/#i)
1319 and (not m#\.idx$#i)
1320 and (not m#\.lock/#i)
1321 and (not m#\.lock$#i)
1322 and (not m#\.pack/#i)
1323 and (not m#\.pack$#i)
1324 and (not m#\.bundle/#i)
1325 and (not m#\.bundle$#i)
1326 and (not m#/$#)
1327 and (not m/^[a-fA-F0-9]{38}$/)
1328 and m#^[a-zA-Z0-9/+._-]+$#
1329 and !has_reserved_suffix($_, $_[1], $_[2]);
1332 sub valid_name {
1333 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1334 local $_ = $_[0];
1335 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1336 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1337 and ((not m#/#) or -d get_forkee_path($_)); # will also catch ^/
1340 # It's possible that some forks have been kept but the forkee is gone.
1341 # In this case the standard valid_name check is too strict.
1342 sub does_exist {
1343 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1344 my ($name, $nodie) = @_;
1345 my $okay = (
1346 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1347 and ((not $name =~ m#/#)
1348 or -d get_forkee_path($name)
1349 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1350 (!$okay && $nodie) and return undef;
1351 !$okay and die "tried to query for project with invalid name $name!";
1352 (-d $Girocco::Config::reporoot."/$name.git");
1355 sub get_full_list {
1356 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1357 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1358 close $fd;
1359 @projects;