10 use base
qw(Exporter);
11 our @EXPORT = qw(scrypt jailed_file sendmail_pipe mailer_pipe
12 lock_file unlock_file valid_tag rand_adjust
13 filedb_atomic_append filedb_atomic_edit filedb_grep
14 filedb_atomic_grep valid_email valid_email_multi
15 valid_repo_url valid_web_url url_base url_path url_server
16 projects_html_list parse_rfc2822_date parse_any_date
17 extract_url_hostname is_dns_hostname is_our_hostname);
23 crypt($pwd||'', join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
29 $Girocco::Config
::chroot."/$filename";
38 use Fcntl
qw(O_WRONLY O_CREAT O_EXCL);
40 my $handle = new IO
::Handle
;
42 unless (sysopen($handle, $path, O_WRONLY
|O_CREAT
|O_EXCL
)) {
44 while (not sysopen($handle, $path, O_WRONLY
|O_CREAT
|O_EXCL
)) {
45 ($! == EEXIST
) or die "$path open failed: $!";
46 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
50 # XXX: filedb-specific
51 chmod 0664, $path or die "$path g+w failed: $!";
57 return defined($_[0]) && $_[0] eq jailed_file
('/etc/passwd');
60 sub _run_update_pwd_db
{
61 my ($path, $updatearg) = @_;
62 my @cmd = ($Girocco::Config
::basedir
.'/bin/update-pwd-db', "$path");
63 push(@cmd, $updatearg) if $updatearg;
64 system(@cmd) == 0 or die "update-pwd-db failed: $?";
68 my ($path, $noreplace, $updatearg) = @_;
71 _run_update_pwd_db
("$path.lock", $updatearg)
72 if $Girocco::Config
::update_pwd_db
&& _is_passwd_file
($path);
73 rename "$path.lock", $path or die "$path unlock failed: $!";
75 unlink "$path.lock" or die "$path unlock failed: $!";
79 sub filedb_atomic_append
{
80 my ($file, $line, $updatearg) = @_;
83 open my $src, '<', $file or die "$file open for reading failed: $!";
84 my $dst = lock_file
($file);
87 my $aid = (split /:/)[2];
88 $id = $aid + 1 if ($aid >= $id);
90 print $dst $_ or die "$file(l) write failed: $!";
94 print $dst "$line\n" or die "$file(l) write failed: $!";
96 close $dst or die "$file(l) close failed: $!";
99 unlock_file
($file, 0, $updatearg);
104 sub filedb_atomic_edit
{
105 my ($file, $fn, $updatearg) = @_;
107 open my $src, '<', $file or die "$file open for reading failed: $!";
108 my $dst = lock_file
($file);
111 print $dst $fn->($_) or die "$file(l) write failed: $!";
114 close $dst or die "$file(l) close failed: $!";
117 unlock_file
($file, 0, $updatearg);
120 sub filedb_atomic_grep
{
121 my ($file, $fn) = @_;
124 open my $src, '<', $file or die "$file open for reading failed: $!";
125 my $dst = lock_file
($file);
128 my $result = $fn->($_);
129 push(@results, $result) if $result;
132 close $dst or die "$file(l) close failed: $!";
135 unlock_file
($file, 1);
140 my ($file, $fn) = @_;
143 open my $src, '<', $file or die "$file open for reading failed: $!";
146 my $result = $fn->($_);
147 push(@results, $result) if $result;
157 defined($email) or $email = '';
158 return $email =~ /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+$/;
161 sub valid_email_multi
{
162 my $email_multi = shift;
163 defined($email_multi) or $email_multi = '';
164 # More relaxed, we just want to avoid too dangerous characters.
165 return $email_multi =~ /^[a-zA-Z0-9+._, @-]+$/;
170 defined($url) or $url = '';
172 /^https?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~:?&=;-]*)?(#[a-zA-Z0-9._-]+)?$/;
176 my $url = shift || '';
177 # Currently neither username nor password is allowed in the URL and IPv6
178 # literal addresses are not accepted either.
179 $Girocco::Config
::mirror_svn
&&
180 $url =~ /^svn(\+https?)?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
182 $Girocco::Config
::mirror_darcs
&&
183 $url =~ /^darcs:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
185 $Girocco::Config
::mirror_bzr
&&
186 $url =~ /^bzr:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
188 $Girocco::Config
::mirror_hg
&&
189 $url =~ /^hg\+https?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
191 return $url =~ /^(https?|git):\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/;
194 sub extract_url_hostname
{
195 my $url = shift || '';
196 if ($url =~ m
,^bzr
://,) {
198 return 'launchpad.net' if $url =~ /^lp:/;
200 return undef unless $url =~ m
,^[A
-Za
-z0
-9+.-]+://[^/],;
201 $url =~ s
,^[A
-Za
-z0
-9+.-]+://,,;
202 $url =~ s
,^([^/]+).*$,$1,;
203 $url =~ s/:[0-9]*$//;
204 $url =~ s/^[^@]*[@]//;
205 return $url ?
$url : undef;
209 # RFC 1034 section 3.5
210 # RFC 1123 section 2.1
211 # RFC 1738 section 3.1
212 # RFC 3986 section 3.2.2
213 sub is_dns_hostname
{
215 defined($host) or $host = '';
216 return 0 if $host eq '' || $host =~ /\s/;
217 # first remove a trailing '.'
219 my $octet = '(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])';
220 return 0 if $host =~ /^$octet\.$octet\.$octet\.$octet$/o;
221 my @labels = split(/[.]/, $host, -1);
222 return 0 unless @labels && @labels >= $Girocco::Config
::min_dns_labels
;
223 # now check each label
224 foreach my $label (@labels) {
225 return 0 unless length($label) > 0 && length($label) <= 63;
226 return 0 unless $label =~ /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
231 sub is_our_hostname
{
232 my $test = shift || '';
236 $Girocco::Config
::gitweburl
,
237 $Girocco::Config
::gitwebfiles
,
238 $Girocco::Config
::webadmurl
,
239 $Girocco::Config
::htmlurl
,
240 $Girocco::Config
::httppullurl
,
241 $Girocco::Config
::httpspushurl
,
242 $Girocco::Config
::gitpullurl
,
243 $Girocco::Config
::pushurl
245 foreach my $url (@urls) {
247 my $host = extract_url_hostname
($url);
248 if (defined($host)) {
250 $names{lc($host)} = 1;
254 return $names{lc($test)} ?
1 : 0;
260 about
=>1, after
=>1, all
=>1, also
=>1, an
=>1, and=>1, another
=>1, any
=>1,
261 are
=>1, as
=>1, at
=>1, be
=>1, because
=>1, been
=>1, before
=>1, being
=>1,
262 between
=>1, both
=>1, but
=>1, by
=>1, came
=>1, can
=>1, come
=>1, could
=>1,
263 did
=>1, do=>1, each=>1, for=>1, from
=>1, get
=>1, got
=>1, had
=>1, has
=>1,
264 have
=>1, he
=>1, her
=>1, here
=>1, him
=>1, himself
=>1, his
=>1, how
=>1,
265 if=>1, in=>1, into
=>1, is
=>1, it
=>1, like
=>1, make
=>1, many
=>1, me
=>1,
266 might
=>1, more
=>1, most
=>1, much
=>1, must
=>1, my=>1, never
=>1, now
=>1,
267 of
=>1, on
=>1, only
=>1, or=>1, other
=>1, our=>1, out
=>1, over
=>1,
268 said
=>1, same
=>1, see
=>1, should
=>1, since
=>1, some
=>1, still
=>1,
269 such
=>1, take
=>1, than
=>1, that
=>1, the
=>1, their
=>1, them
=>1, then
=>1,
270 there
=>1, these
=>1, they
=>1, this
=>1, those
=>1, through
=>1, to
=>1,
271 too
=>1, under
=>1, up
=>1, very
=>1, was
=>1, way
=>1, we
=>1, well
=>1,
272 were
=>1, what
=>1, where
=>1, which
=>1, while=>1, who
=>1, with
=>1,
273 would
=>1, you
=>1, your
=>1
277 # A valid tag must only have [a-zA-Z0-9:.+#_-] characters, must start with a
278 # letter, must not be a noise word and except for 'C' must be more than one
279 # character long and no more than 32 characters long.
281 local $_ = $_[0] || '';
282 return 1 if $_ eq 'C'; # Currently only allowed single letter tag
283 return 0 unless /^[a-zA-Z][a-zA-Z0-9:.+#_-]+$/;
284 return 0 if $_badtags{lc($_)};
285 return length($_) <= 32 ?
1 : 0;
288 # If the passed in argument looks like a URL, return only the stuff up through
289 # the host:port part otherwise return the entire argument.
291 my $url = shift || '';
293 $url = $1.$2.$3.$4 if $url =~ m
,^( [A
-Za
-z
][A
-Za
-z0
-9+.-]*: ) # scheme
294 ( // ) # // separator
295 ((?
:[^\@
]+\@
)?
) # optional userinfo
296 ( [^/?
#]+ ) # host and port
297 (?
:[/?#].*)?$,x; # path and optional query string and/or anchor
301 # If the passed in argument looks like a URL, return only the stuff following
302 # the host:port part otherwise return the entire argument.
304 my $url = shift || '';
305 my $no_empty = shift || 0;
307 $url = $1 if $url =~ m
,^(?
: [A
-Za
-z
][A
-Za
-z0
-9+.-]*: ) # scheme
308 (?
: // ) # // separator
309 (?
: [^\@
]+\@
)?
# optional userinfo
310 (?
: [^/?
#]+ ) # host and port
311 ((?
:[/?#].*)?)$,x; # path and optional query string and/or anchor
312 $url = '/' if $no_empty && $url eq '';
316 # If both SERVER_NAME and SERVER_PORT are set pass the argument through url_path
317 # and then prefix it with the appropriate scheme (HTTPS=?on), host and port and
318 # return it. If a something that doesn't look like it could be the start of a
319 # URL path comes back from url_path or SERVER_NAME is a link-local IPv6 address
320 # then just return the argument unchanged.
322 my $url = shift || '';
323 my $path = url_path
($url);
324 return $url unless $path eq '' || $path =~ m
|^[/?
#]|;
325 return $url unless $ENV{'SERVER_NAME'} && $ENV{'SERVER_PORT'} &&
326 $ENV{'SERVER_PORT'} =~ /^[1-9][0-9]{0,4}$/;
327 return $url if $ENV{'SERVER_NAME'} =~ /^[[]?fe80:/i;
328 my $server = $ENV{'SERVER_NAME'};
329 # Deal with Apache bug where IPv6 literal server names do not include
330 # the required surrounding '[' and ']' characters
331 $server = '[' . $server . ']' if $server =~ /:/ && $server !~ /^[[]/;
332 my $ishttps = $ENV{'HTTPS'} && $ENV{'HTTPS'} =~ /^on$/i;
333 my $portnum = 0 + $ENV{'SERVER_PORT'};
335 if (($ishttps && $portnum != 443) || (!$ishttps && $portnum != 80)) {
336 $port = ':' . $portnum;
338 return 'http' . ($ishttps ?
's' : '') . '://' . $server . $port . $path;
343 $str =~ s/\&/\&/gs;
344 $str =~ s/\</\</gs;
345 $str =~ s/\>/\>/gs;
346 $str =~ s/\"/\"/gs; #"
350 # create relative time string from passed in age in seconds
355 if ($age > 60*60*24*365*2) {
356 $age_str = (int $age/60/60/24/365);
357 $age_str .= " years ago";
358 } elsif ($age > 60*60*24*(365/12)*2) {
359 $age_str = int $age/60/60/24/(365/12);
360 $age_str .= " months ago";
361 } elsif ($age > 60*60*24*7*2) {
362 $age_str = int $age/60/60/24/7;
363 $age_str .= " weeks ago";
364 } elsif ($age > 60*60*24*2) {
365 $age_str = int $age/60/60/24;
366 $age_str .= " days ago";
367 } elsif ($age > 60*60*2) {
368 $age_str = int $age/60/60;
369 $age_str .= " hours ago";
370 } elsif ($age > 60*2) {
371 $age_str = int $age/60;
372 $age_str .= " mins ago";
375 $age_str .= " secs ago";
376 } elsif ($age >= 0) {
377 $age_str = "right now";
379 $age_str = "future time";
384 # create relative time string from passed in idle in seconds
386 my $idle_str = _rel_age
(shift);
387 $idle_str =~ s/ ago//;
388 $idle_str = "not at all" if $idle_str eq "right now";
393 use POSIX
qw(strftime);
394 my ($fmt, $secs, $zonesecs) = @_;
395 my ($S,$M,$H,$d,$m,$y) = gmtime($secs + $zonesecs);
396 $zonesecs = int($zonesecs / 60);
398 my $ans = strftime
($fmt, $S, $M, $H, $d, $m, $y, -1, -1, -1);
402 $zonesecs = -$zonesecs;
406 $z .= sprintf("%02d%02d", int($zonesecs/60), $zonesecs % 60);
411 # Take a list of project names and produce a nicely formated table that
412 # includes owner links and descriptions. If the list is empty returns ''.
413 # The first argument may be a hash ref that contains options. The following
414 # options are available:
415 # target -- sets the target value of the owner link
416 # emptyok -- if true returns an empty table rather than ''
417 # typecol -- if true include type column with hover info
418 # changed -- if true include a changed and idle column
419 sub projects_html_list
{
421 if (defined($_[0]) && ref($_[0]) eq 'HASH') {
424 return '' unless @_ || (defined($options->{emptyok
}) && $options->{emptyok
});
425 require Girocco
::Project
;
428 $target = " target=\""._escapeHTML
($options->{target
})."\""
429 if defined($options->{target
});
430 my $withtype = defined($options->{typecol
}) && $options->{typecol
};
431 my $withchanged = defined($options->{changed
}) && $options->{changed
};
433 $typehead = '<th>Type</th>' if $withtype;
435 $chghead = substr(<<EOT, 0, -1) if $withchanged;
436 <th><span class="hover">Changed<span><span class="head">Changed</span
437 />The last time a ref change was received by this site.</span></span></th
438 ><th><span class="hover">Idle<span><span class="head">Idle</span
439 />The most recent committer time in <i>refs/heads</i>.</span></span></th
443 <table class='projectlist'><tr><th>Project</th>$typehead$chghead<th class="desc">Description</th></tr>
445 my $trclass = ' class="odd"';
446 foreach (sort({lc($a) cmp lc($b)} @_)) {
447 if (Girocco
::Project
::does_exist
($_, 1)) {
448 my $proj = Girocco
::Project
->load($_);
449 my $projname = $proj->{name
}.".git";
450 my $projdesc = $proj->{desc
}||'';
451 utf8
::decode
($projdesc) if utf8
::valid
($projdesc);
454 if ($proj->{mirror
}) {
455 $typecol = substr(<<EOT, 0, -1);
456 <td class="type"><span class="hover">mirror<span class="nowrap">@{[_escapeHTML($proj->{url})]}</span></span></td>
459 my $users = @
{$proj->{users
}};
461 $users .= 's' unless @
{$proj->{users
}} == 1;
462 my $userlist = join(', ', sort({lc($a) cmp lc($b)} @
{$proj->{users
}}));
463 my $spncls = length($userlist) > 25 ?
'' : ' class="nowrap"';
464 $typecol = $userlist ?
substr(<<EOT, 0, -1) : substr(<<EOT, 0, -1);
465 <td
class="type"><span
class="hover">$users<span
$spncls>$userlist</span></span
></td
>
467 <td
class="type">$users</td
>
474 my $changetime = $proj->{lastchange
};
476 $rel = "<span class=\"hover\">" .
477 _rel_age
(time - parse_rfc2822_date
($changetime)) .
478 "<span class=\"nowrap\">$changetime</span></span>";
482 $changecol = substr(<<EOT, 0, -1);
483 <td class="change">$rel</td>
485 my $idletime = $proj->{lastactivity
};
487 $idlesecs = parse_any_date
($idletime, \
$tz) if $idletime;
489 my $idle2822 = _strftime
("%a, %d %b %Y %T %z", $idlesecs, $tz);
490 $rel = "<span class=\"hover\">" .
491 _rel_idle
(time - $idlesecs) .
492 "<span class=\"nowrap\">$idle2822</span></span>";
496 $changecol .= substr(<<EOT, 0, -1);
497 <td class="idle">$rel</td>
501 <tr$trclass><td><a href="@{[url_path($Girocco::Config::gitweburl)]}/$projname"$target
502 >@{[_escapeHTML($projname)]}</td>$typecol$changecol<td>@{[_escapeHTML($projdesc)]}</td></tr>
504 $trclass = $trclass ?
'' : ' class="odd"';
511 return ($count || (defined($options->{emptyok
}) && $options->{emptyok
})) ?
$html : '';
517 jan
=> 0, feb
=> 1, mar
=> 2, apr
=> 3, may
=> 4, jun
=> 5,
518 jul
=> 6, aug
=> 7, sep
=> 8, oct => 9, nov
=> 10, dec
=> 11
522 # Should be in "date '+%a, %d %b %Y %T %z'" format as saved to lastgc, lastrefresh and lastchange
523 # The leading "%a, " is optional, returns undef if unrecognized date. This is also known as
524 # RFC 2822 date format and git's '%cD', '%aD' and --date=rfc2822 format.
525 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
526 sub parse_rfc2822_date
{
527 my $dstr = shift || '';
528 my $tzoff = shift || '';
529 $dstr = $1 if $dstr =~/^[^\s]+,\s*(.*)$/;
530 return undef unless $dstr =~
531 /^\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s+([+-]\d{4})\s*$/;
532 my ($d,$b,$Y,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7);
533 my $m = $_month_names{lc($b)};
534 return undef unless defined($m);
535 my $seconds = timegm
(0+$S, 0+$M, 0+$H, 0+$d, 0+$m, $Y-1900);
536 my $offset = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
537 $offset = -$offset if substr($z,0,1) eq '-';
538 $$tzoff = $offset if ref($tzoff) eq 'SCALAR';
539 return $seconds - $offset;
542 # Will parse any supported date format. Actually there are three formats
543 # currently supported:
544 # 1. RFC 2822 (uses parse_rfc2822_date)
545 # 2. RFC 3339 / ISO 8601 (T may be ' ' or '_', 'Z' is optional, ':' optional in TZ)
546 # 3. Same as #2 except no colons or hyphens allowed and hours MUST be 2 digits
547 # 4. unix seconds since epoch with optional +/- trailing TZ (may not have a ':')
548 # Returns undef if unsupported date.
549 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
551 my $dstr = shift || '';
552 my $tzoff = shift || '';
553 if ($dstr =~ /^\s*([-+]?\d+)(?:\s+([-+]\d{4}))?\s*$/) {
559 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
560 $off = -$off if substr($z,0,1) eq '-';
562 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
565 if ($dstr =~ /^\s*(\d{4})-(\d{2})-(\d{2})[Tt _](\d{1,2}):(\d{2}):(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{1,2}:?\d{2})))?\s*$/ ||
566 $dstr =~ /^\s*(\d{4})(\d{2})(\d{2})[Tt _](\d{2})(\d{2})(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{2}\d{2})))?\s*$/) {
567 my ($Y,$m,$d,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7||'');
568 my $seconds = timegm
(0+$S, 0+$M, 0+$H, 0+$d, $m-1, $Y-1900);
569 defined($z) && $z ne '' or $z = 'Z';
571 substr($z,1,0) = '0' if length($z) == 4;
574 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
575 $off = -$off if substr($z,0,1) eq '-';
577 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
578 return $seconds - $off;
580 return parse_rfc2822_date
($dstr, $tzoff);
583 # Input is a number such as a minute interval
584 # Return value is a random number between the input and 1.25*input
585 # This can be used to randomize the update and gc operations a bit to avoid
586 # having them all end up all clustered together
588 my $input = shift || 0;
589 return $input unless $input;
590 return $input + int(rand(0.25 * $input));
593 # Open a pipe to a new sendmail process. The '-i' option is always passed to
594 # the new process followed by any addtional arguments passed in. Note that
595 # the sendmail process is only expected to understand the '-i', '-t' and '-f'
596 # options. Using any other options via this function is not guaranteed to work.
597 # A list of recipients may follow the options. Combining a list of recipients
598 # with the '-t' option is not recommended.
600 return undef unless @_;
601 die "\$Girocco::Config::sendmail_bin is unset or not executable!\n"
602 unless $Girocco::Config
::sendmail_bin
&& -x
$Girocco::Config
::sendmail_bin
;
603 my $result = open(my $pipe, '|-', $Girocco::Config
::sendmail_bin
, '-i', @_);
604 return $result ?
$pipe : undef;
607 # Open a pipe that works similarly to a mailer such as /usr/bin/mail in that
608 # if the first argument is '-s', a subject line will be automatically added
609 # (using the second argument as the subject). Any remaining arguments are
610 # expected to be recipient addresses that will be added to an explicit To:
611 # line as well as passed on to sendmail_pipe. In addition an
612 # "Auto-Submitted: auto-generated" header is always added as well as a suitable
616 if (@_ >= 2 && $_[0] eq '-s') {
620 my $tolist = join(", ", @_);
621 unshift(@_, '-f', $Girocco::Config
::sender
) if $Girocco::Config
::sender
;
622 my $pipe = sendmail_pipe
(@_);
624 print $pipe "From: \"$Girocco::Config::name\" ",
625 "($Girocco::Config::title) ",
626 "<$Girocco::Config::admin>\n";
627 print $pipe "To: $tolist\n";
628 print $pipe "Subject: $subject\n" if defined($subject);
629 print $pipe "MIME-Version: 1.0\n";
630 print $pipe "Content-Type: text/plain; charset=utf-8\n";
631 print $pipe "Content-Transfer-Encoding: 8bit\n";
632 print $pipe "Auto-Submitted: auto-generated\n";