14 use base
qw(Exporter);
15 our @EXPORT = qw(get_git scrypt jailed_file sendmail_pipe mailer_pipe
16 lock_file unlock_file valid_tag rand_adjust
17 filedb_atomic_append filedb_atomic_edit filedb_grep
18 filedb_atomic_grep valid_email valid_email_multi
19 valid_repo_url valid_web_url url_base url_path url_server
20 projects_html_list parse_rfc2822_date parse_any_date
21 extract_url_hostname is_dns_hostname is_our_hostname
22 get_cmd online_cpus sys_pagesize sys_memsize
23 calc_windowmemory to_utf8 capture_command);
28 $encoder = Encode
::find_encoding
('Windows-1252') ||
29 Encode
::find_encoding
('ISO-8859-1') or
30 die "failed to load ISO-8859-1 encoder\n";
34 my ($str, $encode) = @_;
35 return undef unless defined $str;
37 if (Encode
::is_utf8
($str) || utf8
::decode
($str)) {
40 $ans = $encoder->decode($str, Encode
::FB_DEFAULT
);
42 utf8
::encode
($ans) if $encode;
46 # Return the entire output sent to stdout and/or stderr from running a command.
47 # Input is redirected to /dev/null. Noncaptured output is totally discarded.
48 # Returns ($status, $output) where $status will be undef if there was a problem
49 # running the command otherwise $status will be the full waitpid $? result.
50 # $output will contain the captured output unless $status is undefined.
52 # 0 => discard stdout and stderr, only return command status
53 # 1 => capture stdout, discard stderr, return command status
54 # 2 => capture stderr, discard stdout, return command status
55 # 3 => capture stdout+stderr, return command status
56 # Second argument is undef, '' or string to send to command's stdin
57 # Subsequent arguments are command and arguments for pipe open call
59 # We avoid using STDIN/STDOUT in order to be compatible with FCGI mode
65 open(NULL
, '+<', File
::Spec
->devnull) or die "couldn't open devnull: $!";
67 if (defined($input) && $input ne '') {
69 unshift @cmd, 'sh', '-c', <<'SCRIPT', 'sh';
70 input="$(cat; printf x)";
71 printf '%s' "${input%?}" | "$@"
73 if (($flags & 0x3) == 0) {
74 $pid = open3
(\
*CHLDIN
, '>&NULL', '>&NULL', @cmd);
75 } elsif (($flags &0x3) == 1) {
76 $pid = open3
(\
*CHLDIN
, \
*CHLDOUT
, '>&NULL', @cmd);
77 } elsif (($flags &0x3) == 2) {
78 $pid = open3
(\
*CHLDIN
, '>&NULL', \
*CHLDOUT
, @cmd);
80 $pid = open3
(\
*CHLDIN
, \
*CHLDOUT
, \
*CHLDOUT
, @cmd);
83 local $SIG{'PIPE'} = 'IGNORE';
88 open(CHLDIN
, '<&NULL') or die "couldn't dup NULL: $!";
89 if (($flags & 0x3) == 0) {
90 $pid = open3
('<&CHLDIN', '>&NULL', '>&NULL', @_);
91 } elsif (($flags &0x3) == 1) {
92 $pid = open3
('<&CHLDIN', \
*CHLDOUT
, '>&NULL', @_);
93 } elsif (($flags &0x3) == 2) {
94 $pid = open3
('<&CHLDIN', '>&NULL', \
*CHLDOUT
, @_);
96 $pid = open3
('<&CHLDIN', \
*CHLDOUT
, \
*CHLDOUT
, @_);
99 close(NULL
) or die "couldn't close NULL: $!";
101 if ($pid && ($flags & 0x03)) {
105 defined($output) or $output = '';
106 my $status = waitpid($pid, 0);
107 return (undef) unless defined($status) && $status == $pid;
109 return ($status, $output);
112 # Return the entire output sent to stdout from running a command
113 # Any output the command sends to stderr is discarded
114 # Returns undef if there was an error running the command
116 my ($status, $result) = capture_command
(1, undef, @_);
117 return defined($status) && $status == 0 ?
$result : undef;
120 # Same as get_cmd except configured git binary is automatically provided
121 # as the first argument to get_cmd
123 return get_cmd
($Girocco::Config
::git_bin
, @_);
128 crypt($pwd||'', join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
134 $Girocco::Config
::chroot."/$filename";
142 use Errno
qw(EEXIST);
143 use Fcntl
qw(O_WRONLY O_CREAT O_EXCL);
145 my $handle = new IO
::Handle
;
147 unless (sysopen($handle, $path, O_WRONLY
|O_CREAT
|O_EXCL
)) {
149 while (not sysopen($handle, $path, O_WRONLY
|O_CREAT
|O_EXCL
)) {
150 ($! == EEXIST
) or die "$path open failed: $!";
151 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
155 # XXX: filedb-specific
156 chmod 0664, $path or die "$path g+w failed: $!";
161 sub _is_passwd_file
{
162 return defined($_[0]) && $_[0] eq jailed_file
('/etc/passwd');
165 sub _run_update_pwd_db
{
166 my ($path, $updatearg) = @_;
167 my @cmd = ($Girocco::Config
::basedir
.'/bin/update-pwd-db', "$path");
168 push(@cmd, $updatearg) if $updatearg;
169 system(@cmd) == 0 or die "update-pwd-db failed: $?";
173 my ($path, $noreplace, $updatearg) = @_;
176 _run_update_pwd_db
("$path.lock", $updatearg)
177 if $Girocco::Config
::update_pwd_db
&& _is_passwd_file
($path);
178 rename "$path.lock", $path or die "$path unlock failed: $!";
180 unlink "$path.lock" or die "$path unlock failed: $!";
184 sub filedb_atomic_append
{
185 my ($file, $line, $updatearg) = @_;
188 open my $src, '<', $file or die "$file open for reading failed: $!";
189 my $dst = lock_file
($file);
192 my $aid = (split /:/)[2];
193 $id = $aid + 1 if ($aid >= $id);
195 print $dst $_ or die "$file(l) write failed: $!";
198 $line =~ s/\\i/$id/g;
199 print $dst "$line\n" or die "$file(l) write failed: $!";
201 close $dst or die "$file(l) close failed: $!";
204 unlock_file
($file, 0, $updatearg);
209 sub filedb_atomic_edit
{
210 my ($file, $fn, $updatearg) = @_;
212 open my $src, '<', $file or die "$file open for reading failed: $!";
213 my $dst = lock_file
($file);
216 print $dst $fn->($_) or die "$file(l) write failed: $!";
219 close $dst or die "$file(l) close failed: $!";
222 unlock_file
($file, 0, $updatearg);
225 sub filedb_atomic_grep
{
226 my ($file, $fn) = @_;
229 open my $src, '<', $file or die "$file open for reading failed: $!";
230 my $dst = lock_file
($file);
233 my $result = $fn->($_);
234 push(@results, $result) if $result;
237 close $dst or die "$file(l) close failed: $!";
240 unlock_file
($file, 1);
245 my ($file, $fn) = @_;
248 open my $src, '<', $file or die "$file open for reading failed: $!";
251 my $result = $fn->($_);
252 push(@results, $result) if $result;
262 defined($email) or $email = '';
263 return $email =~ /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+$/;
266 sub valid_email_multi
{
267 my $email_multi = shift;
268 defined($email_multi) or $email_multi = '';
269 # More relaxed, we just want to avoid too dangerous characters.
270 return $email_multi =~ /^[a-zA-Z0-9+._, @-]+$/;
275 defined($url) or $url = '';
277 /^https?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~:?&=;-]*)?(#[a-zA-Z0-9._-]+)?$/;
281 my $url = shift || '';
282 # Currently neither username nor password is allowed in the URL and IPv6
283 # literal addresses are not accepted either.
284 $Girocco::Config
::mirror_svn
&&
285 $url =~ /^svn(\+https?)?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
287 $Girocco::Config
::mirror_darcs
&&
288 $url =~ /^darcs:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
290 $Girocco::Config
::mirror_bzr
&&
291 $url =~ /^bzr:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
293 $Girocco::Config
::mirror_hg
&&
294 $url =~ /^hg\+https?:\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/os
296 return $url =~ /^(https?|git):\/\
/[a-zA-Z0-9.:-]+(\/[_\
%a-zA
-Z0
-9.\
/~-]*)?$/;
299 sub extract_url_hostname
{
300 my $url = shift || '';
301 if ($url =~ m
,^bzr
://,) {
303 return 'launchpad.net' if $url =~ /^lp:/;
305 return undef unless $url =~ m
,^[A
-Za
-z0
-9+.-]+://[^/],;
306 $url =~ s
,^[A
-Za
-z0
-9+.-]+://,,;
307 $url =~ s
,^([^/]+).*$,$1,;
308 $url =~ s/:[0-9]*$//;
309 $url =~ s/^[^@]*[@]//;
310 return $url ?
$url : undef;
314 # RFC 1034 section 3.5
315 # RFC 1123 section 2.1
316 # RFC 1738 section 3.1
317 # RFC 3986 section 3.2.2
318 sub is_dns_hostname
{
320 defined($host) or $host = '';
321 return 0 if $host eq '' || $host =~ /\s/;
322 # first remove a trailing '.'
324 return 0 if length($host) > 255;
325 my $octet = '(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])';
326 return 0 if $host =~ /^$octet\.$octet\.$octet\.$octet$/o;
327 my @labels = split(/[.]/, $host, -1);
328 return 0 unless @labels && @labels >= $Girocco::Config
::min_dns_labels
;
329 # now check each label
330 foreach my $label (@labels) {
331 return 0 unless length($label) > 0 && length($label) <= 63;
332 return 0 unless $label =~ /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
337 sub is_our_hostname
{
338 my $test = shift || '';
342 $Girocco::Config
::gitweburl
,
343 $Girocco::Config
::gitwebfiles
,
344 $Girocco::Config
::webadmurl
,
345 $Girocco::Config
::htmlurl
,
346 $Girocco::Config
::httppullurl
,
347 $Girocco::Config
::httpspushurl
,
348 $Girocco::Config
::gitpullurl
,
349 $Girocco::Config
::pushurl
351 foreach my $url (@urls) {
353 my $host = extract_url_hostname
($url);
354 if (defined($host)) {
356 $names{lc($host)} = 1;
360 return $names{lc($test)} ?
1 : 0;
366 about
=>1, after
=>1, all
=>1, also
=>1, an
=>1, and=>1, another
=>1, any
=>1,
367 are
=>1, as
=>1, at
=>1, be
=>1, because
=>1, been
=>1, before
=>1, being
=>1,
368 between
=>1, both
=>1, but
=>1, by
=>1, came
=>1, can
=>1, come
=>1, could
=>1,
369 did
=>1, do=>1, each=>1, for=>1, from
=>1, get
=>1, got
=>1, had
=>1, has
=>1,
370 have
=>1, he
=>1, her
=>1, here
=>1, him
=>1, himself
=>1, his
=>1, how
=>1,
371 if=>1, in=>1, into
=>1, is
=>1, it
=>1, like
=>1, make
=>1, many
=>1, me
=>1,
372 might
=>1, more
=>1, most
=>1, much
=>1, must
=>1, my=>1, never
=>1, now
=>1,
373 of
=>1, on
=>1, only
=>1, or=>1, other
=>1, our=>1, out
=>1, over
=>1,
374 said
=>1, same
=>1, see
=>1, should
=>1, since
=>1, some
=>1, still
=>1,
375 such
=>1, take
=>1, than
=>1, that
=>1, the
=>1, their
=>1, them
=>1, then
=>1,
376 there
=>1, these
=>1, they
=>1, this
=>1, those
=>1, through
=>1, to
=>1,
377 too
=>1, under
=>1, up
=>1, very
=>1, was
=>1, way
=>1, we
=>1, well
=>1,
378 were
=>1, what
=>1, where
=>1, which
=>1, while=>1, who
=>1, with
=>1,
379 would
=>1, you
=>1, your
=>1
383 # A valid tag must only have [a-zA-Z0-9:.+#_-] characters, must start with a
384 # letter, must not be a noise word and except for 'C' must be more than one
385 # character long and no more than 32 characters long.
387 local $_ = $_[0] || '';
388 return 1 if $_ eq 'C'; # Currently only allowed single letter tag
389 return 0 unless /^[a-zA-Z][a-zA-Z0-9:.+#_-]+$/;
390 return 0 if $_badtags{lc($_)};
391 return length($_) <= 32 ?
1 : 0;
394 # If the passed in argument looks like a URL, return only the stuff up through
395 # the host:port part otherwise return the entire argument.
397 my $url = shift || '';
399 $url = $1.$2.$3.$4 if $url =~ m
,^( [A
-Za
-z
][A
-Za
-z0
-9+.-]*: ) # scheme
400 ( // ) # // separator
401 ((?
:[^\@
]+\@
)?
) # optional userinfo
402 ( [^/?
#]+ ) # host and port
403 (?
:[/?#].*)?$,x; # path and optional query string and/or anchor
407 # If the passed in argument looks like a URL, return only the stuff following
408 # the host:port part otherwise return the entire argument.
410 my $url = shift || '';
411 my $no_empty = shift || 0;
413 $url = $1 if $url =~ m
,^(?
: [A
-Za
-z
][A
-Za
-z0
-9+.-]*: ) # scheme
414 (?
: // ) # // separator
415 (?
: [^\@
]+\@
)?
# optional userinfo
416 (?
: [^/?
#]+ ) # host and port
417 ((?
:[/?#].*)?)$,x; # path and optional query string and/or anchor
418 $url = '/' if $no_empty && $url eq '';
422 # If both SERVER_NAME and SERVER_PORT are set pass the argument through url_path
423 # and then prefix it with the appropriate scheme (HTTPS=?on), host and port and
424 # return it. If a something that doesn't look like it could be the start of a
425 # URL path comes back from url_path or SERVER_NAME is a link-local IPv6 address
426 # then just return the argument unchanged.
428 my $url = shift || '';
429 my $path = url_path
($url);
430 return $url unless $path eq '' || $path =~ m
|^[/?
#]|;
431 return $url unless $ENV{'SERVER_NAME'} && $ENV{'SERVER_PORT'} &&
432 $ENV{'SERVER_PORT'} =~ /^[1-9][0-9]{0,4}$/;
433 return $url if $ENV{'SERVER_NAME'} =~ /^[[]?fe80:/i;
434 my $server = $ENV{'SERVER_NAME'};
435 # Deal with Apache bug where IPv6 literal server names do not include
436 # the required surrounding '[' and ']' characters
437 $server = '[' . $server . ']' if $server =~ /:/ && $server !~ /^[[]/;
438 my $ishttps = $ENV{'HTTPS'} && $ENV{'HTTPS'} =~ /^on$/i;
439 my $portnum = 0 + $ENV{'SERVER_PORT'};
441 if (($ishttps && $portnum != 443) || (!$ishttps && $portnum != 80)) {
442 $port = ':' . $portnum;
444 return 'http' . ($ishttps ?
's' : '') . '://' . $server . $port . $path;
449 $str =~ s/\&/\&/gs;
450 $str =~ s/\</\</gs;
451 $str =~ s/\>/\>/gs;
452 $str =~ s/\"/\"/gs; #"
456 # create relative time string from passed in age in seconds
461 if ($age > 60*60*24*365*2) {
462 $age_str = (int $age/60/60/24/365);
463 $age_str .= " years ago";
464 } elsif ($age > 60*60*24*(365/12)*2) {
465 $age_str = int $age/60/60/24/(365/12);
466 $age_str .= " months ago";
467 } elsif ($age > 60*60*24*7*2) {
468 $age_str = int $age/60/60/24/7;
469 $age_str .= " weeks ago";
470 } elsif ($age > 60*60*24*2) {
471 $age_str = int $age/60/60/24;
472 $age_str .= " days ago";
473 } elsif ($age > 60*60*2) {
474 $age_str = int $age/60/60;
475 $age_str .= " hours ago";
476 } elsif ($age > 60*2) {
477 $age_str = int $age/60;
478 $age_str .= " mins ago";
481 $age_str .= " secs ago";
482 } elsif ($age >= 0) {
483 $age_str = "right now";
485 $age_str = "future time";
490 # create relative time string from passed in idle in seconds
492 my $idle_str = _rel_age
(shift);
493 $idle_str =~ s/ ago//;
494 $idle_str = "not at all" if $idle_str eq "right now";
499 use POSIX
qw(strftime);
500 my ($fmt, $secs, $zonesecs) = @_;
501 my ($S,$M,$H,$d,$m,$y) = gmtime($secs + $zonesecs);
502 $zonesecs = int($zonesecs / 60);
504 my $ans = strftime
($fmt, $S, $M, $H, $d, $m, $y, -1, -1, -1);
508 $zonesecs = -$zonesecs;
512 $z .= sprintf("%02d%02d", int($zonesecs/60), $zonesecs % 60);
517 # Take a list of project names and produce a nicely formated table that
518 # includes owner links and descriptions. If the list is empty returns ''.
519 # The first argument may be a hash ref that contains options. The following
520 # options are available:
521 # target -- sets the target value of the owner link
522 # emptyok -- if true returns an empty table rather than ''
523 # typecol -- if true include type column with hover info
524 # changed -- if true include a changed and idle column
525 sub projects_html_list
{
527 if (defined($_[0]) && ref($_[0]) eq 'HASH') {
530 return '' unless @_ || (defined($options->{emptyok
}) && $options->{emptyok
});
531 require Girocco
::Project
;
534 $target = " target=\""._escapeHTML
($options->{target
})."\""
535 if defined($options->{target
});
536 my $withtype = defined($options->{typecol
}) && $options->{typecol
};
537 my $withchanged = defined($options->{changed
}) && $options->{changed
};
539 $typehead = '<th>Type</th>' if $withtype;
541 $chghead = substr(<<EOT, 0, -1) if $withchanged;
542 <th><span class="hover">Changed<span><span class="head">Changed</span
543 />The last time a ref change was received by this site.</span></span></th
544 ><th><span class="hover">Idle<span><span class="head">Idle</span
545 />The most recent committer time in <i>refs/heads</i>.</span></span></th
549 <table class='projectlist'><tr><th>Project</th>$typehead$chghead<th class="desc">Description</th></tr>
551 my $trclass = ' class="odd"';
552 foreach (sort({lc($a) cmp lc($b)} @_)) {
553 if (Girocco
::Project
::does_exist
($_, 1)) {
554 my $proj = Girocco
::Project
->load($_);
555 my $projname = $proj->{name
}.".git";
556 my $projdesc = $proj->{desc
}||'';
557 utf8
::decode
($projdesc) if utf8
::valid
($projdesc);
560 if ($proj->{mirror
}) {
561 $typecol = substr(<<EOT, 0, -1);
562 <td class="type"><span class="hover">mirror<span class="nowrap">@{[_escapeHTML($proj->{url})]}</span></span></td>
565 my $users = @
{$proj->{users
}};
567 $users .= 's' unless @
{$proj->{users
}} == 1;
568 my $userlist = join(', ', sort({lc($a) cmp lc($b)} @
{$proj->{users
}}));
569 my $spncls = length($userlist) > 25 ?
'' : ' class="nowrap"';
570 $typecol = $userlist ?
substr(<<EOT, 0, -1) : substr(<<EOT, 0, -1);
571 <td
class="type"><span
class="hover">$users<span
$spncls>$userlist</span></span
></td
>
573 <td
class="type">$users</td
>
580 my $changetime = $proj->{lastchange
};
582 $rel = "<span class=\"hover\">" .
583 _rel_age
(time - parse_rfc2822_date
($changetime)) .
584 "<span class=\"nowrap\">$changetime</span></span>";
588 $changecol = substr(<<EOT, 0, -1);
589 <td class="change">$rel</td>
591 my $idletime = $proj->{lastactivity
};
593 $idlesecs = parse_any_date
($idletime, \
$tz) if $idletime;
595 my $idle2822 = _strftime
("%a, %d %b %Y %T %z", $idlesecs, $tz);
596 $rel = "<span class=\"hover\">" .
597 _rel_idle
(time - $idlesecs) .
598 "<span class=\"nowrap\">$idle2822</span></span>";
602 $changecol .= substr(<<EOT, 0, -1);
603 <td class="idle">$rel</td>
607 <tr$trclass><td><a href="@{[url_path($Girocco::Config::gitweburl)]}/$projname"$target
608 >@{[_escapeHTML($projname)]}</td>$typecol$changecol<td>@{[_escapeHTML($projdesc)]}</td></tr>
610 $trclass = $trclass ?
'' : ' class="odd"';
617 return ($count || (defined($options->{emptyok
}) && $options->{emptyok
})) ?
$html : '';
623 jan
=> 0, feb
=> 1, mar
=> 2, apr
=> 3, may
=> 4, jun
=> 5,
624 jul
=> 6, aug
=> 7, sep
=> 8, oct => 9, nov
=> 10, dec
=> 11
628 # Should be in "date '+%a, %d %b %Y %T %z'" format as saved to lastgc, lastrefresh and lastchange
629 # The leading "%a, " is optional, returns undef if unrecognized date. This is also known as
630 # RFC 2822 date format and git's '%cD', '%aD' and --date=rfc2822 format.
631 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
632 sub parse_rfc2822_date
{
633 my $dstr = shift || '';
634 my $tzoff = shift || '';
635 $dstr = $1 if $dstr =~/^[^\s]+,\s*(.*)$/;
636 return undef unless $dstr =~
637 /^\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s+([+-]\d{4})\s*$/;
638 my ($d,$b,$Y,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7);
639 my $m = $_month_names{lc($b)};
640 return undef unless defined($m);
641 my $seconds = timegm
(0+$S, 0+$M, 0+$H, 0+$d, 0+$m, $Y-1900);
642 my $offset = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
643 $offset = -$offset if substr($z,0,1) eq '-';
644 $$tzoff = $offset if ref($tzoff) eq 'SCALAR';
645 return $seconds - $offset;
648 # Will parse any supported date format. Actually there are three formats
649 # currently supported:
650 # 1. RFC 2822 (uses parse_rfc2822_date)
651 # 2. RFC 3339 / ISO 8601 (T may be ' ' or '_', 'Z' is optional, ':' optional in TZ)
652 # 3. Same as #2 except no colons or hyphens allowed and hours MUST be 2 digits
653 # 4. unix seconds since epoch with optional +/- trailing TZ (may not have a ':')
654 # Returns undef if unsupported date.
655 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
657 my $dstr = shift || '';
658 my $tzoff = shift || '';
659 if ($dstr =~ /^\s*([-+]?\d+)(?:\s+([-+]\d{4}))?\s*$/) {
665 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
666 $off = -$off if substr($z,0,1) eq '-';
668 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
671 if ($dstr =~ /^\s*(\d{4})-(\d{2})-(\d{2})[Tt _](\d{1,2}):(\d{2}):(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{1,2}:?\d{2})))?\s*$/ ||
672 $dstr =~ /^\s*(\d{4})(\d{2})(\d{2})[Tt _](\d{2})(\d{2})(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{2}\d{2})))?\s*$/) {
673 my ($Y,$m,$d,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7||'');
674 my $seconds = timegm
(0+$S, 0+$M, 0+$H, 0+$d, $m-1, $Y-1900);
675 defined($z) && $z ne '' or $z = 'Z';
677 substr($z,1,0) = '0' if length($z) == 4;
680 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
681 $off = -$off if substr($z,0,1) eq '-';
683 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
684 return $seconds - $off;
686 return parse_rfc2822_date
($dstr, $tzoff);
689 # Input is a number such as a minute interval
690 # Return value is a random number between the input and 1.25*input
691 # This can be used to randomize the update and gc operations a bit to avoid
692 # having them all end up all clustered together
694 my $input = shift || 0;
695 return $input unless $input;
696 return $input + int(rand(0.25 * $input));
699 # Open a pipe to a new sendmail process. The '-i' option is always passed to
700 # the new process followed by any addtional arguments passed in. Note that
701 # the sendmail process is only expected to understand the '-i', '-t' and '-f'
702 # options. Using any other options via this function is not guaranteed to work.
703 # A list of recipients may follow the options. Combining a list of recipients
704 # with the '-t' option is not recommended.
706 return undef unless @_;
707 die "\$Girocco::Config::sendmail_bin is unset or not executable!\n"
708 unless $Girocco::Config
::sendmail_bin
&& -x
$Girocco::Config
::sendmail_bin
;
709 my $result = open(my $pipe, '|-', $Girocco::Config
::sendmail_bin
, '-i', @_);
710 return $result ?
$pipe : undef;
713 # Open a pipe that works similarly to a mailer such as /usr/bin/mail in that
714 # if the first argument is '-s', a subject line will be automatically added
715 # (using the second argument as the subject). Any remaining arguments are
716 # expected to be recipient addresses that will be added to an explicit To:
717 # line as well as passed on to sendmail_pipe. In addition an
718 # "Auto-Submitted: auto-generated" header is always added as well as a suitable
722 if (@_ >= 2 && $_[0] eq '-s') {
726 my $tolist = join(", ", @_);
727 unshift(@_, '-f', $Girocco::Config
::sender
) if $Girocco::Config
::sender
;
728 my $pipe = sendmail_pipe
(@_);
730 print $pipe "From: \"$Girocco::Config::name\" ",
731 "($Girocco::Config::title) ",
732 "<$Girocco::Config::admin>\n";
733 print $pipe "To: $tolist\n";
734 print $pipe "Subject: $subject\n" if defined($subject);
735 print $pipe "MIME-Version: 1.0\n";
736 print $pipe "Content-Type: text/plain; charset=utf-8\n";
737 print $pipe "Content-Transfer-Encoding: 8bit\n";
738 print $pipe "Auto-Submitted: auto-generated\n";
746 return undef unless defined($val);
747 $val =~ s/[\r\n]+$//s;
748 return undef unless $val =~ /^\d+$/;
750 return undef unless $val >= 1;
754 # Returns the number of "online" cpus or undef if undetermined
756 my @confcpus = $^O
eq "linux" ?
757 qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN) :
758 qw(NPROCESSORS_ONLN _NPROCESSORS_ONLN) ;
759 my $cpus = _goodval
(get_cmd
('getconf', $confcpus[0]));
760 return $cpus if $cpus;
761 $cpus = _goodval
(get_cmd
('getconf', $confcpus[1]));
762 return $cpus if $cpus;
763 if ($^O
ne "linux") {
764 my @sysctls = qw(hw.ncpu);
765 unshift(@sysctls, qw(hw.availcpu)) if $^O
eq "darwin";
766 foreach my $mib (@sysctls) {
767 $cpus = _goodval
(get_cmd
('sysctl', '-n', $mib));
768 return $cpus if $cpus;
774 # Returns the system page size in bytes or undef if undetermined
775 # This should never fail on a POSIX system
777 use POSIX
":unistd_h";
778 my $pagesize = sysconf
(_SC_PAGESIZE
);
779 return undef unless defined($pagesize) && $pagesize =~ /^\d+$/;
780 $pagesize = 0 + $pagesize;
781 return undef unless $pagesize >= 256;
785 # Returns the amount of available physical memory in bytes
786 # This may differ from the actual amount of physical memory installed
787 # Returns undef if this cannot be determined
789 my $pagesize = sys_pagesize
;
790 if ($pagesize && $^O
eq "linux") {
791 my $pages = _goodval
(get_cmd
('getconf', '_PHYS_PAGES'));
792 return $pagesize * $pages if $pages;
794 if ($^O
ne "linux") {
795 my @sysctls = qw(hw.physmem64);
796 unshift(@sysctls, qw(hw.memsize)) if $^O
eq "darwin";
797 foreach my $mib (@sysctls) {
798 my $memsize = _goodval
(get_cmd
('sysctl', '-n', $mib));
799 return $memsize if $memsize;
801 my $memsize32 = _goodval
(get_cmd
('sysctl', '-n', 'hw.physmem'));
802 return $memsize32 if $memsize32 && $memsize32 <= 2147483647;
804 my $pages = _goodval
(get_cmd
('sysctl', '-n', 'hw.availpages'));
805 return $pagesize * $pages if $pages;
807 return 2147483647 + 1 if $memsize32;
812 sub _max_conf_window_bytes
{
813 return undef unless defined($Girocco::Config
::max_gc_window_memory_size
);
815 $Girocco::Config
::max_gc_window_memory_size
=~ /^(\d+)([kKmMgG]?)$/;
816 my ($val, $suffix) = (0+$1, lc($2));
817 $val *= 1024 if $suffix eq 'k';
818 $val *= 1024 * 1024 if $suffix eq 'm';
819 $val *= 1024 * 1024 * 1024 if $suffix eq 'g';
823 # Return the value to pass to --window-memory= for git repack
824 # If the system memory or number of CPUs cannot be determined, returns "1g"
825 # Otherwise returns half the available memory divided by the number of CPUs
826 # but never more than 1 gigabyte or max_gc_window_memory_size.
827 sub calc_windowmemory
{
828 my $cpus = online_cpus
;
829 my $memsize = sys_memsize
;
830 my $max = 1024 * 1024 * 1024;
831 if ($cpus && $memsize) {
832 $max = int($memsize / 2 / $cpus);
833 $max = 1024 * 1024 * 1024 if $max >= 1024 * 1024 * 1024;
835 my $maxconf = _max_conf_window_bytes
;
836 $max = $maxconf if defined($maxconf) && $maxconf && $max > $maxconf;
837 return $max if $max % 1024;
839 return "${max}k" if $max % 1024;
841 return "${max}m" if $max % 1024;