Project.pm: support orphan project creation
[girocco.git] / Girocco / Project.pm
blob582aba876e4e8fe3d9af8c274fac0019c9599ecf
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 my $htmlfrag = shift;
258 defined($htmlfrag) or $htmlfrag = 1;
259 return 0 unless defined($self->{README}) && $self->{README} ne '';
260 my $test = '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>';
261 $test .= $self->{README};
262 $test .= '</div></body></html>';
263 my ($code, $errors) = capture_command(2, $test, 'xmllint', '--nonet',
264 '--noout', '--nowarning', '-');
265 return 0 unless $code;
266 my $cnt = 0;
267 my @errs = ();
268 for my $line (split(/\n+/, $errors)) {
269 $line = html_esc($line) if $htmlfrag;
270 $line =~ s/ /\&#160;/gs if $htmlfrag;
271 ++$cnt, $line = 'README'.$1 if $line =~ /^-(:\d+:.*)$/;
272 if ($htmlfrag) {
273 push @errs, '<tt>' . $line . '</tt>';
274 } else {
275 push @errs, $line . "\n";
278 if ($htmlfrag) {
279 return ($cnt, join("<br />\n", @errs));
280 } else {
281 return ($cnt, join("", @errs));
285 sub _properties_load {
286 my $self = shift;
287 foreach my $prop (keys %propmap) {
288 $self->{$prop} = $self->_property_fget($prop);
290 foreach my $prop (keys %propmapro) {
291 $self->{$prop} = $self->_property_fget($prop);
293 if ($self->{mirror}) {
294 foreach my $prop (keys %propmapromirror) {
295 $self->{$prop} = $self->_property_fget($prop);
298 $self->_readlocalconfigfile
299 unless ref($self->{configfilehash}) eq 'HASH';
300 delete $self->{auth};
301 my $val = $self->{configfilehash}->{'gitweb.repoauth'};
302 defined($val) or $val = '';
303 chomp $val;
304 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
305 my $expire = $3;
306 if (time < $expire) {
307 $self->{authtype} = $1;
308 $self->{auth} = $2;
311 $self->_cleanup_readme;
312 delete $self->{configfilehash};
315 sub _set_bangagain {
316 my $self = shift;
317 my $fd;
318 if ($self->{mirror} && defined($self->{origurl}) && $self->{url} &&
319 $self->{origurl} ne $self->{url} && -e $self->_banged_path) {
320 if (open($fd, '>', $self->_bangagain_path)) {
321 close $fd;
322 chmod(0664, $self->_bangagain_path);
327 sub _properties_save {
328 my $self = shift;
329 delete $self->{configfilehash};
330 foreach my $prop (keys %propmap) {
331 $self->_property_fput($prop, $self->{$prop}, 1);
333 $self->_set_bangagain;
336 sub _nofetch_path {
337 my $self = shift;
338 $self->_property_path('.nofetch');
341 sub _nofetch {
342 my $self = shift;
343 my ($nofetch) = @_;
344 my $nf = $self->_nofetch_path;
345 if ($nofetch) {
346 open my $x, '>', $nf or die "nofetch failed: $!";
347 close $x;
348 } else {
349 unlink $nf or die "yesfetch failed: $!";
353 sub _banged_path {
354 my $self = shift;
355 $self->_property_path('.banged');
358 sub _bangagain_path {
359 my $self = shift;
360 $self->_property_path('.bangagain');
363 sub _gcp_path {
364 my $self = shift;
365 $self->_property_path('.gc_in_progress');
368 sub _clonelog_path {
369 my $self = shift;
370 $self->_property_path('.clonelog');
373 sub _clonefail_path {
374 my $self = shift;
375 $self->_property_path('.clone_failed');
378 sub _clonep_path {
379 my $self = shift;
380 $self->_property_path('.clone_in_progress');
383 sub _clonep {
384 my $self = shift;
385 my ($nofetch) = @_;
386 my $np = $self->_clonep_path;
387 if ($nofetch) {
388 open my $x, '>', $np or die "clonep failed: $!";
389 close $x;
390 } else {
391 unlink $np or die "clonef failed: $!";
394 sub _alternates_setup {
395 my $self = shift;
396 return unless $self->{name} =~ m#/#;
397 my $forkee_name = get_forkee_name($self->{name});
398 my $forkee_path = get_forkee_path($self->{name});
399 return unless -d $forkee_path;
400 mkdir $self->{path}.'/refs'; chmod 02775, $self->{path}.'/refs';
401 mkdir $self->{path}.'/objects'; chmod 02775, $self->{path}.'/objects';
402 mkdir $self->{path}.'/objects/info'; chmod 02775, $self->{path}.'/objects/info';
404 # We set up both alternates and http_alternates since we cannot use
405 # relative path in alternates - that doesn't work recursively.
407 my $filename = $self->{path}.'/objects/info/alternates';
408 open my $x, '>', $filename or die "alternates failed: $!";
409 print $x "$forkee_path/objects\n";
410 close $x;
411 chmod 0664, $filename or warn "cannot chmod $filename: $!";
413 if ($Girocco::Config::httppullurl) {
414 $filename = $self->{path}.'/objects/info/http-alternates';
415 open my $x, '>', $filename or die "http-alternates failed: $!";
416 my $upfork = $forkee_name;
417 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s#/?.+?$## and $upfork); #
418 close $x;
419 chmod 0664, $filename or warn "cannot chmod $filename: $!";
422 # copy lastactivity from the parent project
423 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
424 my $activity = <$x>;
425 close $x;
426 last unless $activity;
427 open $x, '>', $self->{path}.'/info/lastactivity' or last;
428 print $x $activity;
429 close $x;
430 chomp $activity;
431 $self->{'lastactivity'} = $activity;
434 # copy refs from parent project
435 local *SAVEOUT;
436 open(SAVEOUT, ">&STDOUT") || die "couldn't dup STDOUT: $!";
437 my $result = open(STDOUT, '>', "$self->{path}/packed-refs");
438 my $resultstr = $!;
439 if (!$result) {
440 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
441 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
442 die "could not write fork's packed-refs file: $resultstr";
444 system($Girocco::Config::git_bin, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
445 $result = close(STDOUT);
446 $resultstr = $!;
447 open(STDOUT, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
448 close(SAVEOUT) or die "couldn't close SAVEOUT: $!";
449 $result or die "could not close fork's packed-refs file: $resultstr";
450 unlink("$self->{path}/.delaygc") if -s "$self->{path}/packed-refs";
452 # initialize HEAD
453 my $HEAD = get_git("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
454 defined($HEAD) && $HEAD =~ m,^refs/heads/., or $HEAD = 'refs/heads/master';
455 chomp $HEAD;
456 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
457 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
460 sub _set_changed {
461 my $self = shift;
462 my $fd;
463 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
466 sub _set_forkchange {
467 my $self = shift;
468 my $changedtoo = shift;
469 return unless $self->{name} =~ m#/#;
470 my $forkee_path = get_forkee_path($self->{name});
471 return unless -d $forkee_path;
472 # mark forkee as changed
473 my $fd;
474 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
475 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
476 return if -e $forkee_path.'/htmlcache/summary.forkchange';
477 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
480 sub _ctags_setup {
481 my $self = shift;
482 my $perms = $Girocco::Config::permission_control eq 'Hooks' ? 02777 : 02775;
483 mkdir $self->{path}.'/ctags'; chmod $perms, $self->{path}.'/ctags';
486 sub _group_add {
487 my $self = shift;
488 my ($xtra) = @_;
489 $xtra .= join(',', @{$self->{users}});
490 filedb_atomic_append(jailed_file('/etc/group'),
491 join(':', $self->{name}, $self->{crypt}, '\i', $xtra));
494 sub _group_update {
495 my $self = shift;
496 my $xtra = join(',', @{$self->{users}});
497 filedb_atomic_edit(jailed_file('/etc/group'),
498 sub {
499 $_ = $_[0];
500 chomp;
501 if ($self->{name} eq (split /:/)[0]) {
502 # preserve readonly flag
503 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
504 return join(':', $self->{name}, $self->{crypt}, $self->{gid}, $xtra)."\n";
505 } else {
506 return "$_\n";
512 sub _group_remove {
513 my $self = shift;
514 filedb_atomic_edit(jailed_file('/etc/group'),
515 sub {
516 $self->{name} ne (split /:/)[0] and return $_;
521 sub _hook_path {
522 my $self = shift;
523 my ($name) = @_;
524 $self->{path}.'/hooks/'.$name;
527 sub _hook_install {
528 my $self = shift;
529 my ($name) = @_;
530 my $hooksdir = $self->{path}.'/hooks';
531 my $oldmask = umask();
532 umask($oldmask & ~0070);
533 -d $hooksdir or mkdir $hooksdir or
534 die "hooks directory does not exist and unable to create it for project " . $self->{name} . ": $!";
535 umask($oldmask);
536 open my $src, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
537 open my $dst, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
538 while (<$src>) { print $dst $_; }
539 close $dst;
540 close $src;
541 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
544 sub _hooks_install {
545 my $self = shift;
546 foreach my $hook ('pre-receive', 'post-receive', 'update') {
547 $self->_hook_install($hook);
551 # private constructor, do not use
552 sub _new {
553 my $class = shift;
554 my ($name, $base_path, $path, $orphan, $optp) = @_;
555 does_exist($name,1) || valid_name($name, $orphan, $optp) or die "refusing to create project with invalid name ($name)!";
556 $path ||= "$base_path/$name.git";
557 my $proj = { name => $name, base_path => $base_path, path => $path };
559 bless $proj, $class;
562 # public constructor #0
563 # creates a virtual project not connected to disk image
564 # you can conjure() it later to disk
565 sub ghost {
566 my $class = shift;
567 my ($name, $mirror, $orphan, $optp) = @_;
568 my $self = $class->_new($name, $Girocco::Config::reporoot, undef, $orphan, $optp);
569 $self->{users} = [];
570 $self->{mirror} = $mirror;
571 $self->{email} = $self->{orig_email} = '';
572 $self;
575 # public constructor #1
576 sub load {
577 my $class = shift;
578 my $name = shift || '';
580 open my $fd, '<', jailed_file("/etc/group") or die "project load failed: $!";
581 my $r = qr/^\Q$name\E:/;
582 foreach (grep /$r/, <$fd>) {
583 chomp;
585 my $self = $class->_new($name, $Girocco::Config::reporoot);
586 (-d $self->{path} && $self->_readlocalconfigfile(1))
587 or die "invalid path (".$self->{path}.") for project ".$self->{name};
589 my $ulist;
590 (undef, $self->{crypt}, $self->{gid}, $ulist) = split /:/;
591 $ulist ||= '';
592 $self->{users} = [split /,/, $ulist];
593 $self->{HEAD} = $self->get_HEAD;
594 $self->{orig_HEAD} = $self->{HEAD};
595 $self->{orig_users} = [@{$self->{users}}];
596 $self->{mirror} = ! -e $self->_nofetch_path;
597 $self->{banged} = -e $self->_banged_path if $self->{mirror};
598 $self->{gc_in_progress} = -e $self->_gcp_path;
599 $self->{clone_in_progress} = -e $self->_clonep_path;
600 $self->{clone_logged} = -e $self->_clonelog_path;
601 $self->{clone_failed} = -e $self->_clonefail_path;
602 $self->{ccrypt} = $self->{crypt};
604 $self->_properties_load;
605 $self->{orig_email} = $self->{email};
606 $self->{loaded} = 1; # indicates self was loaded from etc/group file
607 close $fd;
608 return $self;
610 close $fd;
611 undef;
614 # $proj may not be in sane state if this returns false!
615 # fields listed in %$metadata_fields that are NOT also
616 # in @Girocco::Config::project_fields are totally ignored!
617 sub cgi_fill {
618 my $self = shift;
619 my ($gcgi) = @_;
620 my $cgi = $gcgi->cgi;
621 my %allowedfields = map({$_ => 1} @Girocco::Config::project_fields);
622 my $field_enabled = sub {
623 !exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]})};
625 my $pwd = $cgi->param('pwd');
626 my $pwd2 = $cgi->param('pwd2');
627 # in case passwords are disabled
628 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd2 = '';
629 if ($Girocco::Config::project_passwords and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
630 $gcgi->err("Empty passwords are not permitted.");
632 if ($pwd ne '' or not $self->{crypt}) {
633 $self->{crypt} = scrypt_sha1($pwd);
635 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
636 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
639 $self->{cpwd} = $cgi->param('cpwd');
641 my ($forkee,$project) = ($self->{name} =~ m#^(.*/)?([^/]+)$#);
642 my $newtype = $forkee ? 'fork' : 'project';
643 length($project) <= 64
644 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
646 if ($Girocco::Config::project_owners eq 'email') {
647 $self->{email} = $gcgi->wparam('email');
648 valid_email($self->{email})
649 or $gcgi->err("Your email sure looks weird...?");
650 length($self->{email}) <= 96
651 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
654 # No setting the url unless we're either new or an existing mirror!
655 unless ($self->{loaded} && !$self->{mirror}) {
656 $self->{url} = $gcgi->wparam('url') ;
657 if ($field_enabled->('cleanmirror')) {
658 $self->{cleanmirror} = $gcgi->wparam('cleanmirror') || 0;
661 # Always validate the url if we're an existing mirror
662 if ((defined($self->{url}) && $self->{url} ne '') || ($self->{loaded} && $self->{mirror})) {{
663 # Always allow the url to be left unchanged without validation when editing
664 last if $self->{loaded} && defined($self->{origurl}) && defined($self->{url}) && $self->{origurl} eq $self->{url};
665 valid_repo_url($self->{url})
666 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
667 if ($Girocco::Config::restrict_mirror_hosts) {
668 my $mh = extract_url_hostname($self->{url});
669 is_dns_hostname($mh)
670 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
671 !is_our_hostname($mh)
672 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
676 if ($field_enabled->('desc')) {
677 $self->{desc} = to_utf8($gcgi->wparam('desc'), 1);
678 length($self->{desc}) <= 1024
679 or $gcgi->err("<b>Short</b> description length &gt; 1kb!");
682 if ($field_enabled->('README')) {
683 $self->{README} = to_utf8($gcgi->wparam('README'), 1);
684 $self->_cleanup_readme;
685 length($self->{README}) <= 8192
686 or $gcgi->err("README length &gt; 8kb!");
687 my ($cnt, $err) = (0);
688 ($cnt, $err) = $self->_lint_readme if $gcgi->ok && $Girocco::Config::xmllint_readme;
689 $gcgi->err($err), $gcgi->{err} += $cnt-1 if $cnt;
692 if ($field_enabled->('hp')) {
693 $self->{hp} = $gcgi->wparam('hp');
694 if ($self->{hp}) {
695 valid_web_url($self->{hp})
696 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
700 # No mucking about with users unless we're a push project
701 if (($self->{loaded} && !$self->{mirror}) ||
702 (!$self->{loaded} && (!defined($self->{url}) || $self->{url} eq ''))) {
703 my %users = ();
704 my @users = ();
705 foreach my $user ($cgi->multi_param('user')) {
706 if (!exists($users{$user})) {
707 $users{$user} = 1;
708 push(@users, $user) if Girocco::User::does_exist($user, 1);
711 $self->{users} = \@users;
714 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
715 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
716 my $newhead;
717 if (defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '' &&
718 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
719 if ($newhead eq $self->{orig_HEAD} ||
720 get_git("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
721 $self->{HEAD} = $newhead;
722 } else {
723 $gcgi->err("Invalid default branch (no such ref)");
727 # schedule deletion of tags (will be committed by update() after auth)
728 $self->{tags_to_delete} = [$cgi->multi_param('tags')];
730 if ($field_enabled->('notifymail')) {
731 my $newaddrs = clean_email_multi($gcgi->wparam('notifymail'));
732 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
733 $self->{notifymail} = $newaddrs;
734 } else {
735 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
737 if ($field_enabled->('reverseorder')) {
738 $self->{reverseorder} = $gcgi->wparam('reverseorder') || 0;
740 if ($field_enabled->('summaryonly')) {
741 $self->{summaryonly} = $gcgi->wparam('summaryonly') || 0;
745 if ($field_enabled->('notifytag')) {
746 my $newaddrs = clean_email_multi($gcgi->wparam('notifytag'));
747 if ($newaddrs eq "" or (valid_email_multi($newaddrs) and length($newaddrs) <= 512)) {
748 $self->{notifytag} = $newaddrs;
749 } else {
750 $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
754 if ($field_enabled->('notifyjson')) {
755 $self->{notifyjson} = $gcgi->wparam('notifyjson');
756 if ($self->{notifyjson}) {
757 valid_web_url($self->{notifyjson})
758 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
762 if ($field_enabled->('notifycia')) {
763 $self->{notifycia} = $gcgi->wparam('notifycia');
764 if ($self->{notifycia}) {
765 $self->{notifycia} =~ /^[a-zA-Z0-9._-]+$/
766 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
770 if ($cgi->param('setstatusupdates')) {
771 my $val = $gcgi->wparam('statusupdates') || '0';
772 $self->{statusupdates} = $val ? 1 : 0;
775 not $gcgi->err_check;
778 sub form_defaults {
779 my $self = shift;
781 name => $self->{name},
782 email => $self->{email},
783 url => $self->{url},
784 cleanmirror => $self->{cleanmirror},
785 desc => html_esc($self->{desc}),
786 README => html_esc($self->{README}),
787 hp => $self->{hp},
788 users => $self->{users},
789 notifymail => html_esc($self->{notifymail}),
790 reverseorder => $self->{reverseorder},
791 summaryonly => $self->{summaryonly},
792 notifytag => html_esc($self->{notifytag}),
793 notifyjson => html_esc($self->{notifyjson}),
794 notifycia => html_esc($self->{notifycia}),
798 # return true if $enc_passwd is a match for $plain_passwd
799 my $_check_passwd_match = sub {
800 my $enc_passwd = shift;
801 my $plain_passwd = shift;
802 defined($enc_passwd) or $enc_passwd = '';
803 defined($plain_passwd) or $plain_passwd = '';
804 # $enc_passwd may be crypt or crypt_sha1
805 if ($enc_passwd =~ m(^\$sha1\$(\d+)\$([./0-9A-Za-z]{1,64})\$[./0-9A-Za-z]{28}$)) {
806 # It's using sha1-crypt
807 return $enc_passwd eq crypt_sha1($plain_passwd, $2, -(0+$1));
808 } else {
809 # It's using crypt
810 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
814 sub authenticate {
815 my $self = shift;
816 my ($gcgi) = @_;
818 $self->{ccrypt} or die "Can't authenticate against a project with no password";
819 defined($self->{cpwd}) or $self->{cpwd} = '';
820 unless ($_check_passwd_match->($self->{ccrypt}, $self->{cpwd})) {
821 $gcgi->err("Your admin password does not match!");
822 return 0;
824 return 1;
827 # return true if the password from the file is empty or consists of all the same
828 # character. However, if the project was NOT loaded from the group file
829 # (!self->{loaded}) then the password is never locked.
830 # This function does NOT check $Girocco::Config::project_passwords, the caller
831 # is responsible for doing so if desired. Same for $self->{email}.
832 sub is_password_locked {
833 my $self = shift;
835 $self->{loaded} or return 0;
836 my $testcrypt = $self->{ccrypt}; # The value from the group file
837 defined($testcrypt) or $testcrypt = '';
838 $testcrypt ne '' or return 1; # No password at all
839 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
840 return 0; # Not locked
843 sub _setup {
844 use POSIX qw(strftime);
845 my $self = shift;
846 my ($pushers) = @_;
847 my $fd;
849 $self->_mkdir_forkees;
851 my $gid;
852 mkdir($self->{path}) or die "mkdir $self->{path} failed: $!";
853 if ($Girocco::Config::owning_group) {
854 $gid = scalar(getgrnam($Girocco::Config::owning_group));
855 chown(-1, $gid, $self->{path}) or die "chgrp $gid $self->{path} failed: $!";
856 chmod(02775, $self->{path}) or die "chmod 02775 $self->{path} failed: $!";
857 } else {
858 chmod(02777, $self->{path}) or die "chmod 02777 $self->{path} failed: $!";
860 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config::chroot.'/var/empty';
861 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
862 or die "git init $self->{path} failed: $?";
863 # we don't need these two, remove them (they will normally be created empty) if they exist
864 rmdir $self->{path}."/branches";
865 rmdir $self->{path}."/remotes";
866 -d $self->{path}."/info" or mkdir $self->{path}."/info"
867 or die "info directory does not exist and unable to create it: $!";
868 -d $self->{path}."/hooks" or mkdir $self->{path}."/hooks"
869 or die "hooks directory does not exist and unable to create it: $!";
870 # clean out any kruft that may have come in from the initial template directory
871 foreach my $cleandir (qw(hooks info)) {
872 if (opendir my $hooksdir, $self->{path}.'/'.$cleandir) {
873 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
874 closedir $hooksdir;
877 if ($Girocco::Config::owning_group) {
878 chown(-1, $gid, $self->{path}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
880 # hooks never world writable
881 chmod 02775, $self->{path}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
882 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.logAllRefUpdates', 'false') == 0
883 or die "disabling core.logAllRefUpdates failed: $?";
884 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'core.ignoreCase', 'false') == 0
885 or die "disabling core.ignoreCase failed: $?";
886 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'transfer.fsckObjects', 'true') == 0
887 or die "enabling transfer.fsckObjects failed: $?";
888 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyNonFastForwards', 'false') == 0
889 or die "disabling receive.denyNonFastForwards failed: $?";
890 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
891 or die "disabling receive.denyDeleteCurrent failed: $?";
892 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gc.auto', '0') == 0
893 or die "disabling gc.auto failed: $?";
894 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.autogc', '0') == 0
895 or die "disabling receive.autogc failed: $?";
896 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
897 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'receive.updateServerInfo', 'true') == 0
898 or die "enabling receive.updateServerInfo failed: $?";
899 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'repack.writeBitmaps', 'true') == 0
900 or die "enabling repack.writeBitmaps failed: $?";
901 $self->{creationtime} = strftime("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
902 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'girocco.creationtime', $self->{creationtime}) == 0
903 or die "setting girocco.creationtime failed: $?";
904 -d $self->{path}."/htmlcache" or mkdir $self->{path}."/htmlcache"
905 or die "htmlcache directory does not exist and unable to create it: $!";
906 -d $self->{path}."/bundles" or mkdir $self->{path}."/bundles"
907 or die "bundles directory does not exist and unable to create it: $!";
908 -d $self->{path}."/reflogs" or mkdir $self->{path}."/reflogs"
909 or die "reflogs directory does not exist and unable to create it: $!";
910 foreach my $file (qw(info/lastactivity .delaygc)) {
911 if (open $fd, '>', $self->{path}."/".$file) {
912 close $fd;
913 chmod 0664, $self->{path}."/".$file;
917 # /info must have right permissions,
918 # and git init didn't do it for some reason.
919 # config must have correct permissions.
920 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
921 # also make sure /refs, /objects and /htmlcache are correct too.
922 my ($dmode, $dmodestr, $fmode, $fmodestr);
923 if ($Girocco::Config::owning_group) {
924 ($dmode, $dmodestr) = (02775, '02775');
925 ($fmode, $fmodestr) = (0664, '0664');
926 } else {
927 ($dmode, $dmodestr) = (02777, '02777');
928 ($fmode, $fmodestr) = (0666, '0666');
930 foreach my $dir (qw(info refs objects htmlcache bundles reflogs)) {
931 chmod($dmode, $self->{path}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
933 foreach my $file (qw(config)) {
934 chmod($fmode, $self->{path}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
936 # these ones are probably not strictly required but are nice to have
937 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
938 -d $self->{path}."/$dir" or mkdir $self->{path}."/$dir";
939 chmod($dmode, $self->{path}."/$dir");
942 $self->_properties_save;
943 $self->_alternates_setup unless $self->{noalternates};
944 $self->_ctags_setup;
945 $self->_group_remove;
946 $self->_group_add($pushers);
947 $self->_hooks_install;
948 $self->_update_index;
949 $self->_set_changed;
950 $self->_set_forkchange(1);
953 sub premirror {
954 my $self = shift;
956 $self->_setup(':');
957 $self->_clonep(1);
958 $self->perm_initialize;
961 sub conjure {
962 my $self = shift;
964 $self->_setup;
965 $self->_nofetch(1);
966 if ($Girocco::Config::mob && $Girocco::Config::mob eq "mob") {
967 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name}) == 0
968 or die "create-personal-mob-area $self->{name} failed";
970 $self->perm_initialize;
973 sub clone {
974 my $self = shift;
976 unlink ($self->_clonefail_path()); # Ignore EEXIST error
977 unlink ($self->_clonelog_path()); # Ignore EEXIST error
979 use IO::Socket;
980 my $sock = IO::Socket::UNIX->new($Girocco::Config::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
981 select((select($sock),$|=1)[0]);
982 $sock->print("clone ".$self->{name}."\n");
983 # Just ignore reply, we are going to succeed anyway and the I/O
984 # would apparently get quite hairy.
985 $sock->flush();
986 sleep 2; # *cough*
987 $sock->close();
990 sub _update_users {
991 my $self = shift;
993 $self->_group_update;
994 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users} } $self->{users};
995 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users} } $self->{orig_users};
996 $self->perm_user_add($_, Girocco::User::resolve_uid($_)) foreach (@users_add);
997 $self->perm_user_del($_, Girocco::User::resolve_uid($_)) foreach (@users_del);
1000 sub update {
1001 my $self = shift;
1003 $self->_properties_save;
1004 $self->_update_users;
1006 if (exists($self->{tags_to_delete})) {
1007 $self->delete_ctag($_) foreach(@{$self->{tags_to_delete}});
1010 $self->set_HEAD($self->{HEAD}) unless $self->{orig_HEAD} eq $self->{HEAD};
1012 $self->_update_index if $self->{email} ne $self->{orig_email};
1013 $self->{orig_email} = $self->{email};
1014 $self->_set_changed;
1019 sub update_password {
1020 my $self = shift;
1021 my ($pwd) = @_;
1023 $self->{crypt} = scrypt_sha1($pwd);
1024 $self->_group_update;
1027 # You can explicitly do this just on a ghost() repository too.
1028 sub delete {
1029 my $self = shift;
1031 if (-d $self->{path}) {
1032 system('rm', '-rf', $self->{path}) == 0
1033 or die "rm -rf $self->{path} failed: $?";
1035 # attempt to clean up any empty fork directories by removing them
1036 my @pelems = split('/', $self->{name});
1037 while (@pelems > 1) {
1038 pop @pelems;
1039 # okay to fail
1040 rmdir join('/', $Girocco::Config::reporoot, @pelems) or last;
1042 $self->_group_remove;
1043 $self->_update_index;
1044 $self->_set_forkchange(1);
1049 sub _contains_files {
1050 my $dir = shift;
1051 (-d $dir) or return 0;
1052 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
1053 while (my $entry = readdir($dh)) {
1054 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1055 closedir($dh), return 1
1056 if -f "$dir/$entry" ||
1057 -d "$dir/$entry" && _contains_files("$dir/$entry");
1059 closedir($dh);
1060 return 0;
1063 sub has_forks {
1064 my $self = shift;
1066 return _contains_files($Girocco::Config::reporoot.'/'.$self->{name});
1069 # Returns an array of 0 or more array refs, one for each bundle:
1070 # ->[0]: bundle creation time (seconds since epoch)
1071 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1072 # ->[2]: bundle size in bytes
1073 sub bundles {
1074 my $self = shift;
1075 use Time::Local;
1077 return @{$self->{bundles}} if ref($self->{bundles}) eq 'ARRAY';
1078 my @blist = ();
1079 if (-d $self->{path}.'/bundles') {{
1080 my $prefix = $self->{name};
1081 $prefix =~ s|^.*[^/]/([^/]+)$|$1|;
1082 opendir(my $dh, $self->{path}.'/bundles') or last;
1083 while (my $bfile = readdir($dh)) {
1084 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1085 my $ctime = eval {timegm(
1086 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1087 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4)-1900)};
1088 next unless $ctime;
1089 open(my $bh, '<', $self->{path}.'/bundles/'.$bfile) or next;
1090 my $f1 = <$bh>;
1091 my $f2 = <$bh>;
1092 $f1 = $self->{path}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m|^/|;
1093 $f2 = $self->{path}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m|^/|;
1094 close($bh);
1095 next unless $f1 && $f2 && $f1 ne $f2;
1096 chomp $f1;
1097 chomp $f2;
1098 next unless -e $f1 && -e $f2;
1099 my $s1 = -s $f1 || 0;
1100 my $s2 = -s $f2 || 0;
1101 next unless $s1 || $s2;
1102 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1104 closedir($dh);
1106 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1107 my %seen = ();
1108 my @result = ();
1109 foreach my $bndl (@blist) {
1110 next if $seen{$bndl->[1]};
1111 $seen{$bndl->[1]} = 1;
1112 push(@result, $bndl);
1114 $self->{bundles} = \@result;
1115 return @result;
1118 sub has_alternates {
1119 my $self = shift;
1120 return -s $self->{path}.'/objects/info/alternates' ? 1 : 0;
1123 sub has_bundle {
1124 my $self = shift;
1126 return scalar($self->bundles);
1129 # returns true if any of the notify fields are non-empty
1130 sub has_notify {
1131 my $self = shift;
1132 # We do not ckeck notifycia since it's defunct
1133 return $self->{'notifymail'} || $self->{'notifytag'} || $self->{'notifyjson'};
1136 sub is_empty {
1137 # A project is considered empty if the git repository does not
1138 # have any refs. This means packed-refs does not exist or is
1139 # empty or only has lines starting with '#' AND there are no
1140 # files in the refs subdirectory hierarchy (no matter how deep).
1142 my $self = shift;
1144 (-d $self->{path}) or return 0;
1145 if (-e $self->{path}.'/packed-refs') {
1146 open(my $pr, '<', $self->{path}.'/packed-refs')
1147 or die "open $self->{path}./packed-refs failed: $!";
1148 my $foundref = 0;
1149 while (my $ref = <$pr>) {
1150 next if $ref =~ /^#/;
1151 $foundref = 1;
1152 last;
1154 close($pr);
1155 return 0 if $foundref;
1157 (-d $self->{path}.'/refs') or return 1;
1158 return !_contains_files($self->{path}.'/refs');
1161 # returns array:
1162 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1163 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1164 # Both values (if not undef) are seconds since epoch
1165 # Result only considers lastgc and min_gc_interval nothing else
1166 sub next_gc {
1167 my $self = shift;
1168 my $lastgcepoch = parse_any_date($self->{lastgc});
1169 return (undef, undef) unless defined $lastgcepoch;
1170 return ($lastgcepoch + $Girocco::Config::min_gc_interval,
1171 int($lastgcepoch + 1.25 * $Girocco::Config::min_gc_interval +
1172 $Girocco::Config::min_mirror_interval));
1175 # returns boolean (0 or 1)
1176 # Attempts to determine whether or not a gc (and corresponding build
1177 # of a .bitmap/.bndl file) will actually take place at the next_gc
1178 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1179 # end up being built depends on whether or not the local object graph
1180 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1181 # is not possible because the object graph will be incomplete,
1182 # but it *is* possible that even though the repository has_alternates,
1183 # it does not actually borrow any objects so a .bitmap/.bndl will build
1184 # in spite of the presence of alternates -- but this is expected to be rare.
1185 # The result is a best guess and false return value is not an absolute
1186 # guarantee that gc will not take place at the next interval, but it probably
1187 # will not if nothing changes in the meantime.
1188 sub needs_gc {
1189 my $self = shift;
1190 my $lgc = parse_any_date($self->{lastgc});
1191 my $lrecv = parse_any_date($self->{lastreceive});
1192 my $lpgc = parse_any_date($self->{lastparentgc});
1193 return 1 unless defined($lgc) && defined($lrecv);
1194 if ($self->has_alternates) {
1195 return 1 unless defined($lpgc);
1196 return 1 unless $lpgc < $lgc;
1198 return 1 unless $lrecv < $lgc;
1199 # We don't try running any "is_dirty" check, so if somehow the
1200 # repository became dirty without updating lastreceive we might
1201 # incorrectly return false instead of true.
1202 return 0;
1205 sub delete_ctag {
1206 my $self = shift;
1207 my ($ctag) = @_;
1209 # sanity check, disallow filenames starting with . .. or /
1210 unlink($self->{path}.'/ctags/'.$ctag) if($ctag !~ m|^(\.\.?)/|);
1213 sub get_ctag_names {
1214 my $self = shift;
1215 my @ctags = ();
1216 opendir(my $dh, $self->{path}.'/ctags')
1217 or return @ctags;
1218 @ctags = grep { -f "$self->{path}/ctags/$_" } readdir($dh);
1219 closedir($dh);
1220 return sort({lc($a) cmp lc($b)} @ctags);
1223 sub get_heads {
1224 my $self = shift;
1225 my $fh;
1226 my $heads = get_git("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1227 defined($heads) or $heads = '';
1228 chomp $heads;
1229 my @res = ();
1230 foreach (split(/\n/, $heads)) {
1231 chomp;
1232 next if !m#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1233 push @res, $1;
1235 push(@res, $self->{orig_HEAD}) if !@res && defined($self->{orig_HEAD}) && $self->{orig_HEAD} ne '';
1236 @res;
1239 sub get_HEAD {
1240 my $self = shift;
1241 my $HEAD = get_git("--git-dir=$self->{path}", 'symbolic-ref', 'HEAD');
1242 defined($HEAD) or $HEAD = '';
1243 chomp $HEAD;
1244 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
1245 return $1;
1248 sub set_HEAD {
1249 my $self = shift;
1250 my $newHEAD = shift;
1251 # Cursory checks only -- if you want to break your HEAD, be my guest
1252 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
1253 die "grossly invalid new HEAD: $newHEAD";
1255 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', "refs/heads/$newHEAD");
1256 die "could not set HEAD" if ($? >> 8);
1257 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob'
1258 or system('cp', '-p', '-f', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1261 sub gen_auth {
1262 my $self = shift;
1263 my ($type) = @_;
1264 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
1266 $self->{authtype} = $type;
1268 no warnings;
1269 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1271 my $expire = time + 24 * 3600;
1272 my $propval = "# ${type}AUTH $self->{auth} $expire";
1273 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', 'gitweb.repoauth', $propval);
1274 $self->{auth};
1277 sub del_auth {
1278 my $self = shift;
1280 delete $self->{auth};
1281 delete $self->{authtype};
1282 system($Girocco::Config::git_bin, '--git-dir='.$self->{path}, 'config', '--unset', 'gitweb.repoauth');
1285 sub remove_user {
1286 my $self = shift;
1287 my ($username) = @_;
1289 my $before_count = @{$self->{users}};
1290 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1291 return @{$self->{users}} != $before_count;
1294 ### static methods
1296 sub get_forkee_name {
1297 local $_ = $_[0];
1298 (m#^(.*)/.*?$#)[0]; #
1301 sub get_forkee_path {
1302 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1303 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git';
1304 -d $forkee ? $forkee : '';
1307 # Ultimately the full project/fork name could end up being part of a Git ref name
1308 # when a project's forks are combined into one giant repository for efficiency.
1309 # That means that the project/fork name must satisfy the Git ref name requirements:
1311 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1312 # 2. The character with an ASCII value of 0x7F is not allowed
1313 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1314 # 4. The character '/' is a separator and is not allowed within a name
1315 # 5. The name may not start with '.' or end with '.'
1316 # 6. The name may not end with '.lock'
1317 # 7. The name may not contain the '..' sequence
1318 # 8. The name may not contain the '@{' sequence
1319 # 9. If multiple components are used (separated by '/'), no empty '' components
1321 # We also prohibit a trailing '.git' on any path component and futher restrict
1322 # the allowed characters to alphanumeric and [+._-] where names must start with
1323 # an alphanumeric.
1325 sub _valid_name_characters {
1326 local $_ = $_[0];
1327 (not m#^[/+._-]#)
1328 and (not m#//#)
1329 and (not m#\.\.#)
1330 and (not m#/[+._-]#)
1331 and (not m#\./#)
1332 and (not m#\.$#)
1333 and (not m#\.git/#i)
1334 and (not m#\.git$#i)
1335 and (not m#\.idx/#i)
1336 and (not m#\.idx$#i)
1337 and (not m#\.lock/#i)
1338 and (not m#\.lock$#i)
1339 and (not m#\.pack/#i)
1340 and (not m#\.pack$#i)
1341 and (not m#\.bundle/#i)
1342 and (not m#\.bundle$#i)
1343 and (not m#/$#)
1344 and (not m/^[a-fA-F0-9]{38}$/)
1345 and m#^[a-zA-Z0-9/+._-]+$#
1346 and !has_reserved_suffix($_, $_[1], $_[2]);
1349 # $_[0] => prospective project name (WITHOUT trailing .git)
1350 # $_[1] => true to allow orphans (i.e. two-or-more-level-deep projects without a parent)
1351 # (the directory in which the orphan will be created must, however, already exist)
1352 # $_[2] => true to allow orphans w/o needed directory if $_[1] also true (like mkdir -p)
1353 sub valid_name {
1354 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1355 local $_ = $_[0];
1356 _valid_name_characters($_) and not exists($reservedprojectnames{lc($_)})
1357 and @{[m#/#g]} <= 5 # maximum fork depth is 5
1358 and ((not m#/#) or -d get_forkee_path($_) or ($_[1] and ($_[2] or -d $Girocco::Config::reporoot.'/'.get_forkee_name($_))))
1359 and (! -f $Girocco::Config::reporoot."/$_.git");
1362 # It's possible that some forks have been kept but the forkee is gone.
1363 # In this case the standard valid_name check is too strict.
1364 sub does_exist {
1365 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
1366 my ($name, $nodie) = @_;
1367 my $okay = (
1368 _valid_name_characters($name, $Girocco::Config::reporoot, ".git")
1369 and ((not $name =~ m#/#)
1370 or -d get_forkee_path($name)
1371 or -d $Girocco::Config::reporoot.'/'.get_forkee_name($name)));
1372 (!$okay && $nodie) and return undef;
1373 !$okay and die "tried to query for project with invalid name $name!";
1374 (-d $Girocco::Config::reporoot."/$name.git");
1377 sub get_full_list {
1378 open my $fd, '<', jailed_file("/etc/group") or die "getting project list failed: $!";
1379 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ? $1 : ()} <$fd>;
1380 close $fd;
1381 @projects;