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
::httpbundleurl
,
348 $Girocco::Config
::httpspushurl
,
349 $Girocco::Config
::gitpullurl
,
350 $Girocco::Config
::pushurl
352 foreach my $url (@urls) {
354 my $host = extract_url_hostname
($url);
355 if (defined($host)) {
357 $names{lc($host)} = 1;
361 return $names{lc($test)} ?
1 : 0;
367 about
=>1, after
=>1, all
=>1, also
=>1, an
=>1, and=>1, another
=>1, any
=>1,
368 are
=>1, as
=>1, at
=>1, be
=>1, because
=>1, been
=>1, before
=>1, being
=>1,
369 between
=>1, both
=>1, but
=>1, by
=>1, came
=>1, can
=>1, come
=>1, could
=>1,
370 did
=>1, do=>1, each=>1, for=>1, from
=>1, get
=>1, got
=>1, had
=>1, has
=>1,
371 have
=>1, he
=>1, her
=>1, here
=>1, him
=>1, himself
=>1, his
=>1, how
=>1,
372 if=>1, in=>1, into
=>1, is
=>1, it
=>1, like
=>1, make
=>1, many
=>1, me
=>1,
373 might
=>1, more
=>1, most
=>1, much
=>1, must
=>1, my=>1, never
=>1, now
=>1,
374 of
=>1, on
=>1, only
=>1, or=>1, other
=>1, our=>1, out
=>1, over
=>1,
375 said
=>1, same
=>1, see
=>1, should
=>1, since
=>1, some
=>1, still
=>1,
376 such
=>1, take
=>1, than
=>1, that
=>1, the
=>1, their
=>1, them
=>1, then
=>1,
377 there
=>1, these
=>1, they
=>1, this
=>1, those
=>1, through
=>1, to
=>1,
378 too
=>1, under
=>1, up
=>1, very
=>1, was
=>1, way
=>1, we
=>1, well
=>1,
379 were
=>1, what
=>1, where
=>1, which
=>1, while=>1, who
=>1, with
=>1,
380 would
=>1, you
=>1, your
=>1
384 # A valid tag must only have [a-zA-Z0-9:.+#_-] characters, must start with a
385 # letter, must not be a noise word and except for 'C' must be more than one
386 # character long and no more than 32 characters long.
388 local $_ = $_[0] || '';
389 return 1 if $_ eq 'C'; # Currently only allowed single letter tag
390 return 0 unless /^[a-zA-Z][a-zA-Z0-9:.+#_-]+$/;
391 return 0 if $_badtags{lc($_)};
392 return length($_) <= 32 ?
1 : 0;
395 # If the passed in argument looks like a URL, return only the stuff up through
396 # the host:port part otherwise return the entire argument.
398 my $url = shift || '';
400 $url = $1.$2.$3.$4 if $url =~ m
,^( [A
-Za
-z
][A
-Za
-z0
-9+.-]*: ) # scheme
401 ( // ) # // separator
402 ((?
:[^\@
]+\@
)?
) # optional userinfo
403 ( [^/?
#]+ ) # host and port
404 (?
:[/?#].*)?$,x; # path and optional query string and/or anchor
408 # If the passed in argument looks like a URL, return only the stuff following
409 # the host:port part otherwise return the entire argument.
410 # If the optional second argument is true, the returned value will have '/'
411 # appended if it does not already end in '/'.
413 my $url = shift || '';
414 my $add_slash = shift || 0;
416 $url = $1 if $url =~ m
,^(?
: [A
-Za
-z
][A
-Za
-z0
-9+.-]*: ) # scheme
417 (?
: // ) # // separator
418 (?
: [^\@
]+\@
)?
# optional userinfo
419 (?
: [^/?
#]+ ) # host and port
420 ((?
:[/?#].*)?)$,x; # path and optional query string and/or anchor
421 $url .= '/' if $add_slash && $url !~ m
|/$|;
425 # If both SERVER_NAME and SERVER_PORT are set pass the argument through url_path
426 # and then prefix it with the appropriate scheme (HTTPS=?on), host and port and
427 # return it. If a something that doesn't look like it could be the start of a
428 # URL path comes back from url_path or SERVER_NAME is a link-local IPv6 address
429 # then just return the argument unchanged.
431 my $url = shift || '';
432 my $path = url_path
($url);
433 return $url unless $path eq '' || $path =~ m
|^[/?
#]|;
434 return $url unless $ENV{'SERVER_NAME'} && $ENV{'SERVER_PORT'} &&
435 $ENV{'SERVER_PORT'} =~ /^[1-9][0-9]{0,4}$/;
436 return $url if $ENV{'SERVER_NAME'} =~ /^[[]?fe80:/i;
437 my $server = $ENV{'SERVER_NAME'};
438 # Deal with Apache bug where IPv6 literal server names do not include
439 # the required surrounding '[' and ']' characters
440 $server = '[' . $server . ']' if $server =~ /:/ && $server !~ /^[[]/;
441 my $ishttps = $ENV{'HTTPS'} && $ENV{'HTTPS'} =~ /^on$/i;
442 my $portnum = 0 + $ENV{'SERVER_PORT'};
444 if (($ishttps && $portnum != 443) || (!$ishttps && $portnum != 80)) {
445 $port = ':' . $portnum;
447 return 'http' . ($ishttps ?
's' : '') . '://' . $server . $port . $path;
452 $str =~ s/\&/\&/gs;
453 $str =~ s/\</\</gs;
454 $str =~ s/\>/\>/gs;
455 $str =~ s/\"/\"/gs; #"
459 # create relative time string from passed in age in seconds
464 if ($age > 60*60*24*365*2) {
465 $age_str = (int $age/60/60/24/365);
466 $age_str .= " years ago";
467 } elsif ($age > 60*60*24*(365/12)*2) {
468 $age_str = int $age/60/60/24/(365/12);
469 $age_str .= " months ago";
470 } elsif ($age > 60*60*24*7*2) {
471 $age_str = int $age/60/60/24/7;
472 $age_str .= " weeks ago";
473 } elsif ($age > 60*60*24*2) {
474 $age_str = int $age/60/60/24;
475 $age_str .= " days ago";
476 } elsif ($age > 60*60*2) {
477 $age_str = int $age/60/60;
478 $age_str .= " hours ago";
479 } elsif ($age > 60*2) {
480 $age_str = int $age/60;
481 $age_str .= " mins ago";
484 $age_str .= " secs ago";
485 } elsif ($age >= 0) {
486 $age_str = "right now";
488 $age_str = "future time";
493 # create relative time string from passed in idle in seconds
495 my $idle_str = _rel_age
(shift);
496 $idle_str =~ s/ ago//;
497 $idle_str = "not at all" if $idle_str eq "right now";
502 use POSIX
qw(strftime);
503 my ($fmt, $secs, $zonesecs) = @_;
504 my ($S,$M,$H,$d,$m,$y) = gmtime($secs + $zonesecs);
505 $zonesecs = int($zonesecs / 60);
507 my $ans = strftime
($fmt, $S, $M, $H, $d, $m, $y, -1, -1, -1);
511 $zonesecs = -$zonesecs;
515 $z .= sprintf("%02d%02d", int($zonesecs/60), $zonesecs % 60);
520 # Take a list of project names and produce a nicely formated table that
521 # includes owner links and descriptions. If the list is empty returns ''.
522 # The first argument may be a hash ref that contains options. The following
523 # options are available:
524 # target -- sets the target value of the owner link
525 # emptyok -- if true returns an empty table rather than ''
526 # typecol -- if true include type column with hover info
527 # changed -- if true include a changed and idle column
528 sub projects_html_list
{
530 if (defined($_[0]) && ref($_[0]) eq 'HASH') {
533 return '' unless @_ || (defined($options->{emptyok
}) && $options->{emptyok
});
534 require Girocco
::Project
;
537 $target = " target=\""._escapeHTML
($options->{target
})."\""
538 if defined($options->{target
});
539 my $withtype = defined($options->{typecol
}) && $options->{typecol
};
540 my $withchanged = defined($options->{changed
}) && $options->{changed
};
542 $typehead = '<th>Type</th>' if $withtype;
544 $chghead = substr(<<EOT, 0, -1) if $withchanged;
545 <th><span class="hover">Changed<span><span class="head">Changed</span
546 />The last time a ref change was received by this site.</span></span></th
547 ><th><span class="hover">Idle<span><span class="head">Idle</span
548 />The most recent committer time in <i>refs/heads</i>.</span></span></th
552 <table class='projectlist'><tr><th>Project</th>$typehead$chghead<th class="desc">Description</th></tr>
554 my $trclass = ' class="odd"';
555 foreach (sort({lc($a) cmp lc($b)} @_)) {
556 if (Girocco
::Project
::does_exist
($_, 1)) {
557 my $proj = Girocco
::Project
->load($_);
558 my $projname = $proj->{name
}.".git";
559 my $projdesc = $proj->{desc
}||'';
560 utf8
::decode
($projdesc) if utf8
::valid
($projdesc);
563 if ($proj->{mirror
}) {
564 $typecol = substr(<<EOT, 0, -1);
565 <td class="type"><span class="hover">mirror<span class="nowrap">@{[_escapeHTML($proj->{url})]}</span></span></td>
568 my $users = @
{$proj->{users
}};
570 $users .= 's' unless @
{$proj->{users
}} == 1;
571 my $userlist = join(', ', sort({lc($a) cmp lc($b)} @
{$proj->{users
}}));
572 my $spncls = length($userlist) > 25 ?
'' : ' class="nowrap"';
573 $typecol = $userlist ?
substr(<<EOT, 0, -1) : substr(<<EOT, 0, -1);
574 <td
class="type"><span
class="hover">$users<span
$spncls>$userlist</span></span
></td
>
576 <td
class="type">$users</td
>
583 my $changetime = $proj->{lastchange
};
585 $rel = "<span class=\"hover\">" .
586 _rel_age
(time - parse_rfc2822_date
($changetime)) .
587 "<span class=\"nowrap\">$changetime</span></span>";
591 $changecol = substr(<<EOT, 0, -1);
592 <td class="change">$rel</td>
594 my $idletime = $proj->{lastactivity
};
596 $idlesecs = parse_any_date
($idletime, \
$tz) if $idletime;
598 my $idle2822 = _strftime
("%a, %d %b %Y %T %z", $idlesecs, $tz);
599 $rel = "<span class=\"hover\">" .
600 _rel_idle
(time - $idlesecs) .
601 "<span class=\"nowrap\">$idle2822</span></span>";
605 $changecol .= substr(<<EOT, 0, -1);
606 <td class="idle">$rel</td>
610 <tr$trclass><td><a href="@{[url_path($Girocco::Config::gitweburl)]}/$projname"$target
611 >@{[_escapeHTML($projname)]}</td>$typecol$changecol<td>@{[_escapeHTML($projdesc)]}</td></tr>
613 $trclass = $trclass ?
'' : ' class="odd"';
620 return ($count || (defined($options->{emptyok
}) && $options->{emptyok
})) ?
$html : '';
626 jan
=> 0, feb
=> 1, mar
=> 2, apr
=> 3, may
=> 4, jun
=> 5,
627 jul
=> 6, aug
=> 7, sep
=> 8, oct => 9, nov
=> 10, dec
=> 11
631 # Should be in "date '+%a, %d %b %Y %T %z'" format as saved to lastgc, lastrefresh and lastchange
632 # The leading "%a, " is optional, returns undef if unrecognized date. This is also known as
633 # RFC 2822 date format and git's '%cD', '%aD' and --date=rfc2822 format.
634 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
635 sub parse_rfc2822_date
{
636 my $dstr = shift || '';
637 my $tzoff = shift || '';
638 $dstr = $1 if $dstr =~/^[^\s]+,\s*(.*)$/;
639 return undef unless $dstr =~
640 /^\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s+([+-]\d{4})\s*$/;
641 my ($d,$b,$Y,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7);
642 my $m = $_month_names{lc($b)};
643 return undef unless defined($m);
644 my $seconds = timegm
(0+$S, 0+$M, 0+$H, 0+$d, 0+$m, $Y-1900);
645 my $offset = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
646 $offset = -$offset if substr($z,0,1) eq '-';
647 $$tzoff = $offset if ref($tzoff) eq 'SCALAR';
648 return $seconds - $offset;
651 # Will parse any supported date format. Actually there are three formats
652 # currently supported:
653 # 1. RFC 2822 (uses parse_rfc2822_date)
654 # 2. RFC 3339 / ISO 8601 (T may be ' ' or '_', 'Z' is optional, ':' optional in TZ)
655 # 3. Same as #2 except no colons or hyphens allowed and hours MUST be 2 digits
656 # 4. unix seconds since epoch with optional +/- trailing TZ (may not have a ':')
657 # Returns undef if unsupported date.
658 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
660 my $dstr = shift || '';
661 my $tzoff = shift || '';
662 if ($dstr =~ /^\s*([-+]?\d+)(?:\s+([-+]\d{4}))?\s*$/) {
668 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
669 $off = -$off if substr($z,0,1) eq '-';
671 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
674 if ($dstr =~ /^\s*(\d{4})-(\d{2})-(\d{2})[Tt _](\d{1,2}):(\d{2}):(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{1,2}:?\d{2})))?\s*$/ ||
675 $dstr =~ /^\s*(\d{4})(\d{2})(\d{2})[Tt _](\d{2})(\d{2})(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{2}\d{2})))?\s*$/) {
676 my ($Y,$m,$d,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7||'');
677 my $seconds = timegm
(0+$S, 0+$M, 0+$H, 0+$d, $m-1, $Y-1900);
678 defined($z) && $z ne '' or $z = 'Z';
680 substr($z,1,0) = '0' if length($z) == 4;
683 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
684 $off = -$off if substr($z,0,1) eq '-';
686 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
687 return $seconds - $off;
689 return parse_rfc2822_date
($dstr, $tzoff);
692 # Input is a number such as a minute interval
693 # Return value is a random number between the input and 1.25*input
694 # This can be used to randomize the update and gc operations a bit to avoid
695 # having them all end up all clustered together
697 my $input = shift || 0;
698 return $input unless $input;
699 return $input + int(rand(0.25 * $input));
702 # Open a pipe to a new sendmail process. The '-i' option is always passed to
703 # the new process followed by any addtional arguments passed in. Note that
704 # the sendmail process is only expected to understand the '-i', '-t' and '-f'
705 # options. Using any other options via this function is not guaranteed to work.
706 # A list of recipients may follow the options. Combining a list of recipients
707 # with the '-t' option is not recommended.
709 return undef unless @_;
710 die "\$Girocco::Config::sendmail_bin is unset or not executable!\n"
711 unless $Girocco::Config
::sendmail_bin
&& -x
$Girocco::Config
::sendmail_bin
;
712 my $result = open(my $pipe, '|-', $Girocco::Config
::sendmail_bin
, '-i', @_);
713 return $result ?
$pipe : undef;
716 # Open a pipe that works similarly to a mailer such as /usr/bin/mail in that
717 # if the first argument is '-s', a subject line will be automatically added
718 # (using the second argument as the subject). Any remaining arguments are
719 # expected to be recipient addresses that will be added to an explicit To:
720 # line as well as passed on to sendmail_pipe. In addition an
721 # "Auto-Submitted: auto-generated" header is always added as well as a suitable
725 if (@_ >= 2 && $_[0] eq '-s') {
729 my $tolist = join(", ", @_);
730 unshift(@_, '-f', $Girocco::Config
::sender
) if $Girocco::Config
::sender
;
731 my $pipe = sendmail_pipe
(@_);
733 print $pipe "From: \"$Girocco::Config::name\" ",
734 "($Girocco::Config::title) ",
735 "<$Girocco::Config::admin>\n";
736 print $pipe "To: $tolist\n";
737 print $pipe "Subject: $subject\n" if defined($subject);
738 print $pipe "MIME-Version: 1.0\n";
739 print $pipe "Content-Type: text/plain; charset=utf-8\n";
740 print $pipe "Content-Transfer-Encoding: 8bit\n";
741 print $pipe "Auto-Submitted: auto-generated\n";
749 return undef unless defined($val);
750 $val =~ s/[\r\n]+$//s;
751 return undef unless $val =~ /^\d+$/;
753 return undef unless $val >= 1;
757 # Returns the number of "online" cpus or undef if undetermined
759 my @confcpus = $^O
eq "linux" ?
760 qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN) :
761 qw(NPROCESSORS_ONLN _NPROCESSORS_ONLN) ;
762 my $cpus = _goodval
(get_cmd
('getconf', $confcpus[0]));
763 return $cpus if $cpus;
764 $cpus = _goodval
(get_cmd
('getconf', $confcpus[1]));
765 return $cpus if $cpus;
766 if ($^O
ne "linux") {
767 my @sysctls = qw(hw.ncpu);
768 unshift(@sysctls, qw(hw.availcpu)) if $^O
eq "darwin";
769 foreach my $mib (@sysctls) {
770 $cpus = _goodval
(get_cmd
('sysctl', '-n', $mib));
771 return $cpus if $cpus;
777 # Returns the system page size in bytes or undef if undetermined
778 # This should never fail on a POSIX system
780 use POSIX
":unistd_h";
781 my $pagesize = sysconf
(_SC_PAGESIZE
);
782 return undef unless defined($pagesize) && $pagesize =~ /^\d+$/;
783 $pagesize = 0 + $pagesize;
784 return undef unless $pagesize >= 256;
788 # Returns the amount of available physical memory in bytes
789 # This may differ from the actual amount of physical memory installed
790 # Returns undef if this cannot be determined
792 my $pagesize = sys_pagesize
;
793 if ($pagesize && $^O
eq "linux") {
794 my $pages = _goodval
(get_cmd
('getconf', '_PHYS_PAGES'));
795 return $pagesize * $pages if $pages;
797 if ($^O
ne "linux") {
798 my @sysctls = qw(hw.physmem64);
799 unshift(@sysctls, qw(hw.memsize)) if $^O
eq "darwin";
800 foreach my $mib (@sysctls) {
801 my $memsize = _goodval
(get_cmd
('sysctl', '-n', $mib));
802 return $memsize if $memsize;
804 my $memsize32 = _goodval
(get_cmd
('sysctl', '-n', 'hw.physmem'));
805 return $memsize32 if $memsize32 && $memsize32 <= 2147483647;
807 my $pages = _goodval
(get_cmd
('sysctl', '-n', 'hw.availpages'));
808 return $pagesize * $pages if $pages;
810 return 2147483647 + 1 if $memsize32;
815 sub _max_conf_window_bytes
{
816 return undef unless defined($Girocco::Config
::max_gc_window_memory_size
);
818 $Girocco::Config
::max_gc_window_memory_size
=~ /^(\d+)([kKmMgG]?)$/;
819 my ($val, $suffix) = (0+$1, lc($2));
820 $val *= 1024 if $suffix eq 'k';
821 $val *= 1024 * 1024 if $suffix eq 'm';
822 $val *= 1024 * 1024 * 1024 if $suffix eq 'g';
826 # Return the value to pass to --window-memory= for git repack
827 # If the system memory or number of CPUs cannot be determined, returns "1g"
828 # Otherwise returns half the available memory divided by the number of CPUs
829 # but never more than 1 gigabyte or max_gc_window_memory_size.
830 sub calc_windowmemory
{
831 my $cpus = online_cpus
;
832 my $memsize = sys_memsize
;
833 my $max = 1024 * 1024 * 1024;
834 if ($cpus && $memsize) {
835 $max = int($memsize / 2 / $cpus);
836 $max = 1024 * 1024 * 1024 if $max >= 1024 * 1024 * 1024;
838 my $maxconf = _max_conf_window_bytes
;
839 $max = $maxconf if defined($maxconf) && $maxconf && $max > $maxconf;
840 return $max if $max % 1024;
842 return "${max}k" if $max % 1024;
844 return "${max}m" if $max % 1024;