12 use base
qw(Exporter);
13 our @EXPORT = qw(get_git scrypt jailed_file sendmail_pipe mailer_pipe
14 lock_file unlock_file valid_tag rand_adjust
15 filedb_atomic_append filedb_atomic_edit filedb_grep
16 filedb_atomic_grep valid_email valid_email_multi
17 valid_repo_url valid_web_url url_base url_path url_server
18 projects_html_list parse_rfc2822_date parse_any_date
19 extract_url_hostname is_dns_hostname is_our_hostname
20 get_cmd online_cpus sys_pagesize sys_memsize
21 calc_windowmemory to_utf8 capture_command human_size
22 calc_bigfilethreshold has_reserved_suffix noFatalsToBrowser);
27 $encoder = Encode
::find_encoding
('Windows-1252') ||
28 Encode
::find_encoding
('ISO-8859-1') or
29 die "failed to load ISO-8859-1 encoder\n";
33 my ($str, $encode) = @_;
34 return undef unless defined $str;
36 if (Encode
::is_utf8
($str) || utf8
::decode
($str)) {
39 $ans = $encoder->decode($str, Encode
::FB_DEFAULT
);
41 utf8
::encode
($ans) if $encode;
45 BEGIN {require "Girocco/extra/capture_command.pl"}
47 # Return the entire output sent to stdout from running a command
48 # Any output the command sends to stderr is discarded
49 # Returns undef if there was an error running the command (see $!)
51 my ($status, $result) = capture_command
(1, undef, @_);
52 return defined($status) && $status == 0 ?
$result : undef;
55 # Same as get_cmd except configured git binary is automatically provided
56 # as the first argument to get_cmd
58 return get_cmd
($Girocco::Config
::git_bin
, @_);
63 crypt($pwd||'', join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
69 $Girocco::Config
::chroot."/$filename";
78 use Fcntl
qw(O_WRONLY O_CREAT O_EXCL);
80 my $handle = new IO
::Handle
;
82 unless (sysopen($handle, $path, O_WRONLY
|O_CREAT
|O_EXCL
)) {
84 while (not sysopen($handle, $path, O_WRONLY
|O_CREAT
|O_EXCL
)) {
85 ($! == EEXIST
) or die "$path open failed: $!";
86 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
90 # XXX: filedb-specific
91 chmod 0664, $path or die "$path g+w failed: $!";
97 return defined($_[0]) && $_[0] eq jailed_file
('/etc/passwd');
100 sub _run_update_pwd_db
{
101 my ($path, $updatearg) = @_;
102 my @cmd = ($Girocco::Config
::basedir
.'/bin/update-pwd-db', "$path");
103 push(@cmd, $updatearg) if $updatearg;
104 system(@cmd) == 0 or die "update-pwd-db failed: $?";
108 my ($path, $noreplace, $updatearg) = @_;
111 _run_update_pwd_db
("$path.lock", $updatearg)
112 if $Girocco::Config
::update_pwd_db
&& _is_passwd_file
($path);
113 rename "$path.lock", $path or die "$path unlock failed: $!";
115 unlink "$path.lock" or die "$path unlock failed: $!";
119 sub filedb_atomic_append
{
120 my ($file, $line, $updatearg) = @_;
123 open my $src, '<', $file or die "$file open for reading failed: $!";
124 my $dst = lock_file
($file);
127 my $aid = (split /:/)[2];
128 $id = $aid + 1 if ($aid >= $id);
130 print $dst $_ or die "$file(l) write failed: $!";
133 $line =~ s/\\i/$id/g;
134 print $dst "$line\n" or die "$file(l) write failed: $!";
136 close $dst or die "$file(l) close failed: $!";
139 unlock_file
($file, 0, $updatearg);
144 sub filedb_atomic_edit
{
145 my ($file, $fn, $updatearg) = @_;
147 open my $src, '<', $file or die "$file open for reading failed: $!";
148 my $dst = lock_file
($file);
151 print $dst $fn->($_) or die "$file(l) write failed: $!";
154 close $dst or die "$file(l) close failed: $!";
157 unlock_file
($file, 0, $updatearg);
160 sub filedb_atomic_grep
{
161 my ($file, $fn) = @_;
164 open my $src, '<', $file or die "$file open for reading failed: $!";
165 my $dst = lock_file
($file);
168 my $result = $fn->($_);
169 push(@results, $result) if $result;
172 close $dst or die "$file(l) close failed: $!";
175 unlock_file
($file, 1);
180 my ($file, $fn) = @_;
183 open my $src, '<', $file or die "$file open for reading failed: $!";
186 my $result = $fn->($_);
187 push(@results, $result) if $result;
197 defined($email) or $email = '';
198 return $email =~ /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+$/;
201 sub valid_email_multi
{
202 my $email_multi = shift;
203 defined($email_multi) or $email_multi = '';
204 # More relaxed, we just want to avoid too dangerous characters.
205 return $email_multi =~ /^[a-zA-Z0-9+._, @-]+$/;
210 defined($url) or $url = '';
212 /^https?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~:?&=;-]*)?(#[a-zA-Z0-9._-]+)?$/;
216 my $url = shift || '';
217 # Currently neither username nor password is allowed in the URL and IPv6
218 # literal addresses are not accepted either.
219 $Girocco::Config
::mirror_svn
&&
220 $url =~ /^svn(\+https?)?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
222 $Girocco::Config
::mirror_darcs
&&
223 $url =~ /^darcs:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
225 $Girocco::Config
::mirror_bzr
&&
226 $url =~ /^bzr:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
228 $Girocco::Config
::mirror_hg
&&
229 $url =~ /^hg\+https?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
231 return $url =~ /^(https?|git):\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/;
234 sub extract_url_hostname
{
235 my $url = shift || '';
236 if ($url =~ m
,^bzr
://,) {
238 return 'launchpad.net' if $url =~ /^lp:/;
240 return undef unless $url =~ m
,^[A
-Za
-z0
-9+.-]+://[^/],;
241 $url =~ s
,^[A
-Za
-z0
-9+.-]+://,,;
242 $url =~ s
,^([^/]+).*$,$1,;
243 $url =~ s/:[0-9]*$//;
244 $url =~ s/^[^@]*[@]//;
245 return $url ?
$url : undef;
249 # RFC 1034 section 3.5
250 # RFC 1123 section 2.1
251 # RFC 1738 section 3.1
252 # RFC 2606 sections 2 & 3
253 # RFC 3986 section 3.2.2
254 sub is_dns_hostname
{
256 defined($host) or $host = '';
257 return 0 if $host eq '' || $host =~ /\s/;
258 # first remove a trailing '.'
260 return 0 if length($host) > 255;
261 my $octet = '(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])';
262 return 0 if $host =~ /^$octet\.$octet\.$octet\.$octet$/o;
263 my @labels = split(/[.]/, $host, -1);
264 return 0 unless @labels && @labels >= $Girocco::Config
::min_dns_labels
;
265 # now check each label
266 foreach my $label (@labels) {
267 return 0 unless length($label) > 0 && length($label) <= 63;
268 return 0 unless $label =~ /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
270 # disallow RFC 2606 names provided at least two labels are present
272 my $tld = lc($labels[-1]);
278 my $sld = lc($labels[-2]);
279 return 0 if $sld eq 'example' &&
280 ($tld eq 'com' || $tld eq 'net' || $tld eq 'org');
285 sub is_our_hostname
{
286 my $test = shift || '';
290 $Girocco::Config
::gitweburl
,
291 $Girocco::Config
::gitwebfiles
,
292 $Girocco::Config
::webadmurl
,
293 $Girocco::Config
::bundlesurl
,
294 $Girocco::Config
::htmlurl
,
295 $Girocco::Config
::httppullurl
,
296 $Girocco::Config
::httpbundleurl
,
297 $Girocco::Config
::httpspushurl
,
298 $Girocco::Config
::gitpullurl
,
299 $Girocco::Config
::pushurl
301 foreach my $url (@urls) {
303 my $host = extract_url_hostname
($url);
304 if (defined($host)) {
306 $names{lc($host)} = 1;
310 return $names{lc($test)} ?
1 : 0;
313 my (%_oktags, %_badtags);
315 # entries MUST be all lowercase to be effective
317 # These are always okay (a "whitelist") even if they would otherwise
319 ".net"=>1, "2d"=>1, "3d"=>1, "6502"=>1, "68000"=>1, "68008"=>1,
320 "68010"=>1, "68020"=>1, "68030"=>1, "68040"=>1, "68060"=>1,
321 "8086"=>1, "80286"=>1, "80386"=>1, "80486"=>1, "80586"=>1,
322 c
=>1, cc
=>1, make
=>1, www
=>1, x
=>1
324 map({$_oktags{lc($_)}=1} @Girocco::Config
::allowed_tags
);
325 # entries MUST be all lowercase to be effective
327 # These are "nonsense" or pointless tags
328 about
=>1, after
=>1, all
=>1, also
=>1, an
=>1, and=>1, another
=>1, any
=>1,
329 are
=>1, as
=>1, at
=>1, be
=>1, because
=>1, been
=>1, before
=>1, being
=>1,
330 between
=>1, both
=>1, but
=>1, by
=>1, came
=>1, can
=>1, come
=>1, could
=>1,
331 did
=>1, do=>1, each=>1, for=>1, from
=>1, get
=>1, got
=>1, had
=>1, has
=>1,
332 have
=>1, he
=>1, her
=>1, here
=>1, him
=>1, himself
=>1, his
=>1, how
=>1,
333 if=>1, in=>1, into
=>1, is
=>1, it
=>1, like
=>1, make
=>1, many
=>1, me
=>1,
334 might
=>1, more
=>1, most
=>1, much
=>1, must
=>1, my=>1, never
=>1, now
=>1,
335 of
=>1, oh
=>1, on
=>1, only
=>1, or=>1, other
=>1, our=>1, out
=>1, over
=>1,
336 said
=>1, same
=>1, see
=>1, should
=>1, since
=>1, some
=>1, still
=>1,
337 such
=>1, take
=>1, than
=>1, that
=>1, the
=>1, their
=>1, them
=>1, then
=>1,
338 there
=>1, these
=>1, they
=>1, this
=>1, those
=>1, through
=>1, to
=>1,
339 too
=>1, under
=>1, up
=>1, very
=>1, was
=>1, way
=>1, we
=>1, well
=>1,
340 were
=>1, what
=>1, where
=>1, which
=>1, while=>1, who
=>1, with
=>1,
341 would
=>1, yea
=>1, yeah
=>1, you
=>1, your
=>1, yup
=>1
343 # These are "offensive" tags with at least one letter escaped to
344 # avoid having this file trigger various safe-scan robots
345 $_badtags{"a\x73\x73"} = 1;
346 $_badtags{"a\x73\x73hole"} = 1;
347 $_badtags{"b\x30\x30b"} = 1;
348 $_badtags{"b\x30\x30bs"} = 1;
349 $_badtags{"b\x6f\x6fb"} = 1;
350 $_badtags{"b\x6f\x6fbs"} = 1;
351 $_badtags{"b\x75tt"} = 1;
352 $_badtags{"b\x75ttd\x69\x63k"} = 1;
353 $_badtags{"c\x6f\x63k"} = 1;
354 $_badtags{"c\x75\x6e\x74"} = 1;
355 $_badtags{"d\x69\x63k"} = 1;
356 $_badtags{"d\x69\x63kb\x75tt"} = 1;
357 $_badtags{"f\x75\x63k"} = 1;
358 $_badtags{"in\x63\x65st"} = 1;
359 $_badtags{"ph\x75\x63k"} = 1;
360 $_badtags{"p\x6f\x72n"} = 1;
361 $_badtags{"p\x6f\x72no"} = 1;
362 $_badtags{"p\x6f\x72nographic"} = 1;
363 $_badtags{"p\x72\x30n"} = 1;
364 $_badtags{"p\x72\x6fn"} = 1;
365 $_badtags{"r\x61\x70e"} = 1;
366 $_badtags{"s\x65\x78"} = 1;
367 map({$_badtags{lc($_)}=1} @Girocco::Config
::blocked_tags
);
370 # A valid tag must only have [a-zA-Z0-9:.+#_-] characters, must start with a
371 # letter, must not be a noise word, must be more than one character long,
372 # must not be a repeated letter and must be no more than 32 characters long.
373 # However, anything in %_oktags is explicitly allowed even if it otherwise
374 # would violate the rules.
376 local $_ = $_[0] || '';
377 return 1 if $_oktags{lc($_)};
378 return 0 unless /^[a-zA-Z][a-zA-Z0-9:.+#_-]+$/;
379 return 0 if $_badtags{lc($_)};
380 return 0 if /^(.)\1+$/;
381 return length($_) <= 32 ?
1 : 0;
384 # If the passed in argument looks like a URL, return only the stuff up through
385 # the host:port part otherwise return the entire argument.
387 my $url = shift || '';
389 $url = $1.$2.$3.$4 if $url =~ m
,^( [A
-Za
-z
][A
-Za
-z0
-9+.-]*: ) # scheme
390 ( // ) # // separator
391 ((?
:[^\@
]+\@
)?
) # optional userinfo
392 ( [^/?
#]+ ) # host and port
393 (?
:[/?#].*)?$,x; # path and optional query string and/or anchor
397 # If the passed in argument looks like a URL, return only the stuff following
398 # the host:port part otherwise return the entire argument.
399 # If the optional second argument is true, the returned value will have '/'
400 # appended if it does not already end in '/'.
402 my $url = shift || '';
403 my $add_slash = shift || 0;
405 $url = $1 if $url =~ m
,^(?
: [A
-Za
-z
][A
-Za
-z0
-9+.-]*: ) # scheme
406 (?
: // ) # // separator
407 (?
: [^\@
]+\@
)?
# optional userinfo
408 (?
: [^/?
#]+ ) # host and port
409 ((?
:[/?#].*)?)$,x; # path and optional query string and/or anchor
410 $url .= '/' if $add_slash && $url !~ m
|/$|;
414 # If both SERVER_NAME and SERVER_PORT are set pass the argument through url_path
415 # and then prefix it with the appropriate scheme (HTTPS=?on), host and port and
416 # return it. If a something that doesn't look like it could be the start of a
417 # URL path comes back from url_path or SERVER_NAME is a link-local IPv6 address
418 # then just return the argument unchanged.
420 my $url = shift || '';
421 my $path = url_path
($url);
422 return $url unless $path eq '' || $path =~ m
|^[/?
#]|;
423 return $url unless $ENV{'SERVER_NAME'} && $ENV{'SERVER_PORT'} &&
424 $ENV{'SERVER_PORT'} =~ /^[1-9][0-9]{0,4}$/;
425 return $url if $ENV{'SERVER_NAME'} =~ /^[[]?fe80:/i;
426 my $server = $ENV{'SERVER_NAME'};
427 # Deal with Apache bug where IPv6 literal server names do not include
428 # the required surrounding '[' and ']' characters
429 $server = '[' . $server . ']' if $server =~ /:/ && $server !~ /^[[]/;
430 my $ishttps = $ENV{'HTTPS'} && $ENV{'HTTPS'} =~ /^on$/i;
431 my $portnum = 0 + $ENV{'SERVER_PORT'};
433 if (($ishttps && $portnum != 443) || (!$ishttps && $portnum != 80)) {
434 $port = ':' . $portnum;
436 return 'http' . ($ishttps ?
's' : '') . '://' . $server . $port . $path;
439 # Returns the number rounded to the nearest tenths. The ".d" part will be
440 # excluded if it's ".0" unless the optional second argument is true
447 return '' . int($v/10) unless $v % 10 || $use0;
448 return '' . int($v/10) . '.' . ($v%10);
451 # Returns a human-readable size string (e.g. '1.5 MiB') for the value
452 # (in bytes) passed in. Returns '0' for undefined or 0 or not all digits.
453 # Otherwise returns '1 KiB' for < 1024, or else a number rounded to the
454 # nearest tenths of a KiB, MiB or GiB.
457 return "0" unless $v && $v =~ /^\d+$/;
458 return "1 KiB" unless $v > 1024;
460 return _tenths
($v) . " KiB" if $v < 1024;
462 return _tenths
($v) . " MiB" if $v < 1024;
464 return _tenths
($v) . " GiB";
469 $str =~ s/\&/\&/gs;
470 $str =~ s/\</\</gs;
471 $str =~ s/\>/\>/gs;
472 $str =~ s/\"/\"/gs; #"
476 # create relative time string from passed in age in seconds
481 if ($age > 60*60*24*365*2) {
482 $age_str = (int $age/60/60/24/365);
483 $age_str .= " years ago";
484 } elsif ($age > 60*60*24*(365/12)*2) {
485 $age_str = int $age/60/60/24/(365/12);
486 $age_str .= " months ago";
487 } elsif ($age > 60*60*24*7*2) {
488 $age_str = int $age/60/60/24/7;
489 $age_str .= " weeks ago";
490 } elsif ($age > 60*60*24*2) {
491 $age_str = int $age/60/60/24;
492 $age_str .= " days ago";
493 } elsif ($age > 60*60*2) {
494 $age_str = int $age/60/60;
495 $age_str .= " hours ago";
496 } elsif ($age > 60*2) {
497 $age_str = int $age/60;
498 $age_str .= " mins ago";
501 $age_str .= " secs ago";
502 } elsif ($age >= 0) {
503 $age_str = "right now";
505 $age_str = "future time";
510 # create relative time string from passed in idle in seconds
512 my $idle_str = _rel_age
(shift);
513 $idle_str =~ s/ ago//;
514 $idle_str = "not at all" if $idle_str eq "right now";
519 use POSIX
qw(strftime);
520 my ($fmt, $secs, $zonesecs) = @_;
521 my ($S,$M,$H,$d,$m,$y) = gmtime($secs + $zonesecs);
522 $zonesecs = int($zonesecs / 60);
524 my $ans = strftime
($fmt, $S, $M, $H, $d, $m, $y, -1, -1, -1);
528 $zonesecs = -$zonesecs;
532 $z .= sprintf("%02d%02d", int($zonesecs/60), $zonesecs % 60);
537 # Take a list of project names and produce a nicely formated table that
538 # includes owner links and descriptions. If the list is empty returns ''.
539 # The first argument may be a hash ref that contains options. The following
540 # options are available:
541 # target -- sets the target value of the owner link
542 # emptyok -- if true returns an empty table rather than ''
543 # sizecol -- if true include a human-readable size column
544 # typecol -- if true include type column with hover info
545 # changed -- if true include a changed and idle column
546 sub projects_html_list
{
548 if (defined($_[0]) && ref($_[0]) eq 'HASH') {
551 return '' unless @_ || (defined($options->{emptyok
}) && $options->{emptyok
});
552 require Girocco
::Project
;
555 $target = " target=\""._escapeHTML
($options->{target
})."\""
556 if defined($options->{target
});
557 my $withsize = defined($options->{sizecol
}) && $options->{sizecol
};
558 my $withtype = defined($options->{typecol
}) && $options->{typecol
};
559 my $withchanged = defined($options->{changed
}) && $options->{changed
};
561 $sizehead = substr(<<EOT, 0, -1) if $withsize;
562 <th class="sizecol"><span class="hover">Size<span><span class="head">Size</span
563 />Fork size excludes objects borrowed from the parent.</span></span></th
567 $typehead = '<th>Type</th>' if $withtype;
569 $chghead = substr(<<EOT, 0, -1) if $withchanged;
570 <th><span class="hover">Changed<span><span class="head">Changed</span
571 />The last time a ref change was received by this site.</span></span></th
572 ><th><span class="hover">Idle<span><span class="head">Idle</span
573 />The most recent committer time in <i>refs/heads</i>.</span></span></th
577 <table class='projectlist'><tr><th>Project</th>$sizehead$typehead$chghead<th class="desc">Description</th></tr>
579 my $trclass = ' class="odd"';
580 foreach (sort({lc($a) cmp lc($b)} @_)) {
581 if (Girocco
::Project
::does_exist
($_, 1)) {
582 my $proj = Girocco
::Project
->load($_);
583 my $projname = $proj->{name
}.".git";
584 my $projdesc = $proj->{desc
}||'';
585 utf8
::decode
($projdesc) if utf8
::valid
($projdesc);
588 my $psize = $proj->{reposizek
};
589 $psize = undef unless defined($psize) && $psize =~ /^\d+$/;
590 $psize = 0 if !defined($psize) && $proj->is_empty;
591 if (!defined($psize)) {
596 $psize = human_size
($psize * 1024);
597 $psize =~ s/ /\ /g;
599 $sizecol = '<td class="sizecol">'.$psize.'</td>';
603 if ($proj->{mirror
}) {
604 $typecol = substr(<<EOT, 0, -1);
605 <td class="type"><span class="hover">mirror<span class="nowrap">@{[_escapeHTML($proj->{url})]}</span></span></td>
608 my $users = @
{$proj->{users
}};
610 $users .= 's' unless @
{$proj->{users
}} == 1;
611 my $userlist = join(', ', sort({lc($a) cmp lc($b)} @
{$proj->{users
}}));
612 my $spncls = length($userlist) > 25 ?
'' : ' class="nowrap"';
613 $typecol = $userlist ?
substr(<<EOT, 0, -1) : substr(<<EOT, 0, -1);
614 <td
class="type"><span
class="hover">$users<span
$spncls>$userlist</span></span
></td
>
616 <td
class="type">$users</td
>
623 my $changetime = $proj->{lastchange
};
625 $rel = "<span class=\"hover\">" .
626 _rel_age
(time - parse_rfc2822_date
($changetime)) .
627 "<span class=\"nowrap\">$changetime</span></span>";
631 $changecol = substr(<<EOT, 0, -1);
632 <td class="change">$rel</td>
634 my $idletime = $proj->{lastactivity
};
636 $idlesecs = parse_any_date
($idletime, \
$tz) if $idletime;
638 my $idle2822 = _strftime
("%a, %d %b %Y %T %z", $idlesecs, $tz);
639 $rel = "<span class=\"hover\">" .
640 _rel_idle
(time - $idlesecs) .
641 "<span class=\"nowrap\">$idle2822</span></span>";
645 $changecol .= substr(<<EOT, 0, -1);
646 <td class="idle">$rel</td>
650 <tr$trclass><td><a href="@{[url_path($Girocco::Config::gitweburl)]}/$projname"$target
651 >@{[_escapeHTML($projname)]}</td>$sizecol$typecol$changecol<td>@{[_escapeHTML($projdesc)]}</td></tr>
653 $trclass = $trclass ?
'' : ' class="odd"';
660 return ($count || (defined($options->{emptyok
}) && $options->{emptyok
})) ?
$html : '';
666 jan
=> 0, feb
=> 1, mar
=> 2, apr
=> 3, may
=> 4, jun
=> 5,
667 jul
=> 6, aug
=> 7, sep
=> 8, oct => 9, nov
=> 10, dec
=> 11
671 # Should be in "date '+%a, %d %b %Y %T %z'" format as saved to lastgc, lastrefresh and lastchange
672 # The leading "%a, " is optional, returns undef if unrecognized date. This is also known as
673 # RFC 2822 date format and git's '%cD', '%aD' and --date=rfc2822 format.
674 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
675 sub parse_rfc2822_date
{
676 my $dstr = shift || '';
677 my $tzoff = shift || '';
678 $dstr = $1 if $dstr =~/^[^\s]+,\s*(.*)$/;
679 return undef unless $dstr =~
680 /^\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s+([+-]\d{4})\s*$/;
681 my ($d,$b,$Y,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7);
682 my $m = $_month_names{lc($b)};
683 return undef unless defined($m);
684 my $seconds = timegm
(0+$S, 0+$M, 0+$H, 0+$d, 0+$m, $Y-1900);
685 my $offset = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
686 $offset = -$offset if substr($z,0,1) eq '-';
687 $$tzoff = $offset if ref($tzoff) eq 'SCALAR';
688 return $seconds - $offset;
691 # Will parse any supported date format. Actually there are three formats
692 # currently supported:
693 # 1. RFC 2822 (uses parse_rfc2822_date)
694 # 2. RFC 3339 / ISO 8601 (T may be ' ' or '_', 'Z' is optional, ':' optional in TZ)
695 # 3. Same as #2 except no colons or hyphens allowed and hours MUST be 2 digits
696 # 4. unix seconds since epoch with optional +/- trailing TZ (may not have a ':')
697 # Returns undef if unsupported date.
698 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
700 my $dstr = shift || '';
701 my $tzoff = shift || '';
702 if ($dstr =~ /^\s*([-+]?\d+)(?:\s+([-+]\d{4}))?\s*$/) {
708 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
709 $off = -$off if substr($z,0,1) eq '-';
711 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
714 if ($dstr =~ /^\s*(\d{4})-(\d{2})-(\d{2})[Tt _](\d{1,2}):(\d{2}):(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{1,2}:?\d{2})))?\s*$/ ||
715 $dstr =~ /^\s*(\d{4})(\d{2})(\d{2})[Tt _](\d{2})(\d{2})(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{2}\d{2})))?\s*$/) {
716 my ($Y,$m,$d,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7||'');
717 my $seconds = timegm
(0+$S, 0+$M, 0+$H, 0+$d, $m-1, $Y-1900);
718 defined($z) && $z ne '' or $z = 'Z';
720 substr($z,1,0) = '0' if length($z) == 4;
723 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
724 $off = -$off if substr($z,0,1) eq '-';
726 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
727 return $seconds - $off;
729 return parse_rfc2822_date
($dstr, $tzoff);
732 # Input is a number such as a minute interval
733 # Return value is a random number between the input and 1.25*input
734 # This can be used to randomize the update and gc operations a bit to avoid
735 # having them all end up all clustered together
737 my $input = shift || 0;
738 return $input unless $input;
739 return $input + int(rand(0.25 * $input));
742 # Open a pipe to a new sendmail process. The '-i' option is always passed to
743 # the new process followed by any addtional arguments passed in. Note that
744 # the sendmail process is only expected to understand the '-i', '-t' and '-f'
745 # options. Using any other options via this function is not guaranteed to work.
746 # A list of recipients may follow the options. Combining a list of recipients
747 # with the '-t' option is not recommended.
749 return undef unless @_;
750 die "\$Girocco::Config::sendmail_bin is unset or not executable!\n"
751 unless $Girocco::Config
::sendmail_bin
&& -x
$Girocco::Config
::sendmail_bin
;
752 my $result = open(my $pipe, '|-', $Girocco::Config
::sendmail_bin
, '-i', @_);
753 return $result ?
$pipe : undef;
756 # Open a pipe that works similarly to a mailer such as /usr/bin/mail in that
757 # if the first argument is '-s', a subject line will be automatically added
758 # (using the second argument as the subject). Any remaining arguments are
759 # expected to be recipient addresses that will be added to an explicit To:
760 # line as well as passed on to sendmail_pipe. In addition an
761 # "Auto-Submitted: auto-generated" header is always added as well as a suitable
765 if (@_ >= 2 && $_[0] eq '-s') {
769 my $tolist = join(", ", @_);
770 unshift(@_, '-f', $Girocco::Config
::sender
) if $Girocco::Config
::sender
;
771 my $pipe = sendmail_pipe
(@_);
773 print $pipe "From: \"$Girocco::Config::name\" ",
774 "($Girocco::Config::title) ",
775 "<$Girocco::Config::admin>\n";
776 print $pipe "To: $tolist\n";
777 print $pipe "Subject: $subject\n" if defined($subject);
778 print $pipe "MIME-Version: 1.0\n";
779 print $pipe "Content-Type: text/plain; charset=utf-8\n";
780 print $pipe "Content-Transfer-Encoding: 8bit\n";
781 print $pipe "Auto-Submitted: auto-generated\n";
789 return undef unless defined($val);
790 $val =~ s/[\r\n]+$//s;
791 return undef unless $val =~ /^\d+$/;
793 return undef unless $val >= 1;
797 # Returns the number of "online" cpus or undef if undetermined
799 my @confcpus = $^O
eq "linux" ?
800 qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN) :
801 qw(NPROCESSORS_ONLN _NPROCESSORS_ONLN) ;
802 my $cpus = _goodval
(get_cmd
('getconf', $confcpus[0]));
803 return $cpus if $cpus;
804 $cpus = _goodval
(get_cmd
('getconf', $confcpus[1]));
805 return $cpus if $cpus;
806 if ($^O
ne "linux") {
807 my @sysctls = qw(hw.ncpu);
808 unshift(@sysctls, qw(hw.availcpu)) if $^O
eq "darwin";
809 foreach my $mib (@sysctls) {
810 $cpus = _goodval
(get_cmd
('sysctl', '-n', $mib));
811 return $cpus if $cpus;
817 # Returns the system page size in bytes or undef if undetermined
818 # This should never fail on a POSIX system
820 use POSIX
":unistd_h";
821 my $pagesize = sysconf
(_SC_PAGESIZE
);
822 return undef unless defined($pagesize) && $pagesize =~ /^\d+$/;
823 $pagesize = 0 + $pagesize;
824 return undef unless $pagesize >= 256;
828 # Returns the amount of available physical memory in bytes
829 # This may differ from the actual amount of physical memory installed
830 # Returns undef if this cannot be determined
832 my $pagesize = sys_pagesize
;
833 if ($pagesize && $^O
eq "linux") {
834 my $pages = _goodval
(get_cmd
('getconf', '_PHYS_PAGES'));
835 return $pagesize * $pages if $pages;
837 if ($^O
ne "linux") {
838 my @sysctls = qw(hw.physmem64);
839 unshift(@sysctls, qw(hw.memsize)) if $^O
eq "darwin";
840 foreach my $mib (@sysctls) {
841 my $memsize = _goodval
(get_cmd
('sysctl', '-n', $mib));
842 return $memsize if $memsize;
844 my $memsize32 = _goodval
(get_cmd
('sysctl', '-n', 'hw.physmem'));
845 return $memsize32 if $memsize32 && $memsize32 <= 2147483647;
847 my $pages = _goodval
(get_cmd
('sysctl', '-n', 'hw.availpages'));
848 return $pagesize * $pages if $pages;
850 return 2147483647 + 1 if $memsize32;
855 sub _get_max_conf_suffixed_size
{
857 return undef unless defined $conf && $conf =~ /^(\d+)([kKmMgG]?)$/;
858 my ($val, $suffix) = (0+$1, lc($2));
859 $val *= 1024 if $suffix eq 'k';
860 $val *= 1024 * 1024 if $suffix eq 'm';
861 $val *= 1024 * 1024 * 1024 if $suffix eq 'g';
865 sub _make_suffixed_size
{
867 return $size if $size % 1024;
869 return "${size}k" if $size % 1024;
871 return "${size}m" if $size % 1024;
876 # Return the value to pass to --window-memory= for git repack
877 # If the system memory or number of CPUs cannot be determined, returns "1g"
878 # Otherwise returns half the available memory divided by the number of CPUs
879 # but never more than 1 gigabyte or max_gc_window_memory_size.
880 sub calc_windowmemory
{
881 my $cpus = online_cpus
;
882 my $memsize = sys_memsize
;
883 my $max = 1024 * 1024 * 1024;
884 if ($cpus && $memsize) {
885 $max = int($memsize / 2 / $cpus);
886 $max = 1024 * 1024 * 1024 if $max >= 1024 * 1024 * 1024;
888 my $maxconf = _get_max_conf_suffixed_size
($Girocco::Config
::max_gc_window_memory_size
);
889 $max = $maxconf if defined($maxconf) && $maxconf && $max > $maxconf;
890 return _make_suffixed_size
($max);
893 # Return the value to set as core.bigFileThreshold for git repack
894 # If the system memory cannot be determined, returns "256m"
895 # Otherwise returns the available memory divided by 16
896 # but never more than 512 megabytes or max_gc_big_file_threshold_size.
897 sub calc_bigfilethreshold
{
898 my $memsize = sys_memsize
;
899 my $max = 256 * 1024 * 1024;
901 $max = int($memsize / 16);
902 $max = 512 * 1024 * 1024 if $max >= 512 * 1024 * 1024;
904 my $maxconf = _get_max_conf_suffixed_size
($Girocco::Config
::max_gc_big_file_threshold_size
);
905 $max = $maxconf if defined($maxconf) && $maxconf && $max > $maxconf;
906 return _make_suffixed_size
($max);
909 # $1 => thing to test
910 # $2 => optional directory, if given and -e "$2/$1$3", then return false
911 # $3 => optional, defaults to ''
912 sub has_reserved_suffix
{
913 no warnings
; # avoid silly 'unsuccessful stat on filename with \n' warning
914 my ($name, $dir, $ext) = @_;
915 $ext = '' unless defined $ext;
916 return 0 unless defined $name && $name =~ /\.([^.]+)$/;
917 return 0 unless exists $Girocco::Config
::reserved_suffixes
{lc($1)};
918 return 0 if defined $dir && -e
"$dir/$name$ext";
922 # undoes effect of `use CGI::Carp qw(fatalsToBrowser);`
923 # undoes effect of `use CGI::Carp qw(warningsToBrowser);`
924 sub noFatalsToBrowser
{
926 delete $SIG{__DIE__
};
927 delete $SIG{__WARN__
};
928 undef *CORE
::GLOBAL
::die;
929 *CORE
::GLOBAL
::die = sub {Carp
::croak
(@_)};
930 undef *CORE
::GLOBAL
::warn;
931 *CORE
::GLOBAL
::warn = sub {Carp
::carp
(@_)};