girocco: support fetching bundles
[girocco.git] / Girocco / Util.pm
bloba816e1a6fd2ee72163d60001f3e5da4c8f77ae1d
1 package Girocco::Util;
3 use 5.008;
4 use strict;
5 use warnings;
7 use Girocco::Config;
8 use Time::Local;
9 use File::Spec;
10 use IPC::Open3;
11 use Encode;
13 BEGIN {
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);
26 my $encoder;
27 BEGIN {
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";
33 sub to_utf8 {
34 my ($str, $encode) = @_;
35 return undef unless defined $str;
36 my $ans;
37 if (Encode::is_utf8($str) || utf8::decode($str)) {
38 $ans = $str;
39 } else {
40 $ans = $encoder->decode($str, Encode::FB_DEFAULT);
42 utf8::encode($ans) if $encode;
43 return $ans;
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.
51 # First argument is:
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
58 sub capture_command {
59 # We avoid using STDIN/STDOUT in order to be compatible with FCGI mode
60 my $flags = shift;
61 my $input = shift;
62 local(*NULL);
63 local(*CHLDIN);
64 local(*CHLDOUT);
65 open(NULL, '+<', File::Spec->devnull) or die "couldn't open devnull: $!";
66 my $pid;
67 if (defined($input) && $input ne '') {
68 my @cmd = @_;
69 unshift @cmd, 'sh', '-c', <<'SCRIPT', 'sh';
70 input="$(cat; printf x)";
71 printf '%s' "${input%?}" | "$@"
72 SCRIPT
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);
79 } else {
80 $pid = open3(\*CHLDIN, \*CHLDOUT, \*CHLDOUT, @cmd);
82 if ($pid) {
83 local $SIG{'PIPE'} = 'IGNORE';
84 print CHLDIN $input;
85 close(CHLDIN);
87 } else {
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, @_);
95 } else {
96 $pid = open3('<&CHLDIN', \*CHLDOUT, \*CHLDOUT, @_);
99 close(NULL) or die "couldn't close NULL: $!";
100 my $output;
101 if ($pid && ($flags & 0x03)) {
102 local $/;
103 $output = <CHLDOUT>;
105 defined($output) or $output = '';
106 my $status = waitpid($pid, 0);
107 return (undef) unless defined($status) && $status == $pid;
108 $status = $?;
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
115 sub get_cmd {
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
122 sub get_git {
123 return get_cmd($Girocco::Config::git_bin, @_);
126 sub scrypt {
127 my ($pwd) = @_;
128 crypt($pwd||'', join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
131 sub jailed_file {
132 my ($filename) = @_;
133 $filename =~ s,^/,,;
134 $Girocco::Config::chroot."/$filename";
137 sub lock_file {
138 my ($path) = @_;
140 $path .= '.lock';
142 use Errno qw(EEXIST);
143 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
144 use IO::Handle;
145 my $handle = new IO::Handle;
147 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
148 my $cnt = 0;
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";
152 sleep(1);
155 # XXX: filedb-specific
156 chmod 0664, $path or die "$path g+w failed: $!";
158 $handle;
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: $?";
172 sub unlock_file {
173 my ($path, $noreplace, $updatearg) = @_;
175 if (!$noreplace) {
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: $!";
179 } else {
180 unlink "$path.lock" or die "$path unlock failed: $!";
184 sub filedb_atomic_append {
185 my ($file, $line, $updatearg) = @_;
186 my $id = 65536;
188 open my $src, '<', $file or die "$file open for reading failed: $!";
189 my $dst = lock_file($file);
191 while (<$src>) {
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: $!";
202 close $src;
204 unlock_file($file, 0, $updatearg);
206 $id;
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);
215 while (<$src>) {
216 print $dst $fn->($_) or die "$file(l) write failed: $!";
219 close $dst or die "$file(l) close failed: $!";
220 close $src;
222 unlock_file($file, 0, $updatearg);
225 sub filedb_atomic_grep {
226 my ($file, $fn) = @_;
227 my @results = ();
229 open my $src, '<', $file or die "$file open for reading failed: $!";
230 my $dst = lock_file($file);
232 while (<$src>) {
233 my $result = $fn->($_);
234 push(@results, $result) if $result;
237 close $dst or die "$file(l) close failed: $!";
238 close $src;
240 unlock_file($file, 1);
241 return @results;
244 sub filedb_grep {
245 my ($file, $fn) = @_;
246 my @results = ();
248 open my $src, '<', $file or die "$file open for reading failed: $!";
250 while (<$src>) {
251 my $result = $fn->($_);
252 push(@results, $result) if $result;
255 close $src;
257 return @results;
260 sub valid_email {
261 my $email = shift;
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+._, @-]+$/;
273 sub valid_web_url {
274 my $url = shift;
275 defined($url) or $url = '';
276 return $url =~
277 /^https?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~:?&=;-]*)?(#[a-zA-Z0-9._-]+)?$/;
280 sub valid_repo_url {
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
286 and return 1;
287 $Girocco::Config::mirror_darcs &&
288 $url =~ /^darcs:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
289 and return 1;
290 $Girocco::Config::mirror_bzr &&
291 $url =~ /^bzr:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
292 and return 1;
293 $Girocco::Config::mirror_hg &&
294 $url =~ /^hg\+https?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
295 and return 1;
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://,) {
302 $url =~ s,^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;
313 # See these RFCs:
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 {
319 my $host = shift;
320 defined($host) or $host = '';
321 return 0 if $host eq '' || $host =~ /\s/;
322 # first remove a trailing '.'
323 $host =~ s/\.$//;
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])?$/;
334 return 1;
337 sub is_our_hostname {
338 my $test = shift || '';
339 $test =~ s/\.$//;
340 my %names = ();
341 my @urls = (
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) {
353 if ($url) {
354 my $host = extract_url_hostname($url);
355 if (defined($host)) {
356 $host =~ s/\.$//;
357 $names{lc($host)} = 1;
361 return $names{lc($test)} ? 1 : 0;
364 my %_badtags;
365 BEGIN {
366 %_badtags = (
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.
387 sub valid_tag {
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.
397 sub url_base {
398 my $url = shift || '';
399 # See RFC 3968
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
405 return $url;
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 '/'.
412 sub url_path {
413 my $url = shift || '';
414 my $add_slash = shift || 0;
415 # See RFC 3968
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|/$|;
422 return $url;
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.
430 sub url_server {
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'};
443 my $port = '';
444 if (($ishttps && $portnum != 443) || (!$ishttps && $portnum != 80)) {
445 $port = ':' . $portnum;
447 return 'http' . ($ishttps ? 's' : '') . '://' . $server . $port . $path;
450 sub _escapeHTML {
451 my $str = shift;
452 $str =~ s/\&/\&amp;/gs;
453 $str =~ s/\</\&lt;/gs;
454 $str =~ s/\>/\&gt;/gs;
455 $str =~ s/\"/\&quot;/gs; #"
456 return $str;
459 # create relative time string from passed in age in seconds
460 sub _rel_age {
461 my $age = shift;
462 my $age_str;
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";
482 } elsif ($age > 2) {
483 $age_str = int $age;
484 $age_str .= " secs ago";
485 } elsif ($age >= 0) {
486 $age_str = "right now";
487 } else {
488 $age_str = "future time";
490 return $age_str;
493 # create relative time string from passed in idle in seconds
494 sub _rel_idle {
495 my $idle_str = _rel_age(shift);
496 $idle_str =~ s/ ago//;
497 $idle_str = "not at all" if $idle_str eq "right now";
498 return $idle_str;
501 sub _strftime {
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);
506 $fmt =~ s/%z/\$z/g;
507 my $ans = strftime($fmt, $S, $M, $H, $d, $m, $y, -1, -1, -1);
508 my $z;
509 if ($zonesecs < 0) {
510 $z = "-";
511 $zonesecs = -$zonesecs;
512 } else {
513 $z = "+";
515 $z .= sprintf("%02d%02d", int($zonesecs/60), $zonesecs % 60);
516 $ans =~ s/\$z/$z/g;
517 return $ans;
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 {
529 my $options = {};
530 if (defined($_[0]) && ref($_[0]) eq 'HASH') {
531 $options = shift;
533 return '' unless @_ || (defined($options->{emptyok}) && $options->{emptyok});
534 require Girocco::Project;
535 my $count = 0;
536 my $target = '';
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};
541 my $typehead = '';
542 $typehead = '<th>Type</th>' if $withtype;
543 my $chghead = '';
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
551 my $html = <<EOT;
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);
561 my $typecol = '';
562 if ($withtype) {
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>
567 } else {
568 my $users = @{$proj->{users}};
569 $users .= ' user';
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>
580 my $changecol = '';
581 if ($withchanged) {
582 my $rel = '';
583 my $changetime = $proj->{lastchange};
584 if ($changetime) {
585 $rel = "<span class=\"hover\">" .
586 _rel_age(time - parse_rfc2822_date($changetime)) .
587 "<span class=\"nowrap\">$changetime</span></span>";
588 } else {
589 $rel = "no commits";
591 $changecol = substr(<<EOT, 0, -1);
592 <td class="change">$rel</td>
594 my $idletime = $proj->{lastactivity};
595 my ($idlesecs, $tz);
596 $idlesecs = parse_any_date($idletime, \$tz) if $idletime;
597 if ($idlesecs) {
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>";
602 } else {
603 $rel = "no commits";
605 $changecol .= substr(<<EOT, 0, -1);
606 <td class="idle">$rel</td>
609 $html .= <<EOT;
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"';
614 ++$count;
617 $html .= <<EOT;
618 </table>
620 return ($count || (defined($options->{emptyok}) && $options->{emptyok})) ? $html : '';
623 my %_month_names;
624 BEGIN {
625 %_month_names = (
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
659 sub parse_any_date {
660 my $dstr = shift || '';
661 my $tzoff = shift || '';
662 if ($dstr =~ /^\s*([-+]?\d+)(?:\s+([-+]\d{4}))?\s*$/) {
663 # Unix timestamp
664 my $ts = 0 + $1;
665 my $off = 0;
666 if ($2) {
667 my $z = $2;
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';
672 return $ts;
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';
679 $z =~ s/://;
680 substr($z,1,0) = '0' if length($z) == 4;
681 my $off = 0;
682 if (uc($z) ne 'Z') {
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
696 sub rand_adjust {
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.
708 sub sendmail_pipe {
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
722 # "From:" header.
723 sub mailer_pipe {
724 my $subject = undef;
725 if (@_ >= 2 && $_[0] eq '-s') {
726 shift;
727 $subject = shift;
729 my $tolist = join(", ", @_);
730 unshift(@_, '-f', $Girocco::Config::sender) if $Girocco::Config::sender;
731 my $pipe = sendmail_pipe(@_);
732 if ($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";
742 print $pipe "\n";
744 return $pipe;
747 sub _goodval {
748 my $val = shift;
749 return undef unless defined($val);
750 $val =~ s/[\r\n]+$//s;
751 return undef unless $val =~ /^\d+$/;
752 $val = 0 + $val;
753 return undef unless $val >= 1;
754 return $val;
757 # Returns the number of "online" cpus or undef if undetermined
758 sub online_cpus {
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;
774 return undef;
777 # Returns the system page size in bytes or undef if undetermined
778 # This should never fail on a POSIX system
779 sub sys_pagesize {
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;
785 return $pagesize;
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
791 sub sys_memsize {
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;
806 if ($pagesize) {
807 my $pages = _goodval(get_cmd('sysctl', '-n', 'hw.availpages'));
808 return $pagesize * $pages if $pages;
810 return 2147483647 + 1 if $memsize32;
812 return undef;
815 sub _max_conf_window_bytes {
816 return undef unless defined($Girocco::Config::max_gc_window_memory_size);
817 return undef unless
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';
823 return $val;
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;
841 $max /= 1024;
842 return "${max}k" if $max % 1024;
843 $max /= 1024;
844 return "${max}m" if $max % 1024;
845 $max /= 1024;
846 return "${max}g";