1 package Girocco
::Project
;
10 use Girocco
::HashUtil
;
11 use Girocco
::ProjPerm
;
13 use base
('Girocco::ProjPerm::'.$Girocco::Config
::permission_control
); # mwahaha
28 require Digest
::SHA
::PurePerl
;
29 Digest
::SHA
::PurePerl
->import(
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, < 8 KiB)<br />leave blank for automatic</span>',
42 'README', 'textarea', 'Enter only “<!-- comments -->” '.
43 'to completely suppress any README'],
44 notifymail
=> ['Commit notify – 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 “Commit notify” email when showing new revisions'],
49 summaryonly
=> ['Summaries only', 'summaryonly', 'checkbox',
50 'suppress patch/diff output in “Commit notify” email when showing new revisions'],
51 notifytag
=> ['Tag notify – mail to', 'notifytag', 'text',
52 'comma separated address list – if not empty, tag '.
53 'notifications are sent here INSTEAD of to '.
54 '“Commit notify – mail to” address(es)'],
55 notifyjson
=> ['Commit notify – '.
56 '<a title="'.html_esc
('single field name is “payload”', 1).'" href="'.
57 'https://developer.github.com/v3/activity/events/types/#pushevent'.
58 '">POST JSON</a> at', 'notifyjson', 'text'],
59 notifycia
=> ['Commit notify – <a href="http://cia.vc/doc/">CIA project</a> name',
60 'notifycia', 'text', 'CIA is defunct – this value is ignored'],
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) {
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 # Otherwise it's a project file name to be loaded
78 # %propmapro entries are loaded but never written
83 desc
=> 'description',
84 README
=> 'README.html',
86 notifymail
=> '%hooks.mailinglist',
87 notifytag
=> '%hooks.announcelist',
88 notifyjson
=> '%hooks.jsonurl',
89 notifycia
=> '%hooks.cianame',
93 lastchange
=> ':lastchange',
94 lastactivity
=> 'info/lastactivity',
96 lastreceive
=> ':lastreceive',
97 lastparentgc
=> ':lastparentgc',
98 lastrefresh
=> ':lastrefresh',
99 creationtime
=> '%girocco.creationtime',
100 reposizek
=> '%girocco.reposizek',
101 origurl
=> ':baseurl',
104 # Projects with any of these names will be disallowed to avoid possible
105 # collisions with cgi script paths or chroot paths
106 # NOTE: names are checked after using lc on them, so all entries MUST be lowercase
107 our %reservedprojectnames = (
108 admin
=> 1, # /admin/ links
109 alternates
=> 1, # .git/objects/info/alternates
110 b
=> 1, # /b/ -> bundle.cgi
111 blog
=> 1, # /blog/ links
112 c
=> 1, # /c/ -> cgit
113 'git-receive-pack' => 1, # smart HTTP
114 'git-upload-archive' => 1, # smart HTTP
115 'git-upload-pack' => 1, # smart HTTP
116 h
=> 1, # /h/ -> html.cgi
117 head
=> 1, # .git/HEAD
118 'http-alternates' => 1, # .git/objects/info/http-alternates
119 info
=> 1, # .git/info
120 objects
=> 1, # .git/objects
121 packs
=> 1, # .git/objects/info/packs
122 r
=> 1, # /r/ -> git http
123 refs
=> 1, # .git/refs
124 w
=> 1, # /w/ -> gitweb
125 wiki
=> 1, # /wiki/ links
126 srv
=> 1, # /srv/git/ -> chroot ssh git repositories
131 system("$Girocco::Config::basedir/gitweb/genindex.sh", $self->{name
});
134 sub _readlocalconfigfile
{
136 my $undefonerr = shift || 0;
137 delete $self->{configfilehash
};
138 my $configfile = get_git
("--git-dir=$self->{path}",
139 'config', '--list', '--local', '--null');
141 defined($configfile) || $undefonerr or $result = 0, $configfile = '';
142 return undef unless defined($configfile);
143 my %config = map({split(/\n/, $_=~/\n/?
$_:"$_\ntrue", 2)} split(/\x00/, $configfile));
144 $self->{configfilehash
} = \
%config;
148 # @_[0]: argument to convert to boolean result (0 or 1)
149 # @_[1]: value to use if argument is undef (default is 0)
152 my ($val, $def) = @_;
153 defined($def) or $def = 0;
154 defined($val) or $val = $def;
157 return 0 if $val eq '' || $val eq 'false' || $val eq 'off' || $val eq 'no' || $val =~ /^0+$/;
164 $self->{path
}.'/'.$name;
170 my $pname = $propmap{$name};
171 $pname = $propmapro{$name} unless $pname;
172 $pname or die "unknown property: $name";
173 if ($pname =~ /^([:%])(.*)$/) {
174 my ($where, $pname) = ($1,lc($2));
175 $self->_readlocalconfigfile
176 unless ref($self->{configfilehash
}) eq 'HASH';
177 my $val = $where eq ':' ?
178 $self->{configfilehash
}->{"gitweb.$pname"} :
179 $self->{configfilehash
}->{$pname};
180 defined($val) or $val = '';
185 open my $p, '<', $self->_property_path($pname) or return undef;
188 my $value = join('', @value); chomp $value;
194 my ($name, $value) = @_;
195 my $pname = $propmap{$name};
196 $pname or die "unknown property: $name";
198 if ($pname =~ s/^://) {
199 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', "gitweb.$pname", $value);
201 } elsif ($pname =~ s/^%//) {
202 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', $pname, $value);
206 my $P = lock_file
($self->_property_path($pname));
208 $value ne '' and print $P "$value\n";
210 unlock_file
($self->_property_path($pname));
213 sub _cleanup_readme
{
215 defined($self->{README
}) or $self->{README
} = '';
216 $self->{README
} =~ s/\r\n?/\n/gs;
217 $self->{README
} =~ s/^\s+//s;
218 $self->{README
} =~ s/\s+$//s;
219 $self->{README
} eq '' or $self->{README
} .= "\n";
224 return 0 unless defined($self->{README
}) && $self->{README
} ne '';
225 my $test = '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>';
226 $test .= $self->{README
};
227 $test .= '</div></body></html>';
228 my ($code, $errors) = capture_command
(2, $test, 'xmllint', '--nonet',
229 '--noout', '--nowarning', '-');
230 return 0 unless $code;
233 for my $line (split(/\n+/, $errors)) {
234 $line = html_esc
($line);
235 $line =~ s/ /\ /gs;
236 ++$cnt, $line = 'README'.$1 if $line =~ /^-(:\d+:.*)$/;
237 push @errs, '<tt>' . $line . '</tt>';
239 return ($cnt, join("<br />\n", @errs));
242 sub _properties_load
{
244 foreach my $prop (keys %propmap) {
245 $self->{$prop} = $self->_property_fget($prop);
247 foreach my $prop (keys %propmapro) {
248 $self->{$prop} = $self->_property_fget($prop);
250 $self->_readlocalconfigfile
251 unless ref($self->{configfilehash
}) eq 'HASH';
252 $self->{cleanmirror
} = _boolval
($self->{configfilehash
}->{'girocco.cleanmirror'}, 0);
253 $self->{statusupdates
} = _boolval
($self->{configfilehash
}->{'gitweb.statusupdates'}, 1);
254 $self->{reverseorder
} = _boolval
($self->{configfilehash
}->{'hooks.reverseorder'}, 0);
255 $self->{summaryonly
} = _boolval
($self->{configfilehash
}->{'hooks.summaryonly'}, 0);
256 delete $self->{auth
};
257 my $val = $self->{configfilehash
}->{'gitweb.repoauth'};
258 defined($val) or $val = '';
260 if ($val =~ /^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
262 if (time < $expire) {
263 $self->{authtype
} = $1;
267 $self->_cleanup_readme;
268 delete $self->{configfilehash
};
271 sub _properties_save
{
274 foreach my $prop (keys %propmap) {
275 $self->_property_fput($prop, $self->{$prop});
277 $self->{cleanmirror
} = 0
278 unless defined($self->{cleanmirror
}) && $self->{cleanmirror
} =~ /^\d+$/;
279 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', '--bool',
280 "girocco.cleanmirror", $self->{cleanmirror
});
281 $self->{statusupdates
} = 1
282 unless defined($self->{statusupdates
}) && $self->{statusupdates
} =~ /^\d+$/;
283 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', '--bool',
284 "gitweb.statusupdates", $self->{statusupdates
});
285 $self->{reverseorder
} = 0
286 unless defined($self->{reverseorder
}) && $self->{reverseorder
} =~ /^\d+$/;
287 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', '--bool',
288 "hooks.reverseorder", $self->{reverseorder
});
289 $self->{summaryonly
} = 0
290 unless defined($self->{summaryonly
}) && $self->{summaryonly
} =~ /^\d+$/;
291 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', '--bool',
292 "hooks.summaryonly", $self->{summaryonly
});
293 if (defined($self->{origurl
}) && defined($self->{url
}) &&
294 $self->{origurl
} ne $self->{url
} && -e
$self->_property_path(".banged")) {
295 if (open($fd, '>', $self->_property_path(".bangagain"))) {
297 chmod(0664, $self->_property_path(".bangagain"));
304 $self->_property_path('.nofetch');
310 my $nf = $self->_nofetch_path;
312 open my $x, '>', $nf or die "nofetch failed: $!";
315 unlink $nf or die "yesfetch failed: $!";
321 $self->_property_path('.gc_in_progress');
326 $self->_property_path('.clonelog');
329 sub _clonefail_path
{
331 $self->_property_path('.clone_failed');
336 $self->_property_path('.clone_in_progress');
342 my $np = $self->_clonep_path;
344 open my $x, '>', $np or die "clonep failed: $!";
347 unlink $np or die "clonef failed: $!";
350 sub _alternates_setup
{
352 return unless $self->{name
} =~ m
#/#;
353 my $forkee_name = get_forkee_name
($self->{name
});
354 my $forkee_path = get_forkee_path
($self->{name
});
355 return unless -d
$forkee_path;
356 mkdir $self->{path
}.'/refs'; chmod 02775, $self->{path
}.'/refs';
357 mkdir $self->{path
}.'/objects'; chmod 02775, $self->{path
}.'/objects';
358 mkdir $self->{path
}.'/objects/info'; chmod 02775, $self->{path
}.'/objects/info';
360 # We set up both alternates and http_alternates since we cannot use
361 # relative path in alternates - that doesn't work recursively.
363 my $filename = $self->{path
}.'/objects/info/alternates';
364 open my $x, '>', $filename or die "alternates failed: $!";
365 print $x "$forkee_path/objects\n";
367 chmod 0664, $filename or warn "cannot chmod $filename: $!";
369 if ($Girocco::Config
::httppullurl
) {
370 $filename = $self->{path
}.'/objects/info/http-alternates';
371 open my $x, '>', $filename or die "http-alternates failed: $!";
372 my $upfork = $forkee_name;
373 do { print $x "$Girocco::Config::httppullurl/$upfork.git/objects\n"; } while ($upfork =~ s
#/?.+?$## and $upfork); #
375 chmod 0664, $filename or warn "cannot chmod $filename: $!";
378 # copy lastactivity from the parent project
379 if (open $x, '<', $forkee_path.'/info/lastactivity') {{
382 last unless $activity;
383 open $x, '>', $self->{path
}.'/info/lastactivity' or last;
387 $self->{'lastactivity'} = $activity;
390 # copy refs from parent project
392 open(SAVEOUT
, ">&STDOUT") || die "couldn't dup STDOUT: $!";
393 my $result = open(STDOUT
, '>', "$self->{path}/packed-refs");
396 open(STDOUT
, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
397 close(SAVEOUT
) or die "couldn't close SAVEOUT: $!";
398 die "could not write fork's packed-refs file: $resultstr";
400 system($Girocco::Config
::git_bin
, "--git-dir=$forkee_path", 'for-each-ref', '--format=%(objectname) %(refname)');
401 $result = close(STDOUT
);
403 open(STDOUT
, ">&SAVEOUT") || die "couldn't dup SAVEOUT to STDOUT: $!";
404 close(SAVEOUT
) or die "couldn't close SAVEOUT: $!";
405 $result or die "could not close fork's packed-refs file: $resultstr";
406 unlink("$self->{path}/.delaygc") if -s
"$self->{path}/packed-refs";
409 my $HEAD = get_git
("--git-dir=$forkee_path", 'symbolic-ref', 'HEAD');
410 defined($HEAD) && $HEAD =~ m
,^refs
/heads
/., or $HEAD = 'refs/heads/master';
412 system($Girocco::Config
::git_bin
, "--git-dir=$self->{path}", 'symbolic-ref', 'HEAD', $HEAD);
413 chmod 0664, "$self->{path}/packed-refs", "$self->{path}/HEAD";
419 open $fd, '>', "$self->{path}/htmlcache/changed" and close $fd;
422 sub _set_forkchange
{
424 my $changedtoo = shift;
425 return unless $self->{name
} =~ m
#/#;
426 my $forkee_path = get_forkee_path
($self->{name
});
427 return unless -d
$forkee_path;
428 # mark forkee as changed
430 open $fd, '>', $forkee_path.'/htmlcache/changed' and close $fd if $changedtoo;
431 open $fd, '>', $forkee_path.'/htmlcache/forkchange' and close $fd;
432 return if -e
$forkee_path.'/htmlcache/summary.forkchange';
433 open $fd, '>', $forkee_path.'/htmlcache/summary.forkchange' and close $fd;
438 my $perms = $Girocco::Config
::permission_control
eq 'Hooks' ?
02777 : 02775;
439 mkdir $self->{path
}.'/ctags'; chmod $perms, $self->{path
}.'/ctags';
445 $xtra .= join(',', @
{$self->{users
}});
446 filedb_atomic_append
(jailed_file
('/etc/group'),
447 join(':', $self->{name
}, $self->{crypt}, '\i', $xtra));
452 my $xtra = join(',', @
{$self->{users
}});
453 filedb_atomic_edit
(jailed_file
('/etc/group'),
457 if ($self->{name
} eq (split /:/)[0]) {
458 # preserve readonly flag
459 s/::([^:]*)$/:$1/ and $xtra = ":$xtra";
460 return join(':', $self->{name
}, $self->{crypt}, $self->{gid
}, $xtra)."\n";
470 filedb_atomic_edit
(jailed_file
('/etc/group'),
472 $self->{name
} ne (split /:/)[0] and return $_;
480 $self->{path
}.'/hooks/'.$name;
486 my $hooksdir = $self->{path
}.'/hooks';
487 my $oldmask = umask();
488 umask($oldmask & ~0070);
489 -d
$hooksdir or mkdir $hooksdir or
490 die "hooks directory does not exist and unable to create it for project " . $self->{name
} . ": $!";
492 open my $src, '<', "$Girocco::Config::basedir/hooks/$name" or die "cannot open hook $name: $!";
493 open my $dst, '>', $self->_hook_path($name) or die "cannot open hook $name for writing: $!";
494 while (<$src>) { print $dst $_; }
497 chmod 0775, $self->_hook_path($name) or die "cannot chmod hook $name: $!";
502 foreach my $hook ('pre-receive', 'post-receive', 'update') {
503 $self->_hook_install($hook);
507 # private constructor, do not use
510 my ($name, $base_path, $path) = @_;
511 does_exist
($name,1) || valid_name
($name) or die "refusing to create project with invalid name ($name)!";
512 $path ||= "$base_path/$name.git";
513 my $proj = { name
=> $name, base_path
=> $base_path, path
=> $path };
518 # public constructor #0
519 # creates a virtual project not connected to disk image
520 # you can conjure() it later to disk
523 my ($name, $mirror) = @_;
524 my $self = $class->_new($name, $Girocco::Config
::reporoot
);
526 $self->{mirror
} = $mirror;
527 $self->{email
} = $self->{orig_email
} = '';
531 # public constructor #1
534 my $name = shift || '';
536 open my $fd, '<', jailed_file
("/etc/group") or die "project load failed: $!";
537 my $r = qr/^\Q$name\E:/;
538 foreach (grep /$r/, <$fd>) {
541 my $self = $class->_new($name, $Girocco::Config
::reporoot
);
542 (-d
$self->{path
} && $self->_readlocalconfigfile(1))
543 or die "invalid path (".$self->{path
}.") for project ".$self->{name
};
546 (undef, $self->{crypt}, $self->{gid
}, $ulist) = split /:/;
548 $self->{users
} = [split /,/, $ulist];
549 $self->{HEAD
} = $self->get_HEAD;
550 $self->{orig_HEAD
} = $self->{HEAD
};
551 $self->{orig_users
} = [@
{$self->{users
}}];
552 $self->{mirror
} = ! -e
$self->_nofetch_path;
553 $self->{gc_in_progress
} = -e
$self->_gcp_path;
554 $self->{clone_in_progress
} = -e
$self->_clonep_path;
555 $self->{clone_logged
} = -e
$self->_clonelog_path;
556 $self->{clone_failed
} = -e
$self->_clonefail_path;
557 $self->{ccrypt
} = $self->{crypt};
559 $self->_properties_load;
560 $self->{orig_email
} = $self->{email
};
561 $self->{loaded
} = 1; # indicates self was loaded from etc/group file
569 # $proj may not be in sane state if this returns false!
570 # fields listed in %$metadata_fields that are NOT also
571 # in @Girocco::Config::project_fields are totally ignored!
575 my $cgi = $gcgi->cgi;
576 my %allowedfields = map({$_ => 1} @Girocco::Config
::project_fields
);
577 my $field_enabled = sub {
578 !exists($metadata_fields->{$_[0]}) || exists($allowedfields{$_[0]})};
580 my $pwd = $cgi->param('pwd');
581 my $pwd2 = $cgi->param('pwd2');
582 # in case passwords are disabled
583 defined($pwd) or $pwd = ''; defined($pwd2) or $pwd = '';
584 if ($Girocco::Config
::project_passwords
and not $self->{crypt} and $pwd eq '' and $pwd2 eq '') {
585 $gcgi->err("Empty passwords are not permitted.");
587 if ($pwd ne '' or not $self->{crypt}) {
588 $self->{crypt} = scrypt_sha1
($pwd);
590 if (($pwd ne '' || $pwd2 ne '') and $pwd ne $pwd2) {
591 $gcgi->err("Our high-paid security consultants have determined that the admin passwords you have entered do not match each other.");
594 $self->{cpwd
} = $cgi->param('cpwd');
596 my ($forkee,$project) = ($self->{name
} =~ m
#^(.*/)?([^/]+)$#);
597 my $newtype = $forkee ?
'fork' : 'project';
598 length($project) <= 64
599 or $gcgi->err("The $newtype name is longer than 64 characters. Do you really need that much?");
601 if ($Girocco::Config
::project_owners
eq 'email') {
602 $self->{email
} = $gcgi->wparam('email');
603 valid_email
($self->{email
})
604 or $gcgi->err("Your email sure looks weird...?");
605 length($self->{email
}) <= 96
606 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
609 # No setting the url unless we're either new or an existing mirror!
610 unless ($self->{loaded
} && !$self->{mirror
}) {
611 $self->{url
} = $gcgi->wparam('url') ;
612 if ($field_enabled->('cleanmirror')) {
613 $self->{cleanmirror
} = $gcgi->wparam('cleanmirror') || 0;
616 # Always validate the url if we're an existing mirror
617 if ((defined($self->{url
}) && $self->{url
} ne '') || ($self->{loaded
} && $self->{mirror
})) {{
618 # Always allow the url to be left unchanged without validation when editing
619 last if $self->{loaded
} && defined($self->{origurl
}) && defined($self->{url
}) && $self->{origurl
} eq $self->{url
};
620 valid_repo_url
($self->{url
})
621 or $gcgi->err("Invalid URL. Note that only HTTP and Git protocols are supported. If the URL contains funny characters, contact me.");
622 if ($Girocco::Config
::restrict_mirror_hosts
) {
623 my $mh = extract_url_hostname
($self->{url
});
625 or $gcgi->err("Invalid URL. Note that only DNS names are allowed, not IP addresses.");
626 !is_our_hostname
($mh)
627 or $gcgi->err("Invalid URL. Mirrors from this host are not allowed, please create a fork instead.");
631 if ($field_enabled->('desc')) {
632 $self->{desc
} = to_utf8
($gcgi->wparam('desc'), 1);
633 length($self->{desc
}) <= 1024
634 or $gcgi->err("<b>Short</b> description length > 1kb!");
637 if ($field_enabled->('README')) {
638 $self->{README
} = to_utf8
($gcgi->wparam('README'), 1);
639 $self->_cleanup_readme;
640 length($self->{README
}) <= 8192
641 or $gcgi->err("README length > 8kb!");
642 my ($cnt, $err) = (0);
643 ($cnt, $err) = $self->_lint_readme if $gcgi->ok && $Girocco::Config
::xmllint_readme
;
644 $gcgi->err($err), $gcgi->{err
} += $cnt-1 if $cnt;
647 if ($field_enabled->('hp')) {
648 $self->{hp
} = $gcgi->wparam('hp');
650 valid_web_url
($self->{hp
})
651 or $gcgi->err("Invalid homepage URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
655 # No mucking about with users unless we're a push project
656 if (($self->{loaded
} && !$self->{mirror
}) ||
657 (!$self->{loaded
} && (!defined($self->{url
}) || $self->{url
} eq ''))) {
660 foreach my $user ($cgi->multi_param('user')) {
661 if (!exists($users{$user})) {
663 push(@users, $user) if Girocco
::User
::does_exist
($user, 1);
666 $self->{users
} = \
@users;
669 # HEAD can only be set with editproj, NOT regproj (regproj sets it automatically)
670 # It may ALWAYS be set to what it was (even if there's no such refs/heads/...)
672 if (defined($self->{orig_HEAD
}) && $self->{orig_HEAD
} ne '' &&
673 defined($newhead = $cgi->param('HEAD')) && $newhead ne '') {
674 if ($newhead eq $self->{orig_HEAD
} ||
675 get_git
("--git-dir=$self->{path}", 'rev-parse', '--verify', '--quiet', 'refs/heads/'.$newhead)) {
676 $self->{HEAD
} = $newhead;
678 $gcgi->err("Invalid default branch (no such ref)");
682 # schedule deletion of tags (will be committed by update() after auth)
683 $self->{tags_to_delete
} = [$cgi->multi_param('tags')];
685 if ($field_enabled->('notifymail')) {
686 $self->{notifymail
} = $gcgi->wparam('notifymail');
687 if ($self->{notifymail
}) {
688 (valid_email_multi
($self->{notifymail
}) and length($self->{notifymail
}) <= 512)
689 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
691 if ($field_enabled->('reverseorder')) {
692 $self->{reverseorder
} = $gcgi->wparam('reverseorder') || 0;
694 if ($field_enabled->('summaryonly')) {
695 $self->{summaryonly
} = $gcgi->wparam('summaryonly') || 0;
699 if ($field_enabled->('notifytag')) {
700 $self->{notifytag
} = $gcgi->wparam('notifytag');
701 if ($self->{notifytag
}) {
702 (valid_email_multi
($self->{notifytag
}) and length($self->{notifytag
}) <= 512)
703 or $gcgi->err("Invalid notify e-mail address. Use mail,mail to specify multiple addresses; total length must not exceed 512 characters, however.");
707 if ($field_enabled->('notifyjson')) {
708 $self->{notifyjson
} = $gcgi->wparam('notifyjson');
709 if ($self->{notifyjson
}) {
710 valid_web_url
($self->{notifyjson
})
711 or $gcgi->err("Invalid JSON notify URL. Note that only HTTP protocol is supported. If the URL contains funny characters, contact me.");
715 if ($field_enabled->('notifycia')) {
716 $self->{notifycia
} = $gcgi->wparam('notifycia');
717 if ($self->{notifycia
}) {
718 $self->{notifycia
} =~ /^[a-zA-Z0-9._-]+$/
719 or $gcgi->err("Overly suspicious CIA notify project name. If it's actually valid, don't contact me, CIA is defunct.");
723 if ($cgi->param('setstatusupdates')) {
724 my $val = $gcgi->wparam('statusupdates') || '0';
725 $self->{statusupdates
} = $val ?
1 : 0;
728 not $gcgi->err_check;
734 name
=> $self->{name
},
735 email
=> $self->{email
},
737 cleanmirror
=> $self->{cleanmirror
},
738 desc
=> html_esc
($self->{desc
}),
739 README
=> html_esc
($self->{README
}),
741 users
=> $self->{users
},
742 notifymail
=> html_esc
($self->{notifymail
}),
743 reverseorder
=> $self->{reverseorder
},
744 summaryonly
=> $self->{summaryonly
},
745 notifytag
=> html_esc
($self->{notifytag
}),
746 notifyjson
=> html_esc
($self->{notifyjson
}),
747 notifycia
=> html_esc
($self->{notifycia
}),
751 # return true if $enc_passwd is a match for $plain_passwd
752 my $_check_passwd_match = sub {
753 my $enc_passwd = shift;
754 my $plain_passwd = shift;
755 defined($enc_passwd) or $enc_passwd = '';
756 defined($plain_passwd) or $plain_passwd = '';
757 # $enc_passwd may be crypt or crypt_sha1
758 if ($enc_passwd =~ m
(^\
$sha1\
$(\d
+)\
$([./0-9A-Za-z]{1,64})\$[./0-9A
-Za
-z
]{28}$)) {
759 # It's using sha1-crypt
760 return $enc_passwd eq crypt_sha1
($plain_passwd, $2, -(0+$1));
763 return $enc_passwd eq crypt($plain_passwd, $enc_passwd);
771 $self->{ccrypt
} or die "Can't authenticate against a project with no password";
772 defined($self->{cpwd
}) or $self->{cpwd
} = '';
773 unless ($_check_passwd_match->($self->{ccrypt
}, $self->{cpwd
})) {
774 $gcgi->err("Your admin password does not match!");
780 # return true if the password from the file is empty or consists of all the same
781 # character. However, if the project was NOT loaded from the group file
782 # (!self->{loaded}) then the password is never locked.
783 # This function does NOT check $Girocco::Config::project_passwords, the caller
784 # is responsible for doing so if desired. Same for $self->{email}.
785 sub is_password_locked
{
788 $self->{loaded
} or return 0;
789 my $testcrypt = $self->{ccrypt
}; # The value from the group file
790 defined($testcrypt) or $testcrypt = '';
791 $testcrypt ne '' or return 1; # No password at all
792 $testcrypt =~ /^(.)\1*$/ and return 1; # Bogus crypt value
793 return 0; # Not locked
797 use POSIX
qw(strftime);
802 $self->_mkdir_forkees;
805 mkdir($self->{path
}) or die "mkdir $self->{path} failed: $!";
806 if ($Girocco::Config
::owning_group
) {
807 $gid = scalar(getgrnam($Girocco::Config
::owning_group
));
808 chown(-1, $gid, $self->{path
}) or die "chgrp $gid $self->{path} failed: $!";
809 chmod(02775, $self->{path
}) or die "chmod 02775 $self->{path} failed: $!";
811 chmod(02777, $self->{path
}) or die "chmod 02777 $self->{path} failed: $!";
813 $ENV{'GIT_TEMPLATE_DIR'} = $Girocco::Config
::chroot.'/var/empty';
814 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'init', '--quiet', '--bare', '--shared='.$self->shared_mode()) == 0
815 or die "git init $self->{path} failed: $?";
816 # we don't need these two, remove them (they will normally be created empty) if they exist
817 rmdir $self->{path
}."/branches";
818 rmdir $self->{path
}."/remotes";
819 -d
$self->{path
}."/info" or mkdir $self->{path
}."/info"
820 or die "info directory does not exist and unable to create it: $!";
821 -d
$self->{path
}."/hooks" or mkdir $self->{path
}."/hooks"
822 or die "hooks directory does not exist and unable to create it: $!";
823 # clean out any kruft that may have come in from the initial template directory
824 foreach my $cleandir (qw(hooks info)) {
825 if (opendir my $hooksdir, $self->{path
}.'/'.$cleandir) {
826 unlink map "$self->{path}/$_", grep { $_ ne '.' && $_ ne '..' } readdir $hooksdir;
830 if ($Girocco::Config
::owning_group
) {
831 chown(-1, $gid, $self->{path
}."/hooks") or die "chgrp $gid $self->{path}/hooks failed: $!";
833 # hooks never world writable
834 chmod 02775, $self->{path
}."/hooks" or die "chmod 02775 $self->{path}/hooks failed: $!";
835 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'core.logAllRefUpdates', 'false') == 0
836 or die "disabling core.logAllRefUpdates failed: $?";
837 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'core.ignoreCase', 'false') == 0
838 or die "disabling core.ignoreCase failed: $?";
839 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'transfer.fsckObjects', 'true') == 0
840 or die "enabling transfer.fsckObjects failed: $?";
841 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'receive.denyNonFastForwards', 'false') == 0
842 or die "disabling receive.denyNonFastForwards failed: $?";
843 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'receive.denyDeleteCurrent', 'warn') == 0
844 or die "disabling receive.denyDeleteCurrent failed: $?";
845 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'gc.auto', '0') == 0
846 or die "disabling gc.auto failed: $?";
847 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'receive.autogc', '0') == 0
848 or die "disabling receive.autogc failed: $?";
849 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
850 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'receive.updateServerInfo', 'true') == 0
851 or die "enabling receive.updateServerInfo failed: $?";
852 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'repack.writeBitmaps', 'true') == 0
853 or die "enabling repack.writeBitmaps failed: $?";
854 $self->{creationtime
} = strftime
("%Y-%m-%dT%H:%M:%SZ", $S, $M, $H, $d, $m, $y, -1, -1, -1);
855 system($Girocco::Config
::git_bin
, '--git-dir='.$self->{path
}, 'config', 'girocco.creationtime', $self->{creationtime
}) == 0
856 or die "setting girocco.creationtime failed: $?";
857 -d
$self->{path
}."/htmlcache" or mkdir $self->{path
}."/htmlcache"
858 or die "htmlcache directory does not exist and unable to create it: $!";
859 -d
$self->{path
}."/bundles" or mkdir $self->{path
}."/bundles"
860 or die "bundles directory does not exist and unable to create it: $!";
861 foreach my $file (qw(info/lastactivity .delaygc)) {
862 if (open $fd, '>', $self->{path
}."/".$file) {
864 chmod 0664, $self->{path
}."/".$file;
868 # /info must have right permissions,
869 # and git init didn't do it for some reason.
870 # config must have correct permissions.
871 # and Git 2.1.0 - 2.2.1 incorrectly add +x for some reason.
872 # also make sure /refs, /objects and /htmlcache are correct too.
873 my ($dmode, $dmodestr, $fmode, $fmodestr);
874 if ($Girocco::Config
::owning_group
) {
875 ($dmode, $dmodestr) = (02775, '02775');
876 ($fmode, $fmodestr) = (0664, '0664');
878 ($dmode, $dmodestr) = (02777, '02777');
879 ($fmode, $fmodestr) = (0666, '0666');
881 foreach my $dir (qw(info refs objects htmlcache bundles)) {
882 chmod($dmode, $self->{path
}."/$dir") or die "chmod $dmodestr $self->{path}/$dir failed: $!";
884 foreach my $file (qw(config)) {
885 chmod($fmode, $self->{path
}."/$file") or die "chmod $fmodestr $self->{path}/$file failed: $!";
887 # these ones are probably not strictly required but are nice to have
888 foreach my $dir (qw(refs/heads refs/tags objects/info objects/pack)) {
889 -d
$self->{path
}."/$dir" or mkdir $self->{path
}."/$dir";
890 chmod($dmode, $self->{path
}."/$dir");
893 $self->_properties_save;
894 $self->_alternates_setup;
896 $self->_group_remove;
897 $self->_group_add($pushers);
898 $self->_hooks_install;
899 $self->_update_index;
901 $self->_set_forkchange(1);
909 $self->perm_initialize;
917 if ($Girocco::Config
::mob
&& $Girocco::Config
::mob
eq "mob") {
918 system("$Girocco::Config::basedir/bin/create-personal-mob-area", $self->{name
}) == 0
919 or die "create-personal-mob-area $self->{name} failed";
921 $self->perm_initialize;
927 unlink ($self->_clonefail_path()); # Ignore EEXIST error
928 unlink ($self->_clonelog_path()); # Ignore EEXIST error
931 my $sock = IO
::Socket
::UNIX
->new($Girocco::Config
::chroot.'/etc/taskd.socket') or die "cannot connect to taskd.socket: $!";
932 select((select($sock),$|=1)[0]);
933 $sock->print("clone ".$self->{name
}."\n");
934 # Just ignore reply, we are going to succeed anyway and the I/O
935 # would apparently get quite hairy.
944 $self->_properties_save;
945 $self->_group_update;
947 if (exists($self->{tags_to_delete
})) {
948 $self->delete_ctag($_) foreach(@
{$self->{tags_to_delete
}});
951 $self->set_HEAD($self->{HEAD
}) unless $self->{orig_HEAD
} eq $self->{HEAD
};
953 my @users_add = grep { $a = $_; not scalar grep { $a eq $_ } $self->{orig_users
} } $self->{users
};
954 my @users_del = grep { $a = $_; not scalar grep { $a eq $_ } $self->{users
} } $self->{orig_users
};
955 $self->perm_user_add($_, Girocco
::User
::resolve_uid
($_)) foreach (@users_add);
956 $self->perm_user_del($_, Girocco
::User
::resolve_uid
($_)) foreach (@users_del);
958 $self->_update_index if $self->{email
} ne $self->{orig_email
};
959 $self->{orig_email
} = $self->{email
};
965 sub update_password
{
969 $self->{crypt} = scrypt_sha1
($pwd);
970 $self->_group_update;
973 # You can explicitly do this just on a ghost() repository too.
977 if (-d
$self->{path
}) {
978 system('rm', '-rf', $self->{path
}) == 0
979 or die "rm -rf $self->{path} failed: $?";
981 # attempt to clean up any empty fork directories by removing them
982 my @pelems = split('/', $self->{name
});
983 while (@pelems > 1) {
986 rmdir join('/', $Girocco::Config
::reporoot
, @pelems) or last;
988 $self->_group_remove;
989 $self->_update_index;
990 $self->_set_forkchange(1);
995 sub _contains_files
{
997 (-d
$dir) or return 0;
998 opendir(my $dh, $dir) or die "opendir $dir failed: $!";
999 while (my $entry = readdir($dh)) {
1000 next if $entry eq '' || $entry eq '.' || $entry eq '..';
1001 closedir($dh), return 1
1002 if -f
"$dir/$entry" ||
1003 -d
"$dir/$entry" && _contains_files
("$dir/$entry");
1012 return _contains_files
($Girocco::Config
::reporoot
.'/'.$self->{name
});
1015 # Returns an array of 0 or more array refs, one for each bundle:
1016 # ->[0]: bundle creation time (seconds since epoch)
1017 # ->[1]: bundle name (e.g. foo-xxxxxxxx.bundle)
1018 # ->[2]: bundle size in bytes
1023 return @
{$self->{bundles
}} if ref($self->{bundles
}) eq 'ARRAY';
1025 if (-d
$self->{path
}.'/bundles') {{
1026 my $prefix = $self->{name
};
1027 $prefix =~ s
|^.*[^/]/([^/]+)$|$1|;
1028 opendir(my $dh, $self->{path
}.'/bundles') or last;
1029 while (my $bfile = readdir($dh)) {
1030 next unless $bfile =~ /^\d{8}_\d{6}-[0-9a-f]{8}$/;
1031 my $ctime = eval {timegm
(
1032 0+substr($bfile,13,2), 0+substr($bfile,11,2), 0+substr($bfile,9,2),
1033 0+substr($bfile,6,2), 0+substr($bfile,4,2)-1, 0+substr($bfile,0,4)-1900)};
1035 open(my $bh, '<', $self->{path
}.'/bundles/'.$bfile) or next;
1038 $f1 = $self->{path
}.'/objects/pack/'.$f1 if $f1 && $f1 !~ m
|^/|;
1039 $f2 = $self->{path
}.'/objects/pack/'.$f2 if $f2 && $f2 !~ m
|^/|;
1041 next unless $f1 && $f2 && $f1 ne $f2;
1044 next unless -e
$f1 && -e
$f2;
1045 my $s1 = -s
$f1 || 0;
1046 my $s2 = -s
$f2 || 0;
1047 next unless $s1 || $s2;
1048 push(@blist, [$ctime, "$prefix-".substr($bfile,16,8).".bundle", $s1+$s2]);
1052 @blist = sort({$b->[0] <=> $a->[0]} @blist);
1055 foreach my $bndl (@blist) {
1056 next if $seen{$bndl->[1]};
1057 $seen{$bndl->[1]} = 1;
1058 push(@result, $bndl);
1060 $self->{bundles
} = \
@result;
1064 sub has_alternates
{
1066 return -s
$self->{path
}.'/objects/info/alternates' ?
1 : 0;
1072 return scalar($self->bundles);
1075 # returns true if any of the notify fields are non-empty
1078 # We do not ckeck notifycia since it's defunct
1079 return $self->{'notifymail'} || $self->{'notifytag'} || $self->{'notifyjson'};
1083 # A project is considered empty if the git repository does not
1084 # have any refs. This means packed-refs does not exist or is
1085 # empty or only has lines starting with '#' AND there are no
1086 # files in the refs subdirectory hierarchy (no matter how deep).
1090 (-d
$self->{path
}) or return 0;
1091 if (-e
$self->{path
}.'/packed-refs') {
1092 open(my $pr, '<', $self->{path
}.'/packed-refs')
1093 or die "open $self->{path}./packed-refs failed: $!";
1095 while (my $ref = <$pr>) {
1096 next if $ref =~ /^#/;
1101 return 0 if $foundref;
1103 (-d
$self->{path
}.'/refs') or return 1;
1104 return !_contains_files
($self->{path
}.'/refs');
1108 # [0]: earliest possible scheduled next gc, undef if lastgc not set
1109 # [1]: approx. latest possible scheduled next gc, undef if lastgc not set
1110 # Both values (if not undef) are seconds since epoch
1111 # Result only considers lastgc and min_gc_interval nothing else
1114 my $lastgcepoch = parse_any_date
($self->{lastgc
});
1115 return (undef, undef) unless defined $lastgcepoch;
1116 return ($lastgcepoch + $Girocco::Config
::min_gc_interval
,
1117 int($lastgcepoch + 1.25 * $Girocco::Config
::min_gc_interval
+
1118 $Girocco::Config
::min_mirror_interval
));
1121 # returns boolean (0 or 1)
1122 # Attempts to determine whether or not a gc (and corresponding build
1123 # of a .bitmap/.bndl file) will actually take place at the next_gc
1124 # time (as returned by next_gc). Whether or not a .bitmap and .bndl
1125 # end up being built depends on whether or not the local object graph
1126 # is complete. In general if has_alternates is true then a .bitmap/.bndl
1127 # is not possible because the object graph will be incomplete,
1128 # but it *is* possible that even though the repository has_alternates,
1129 # it does not actually borrow any objects so a .bitmap/.bndl will build
1130 # in spite of the presence of alternates -- but this is expected to be rare.
1131 # The result is a best guess and false return value is not an absolute
1132 # guarantee that gc will not take place at the next interval, but it probably
1133 # will not if nothing changes in the meantime.
1136 my $lgc = parse_any_date
($self->{lastgc
});
1137 my $lrecv = parse_any_date
($self->{lastreceive
});
1138 my $lpgc = parse_any_date
($self->{lastparentgc
});
1139 return 1 unless defined($lgc) && defined($lrecv);
1140 if ($self->has_alternates) {
1141 return 1 unless defined($lpgc);
1142 return 1 unless $lpgc < $lgc;
1144 return 1 unless $lrecv < $lgc;
1145 # We don't try running any "is_dirty" check, so if somehow the
1146 # repository became dirty without updating lastreceive we might
1147 # incorrectly return false instead of true.
1155 # sanity check, disallow filenames starting with . .. or /
1156 unlink($self->{path
}.'/ctags/'.$ctag) if($ctag !~ m
|^(\
.\
.?
)/|);
1159 sub get_ctag_names
{
1162 opendir(my $dh, $self->{path
}.'/ctags')
1164 @ctags = grep { -f
"$self->{path}/ctags/$_" } readdir($dh);
1166 return sort({lc($a) cmp lc($b)} @ctags);
1172 my $heads = get_git
("--git-dir=$self->{path}", 'for-each-ref', '--format=%(objectname) %(refname)', 'refs/heads');
1173 defined($heads) or $heads = '';
1176 foreach (split(/\n/, $heads)) {
1178 next if !m
#^[0-9a-f]{40}\s+refs/heads/(.+)$ #x;
1181 push(@res, $self->{orig_HEAD
}) if !@res && defined($self->{orig_HEAD
}) && $self->{orig_HEAD
} ne '';
1187 my $HEAD = get_git
("--git-dir=$self->{path}", 'symbolic-ref', 'HEAD');
1188 defined($HEAD) or $HEAD = '';
1190 die "could not get HEAD" if ($HEAD !~ m{^refs/heads/(.+)$});
1196 my $newHEAD = shift;
1197 # Cursory checks only -- if you want to break your HEAD, be my guest
1198 if ($newHEAD =~ /^\/|['<>]|\.\.|\/$/) {
1199 die "grossly invalid new HEAD: $newHEAD";
1201 system($Girocco::Config::git_bin, "--git-dir=$self->{path}", 'symbolic
-ref', 'HEAD
', "refs/heads/$newHEAD");
1202 die "could not set HEAD" if ($? >> 8);
1203 ! -d "$self->{path}/mob" || $Girocco::Config::mob ne 'mob
'
1204 or system('cp
', '-p
', '-f
', "$self->{path}/HEAD", "$self->{path}/mob/HEAD") == 0;
1210 $type = 'REPO
' unless $type && $type =~ /^[A-Z]+$/;
1212 $self->{authtype} = $type;
1215 $self->{auth} = sha1_hex(time . $$ . rand() . join(':',%$self));
1217 my $expire = time + 24 * 3600;
1218 my $propval = "# ${type}AUTH $self->{auth} $expire";
1219 system($Girocco::Config::git_bin, '--git
-dir
='.$self->{path}, 'config
', 'gitweb
.repoauth
', $propval);
1226 delete $self->{auth};
1227 delete $self->{authtype};
1228 system($Girocco::Config::git_bin, '--git
-dir
='.$self->{path}, 'config
', '--unset
', 'gitweb
.repoauth
');
1233 my ($username) = @_;
1235 my $before_count = @{$self->{users}};
1236 $self->{users} = [grep { $_ ne $username } @{$self->{users}}];
1237 return @{$self->{users}} != $before_count;
1242 sub get_forkee_name {
1244 (m#^(.*)/.*?$#)[0]; #
1247 sub get_forkee_path {
1248 no warnings; # avoid silly 'unsuccessful
stat on filename with
\n' warning
1249 my $forkee = $Girocco::Config::reporoot.'/'.get_forkee_name($_[0]).'.git
';
1250 -d $forkee ? $forkee : '';
1253 # Ultimately the full project/fork name could end up being part of a Git ref name
1254 # when a project's forks are combined into one giant repository
for efficiency
.
1255 # That means that the project/fork name must satisfy the Git ref name requirements:
1257 # 1. Characters with an ASCII value less than or equal to 32 are not allowed
1258 # 2. The character with an ASCII value of 0x7F is not allowed
1259 # 3. The characters '~', '^', ':', '\', '*', '?', and '[' are not allowed
1260 # 4. The character '/' is a separator and is not allowed within a name
1261 # 5. The name may not start with '.' or end with '.'
1262 # 6. The name may not end with '.lock'
1263 # 7. The name may not contain the '..' sequence
1264 # 8. The name may not contain the '@{' sequence
1265 # 9. If multiple components are used (separated by '/'), no empty '' components
1267 # We also prohibit a trailing '.git' on any path component and futher restrict
1268 # the allowed characters to alphanumeric and [+._-] where names must start with
1271 sub _valid_name_characters
{
1276 and (not m
#/[+._-]#)
1279 and (not m
#\.git/#i)
1280 and (not m
#\.git$#i)
1281 and (not m
#\.idx/#i)
1282 and (not m
#\.idx$#i)
1283 and (not m
#\.lock/#i)
1284 and (not m
#\.lock$#i)
1285 and (not m
#\.pack/#i)
1286 and (not m
#\.pack$#i)
1287 and (not m
#\.bundle/#i)
1288 and (not m
#\.bundle$#i)
1290 and (not m/^[a-fA-F0-9]{38}$/)
1291 and m
#^[a-zA-Z0-9/+._-]+$#
1292 and !has_reserved_suffix
($_, $_[1], $_[2]);
1296 no warnings
; # avoid silly 'unsuccessful stat on filename with \n' warning
1298 _valid_name_characters
($_) and not exists($reservedprojectnames{lc($_)})
1299 and @
{[m
#/#g]} <= 5 # maximum fork depth is 5
1300 and ((not m
#/#) or -d get_forkee_path($_)); # will also catch ^/
1303 # It's possible that some forks have been kept but the forkee is gone.
1304 # In this case the standard valid_name check is too strict.
1306 no warnings
; # avoid silly 'unsuccessful stat on filename with \n' warning
1307 my ($name, $nodie) = @_;
1309 _valid_name_characters
($name, $Girocco::Config
::reporoot
, ".git")
1310 and ((not $name =~ m
#/#)
1311 or -d get_forkee_path
($name)
1312 or -d
$Girocco::Config
::reporoot
.'/'.get_forkee_name
($name)));
1313 (!$okay && $nodie) and return undef;
1314 !$okay and die "tried to query for project with invalid name $name!";
1315 (-d
$Girocco::Config
::reporoot
."/$name.git");
1319 open my $fd, '<', jailed_file
("/etc/group") or die "getting project list failed: $!";
1320 my @projects = map {/^([^:_\s#][^:\s#]*):[^:]*:\d{5,}:/ ?
$1 : ()} <$fd>;