Util.pm: mention fork size excludes borrowed objects
[girocco.git] / Girocco / Util.pm
blobeefcaf306ac86f5541920dfc9568d1936b5f74ee
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 human_size
24 has_reserved_suffix);
27 my $encoder;
28 BEGIN {
29 $encoder = Encode::find_encoding('Windows-1252') ||
30 Encode::find_encoding('ISO-8859-1') or
31 die "failed to load ISO-8859-1 encoder\n";
34 sub to_utf8 {
35 my ($str, $encode) = @_;
36 return undef unless defined $str;
37 my $ans;
38 if (Encode::is_utf8($str) || utf8::decode($str)) {
39 $ans = $str;
40 } else {
41 $ans = $encoder->decode($str, Encode::FB_DEFAULT);
43 utf8::encode($ans) if $encode;
44 return $ans;
47 # Return the entire output sent to stdout and/or stderr from running a command.
48 # Input is redirected to /dev/null. Noncaptured output is totally discarded.
49 # Returns ($status, $output) where $status will be undef if there was a problem
50 # running the command otherwise $status will be the full waitpid $? result.
51 # $output will contain the captured output unless $status is undefined.
52 # First argument is:
53 # 0 => discard stdout and stderr, only return command status
54 # 1 => capture stdout, discard stderr, return command status
55 # 2 => capture stderr, discard stdout, return command status
56 # 3 => capture stdout+stderr, return command status
57 # Second argument is undef, '' or string to send to command's stdin
58 # Subsequent arguments are command and arguments for pipe open call
59 sub capture_command {
60 # We avoid using STDIN/STDOUT in order to be compatible with FCGI mode
61 my $flags = shift;
62 my $input = shift;
63 local(*NULL);
64 local(*CHLDIN);
65 local(*CHLDOUT);
66 open(NULL, '+<', File::Spec->devnull) or die "couldn't open devnull: $!";
67 my $pid;
68 if (defined($input) && $input ne '') {
69 my @cmd = @_;
70 unshift @cmd, 'sh', '-c', <<'SCRIPT', 'sh';
71 input="$(cat; printf x)";
72 printf '%s' "${input%?}" | "$@"
73 SCRIPT
74 if (($flags & 0x3) == 0) {
75 $pid = open3(\*CHLDIN, '>&NULL', '>&NULL', @cmd);
76 } elsif (($flags &0x3) == 1) {
77 $pid = open3(\*CHLDIN, \*CHLDOUT, '>&NULL', @cmd);
78 } elsif (($flags &0x3) == 2) {
79 $pid = open3(\*CHLDIN, '>&NULL', \*CHLDOUT, @cmd);
80 } else {
81 $pid = open3(\*CHLDIN, \*CHLDOUT, \*CHLDOUT, @cmd);
83 if ($pid) {
84 local $SIG{'PIPE'} = 'IGNORE';
85 print CHLDIN $input;
86 close(CHLDIN);
88 } else {
89 open(CHLDIN, '<&NULL') or die "couldn't dup NULL: $!";
90 if (($flags & 0x3) == 0) {
91 $pid = open3('<&CHLDIN', '>&NULL', '>&NULL', @_);
92 } elsif (($flags &0x3) == 1) {
93 $pid = open3('<&CHLDIN', \*CHLDOUT, '>&NULL', @_);
94 } elsif (($flags &0x3) == 2) {
95 $pid = open3('<&CHLDIN', '>&NULL', \*CHLDOUT, @_);
96 } else {
97 $pid = open3('<&CHLDIN', \*CHLDOUT, \*CHLDOUT, @_);
100 close(NULL) or die "couldn't close NULL: $!";
101 my $output;
102 if ($pid && ($flags & 0x03)) {
103 local $/;
104 $output = <CHLDOUT>;
106 defined($output) or $output = '';
107 my $status = waitpid($pid, 0);
108 return (undef) unless defined($status) && $status == $pid;
109 $status = $?;
110 return ($status, $output);
113 # Return the entire output sent to stdout from running a command
114 # Any output the command sends to stderr is discarded
115 # Returns undef if there was an error running the command
116 sub get_cmd {
117 my ($status, $result) = capture_command(1, undef, @_);
118 return defined($status) && $status == 0 ? $result : undef;
121 # Same as get_cmd except configured git binary is automatically provided
122 # as the first argument to get_cmd
123 sub get_git {
124 return get_cmd($Girocco::Config::git_bin, @_);
127 sub scrypt {
128 my ($pwd) = @_;
129 crypt($pwd||'', join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
132 sub jailed_file {
133 my ($filename) = @_;
134 $filename =~ s,^/,,;
135 $Girocco::Config::chroot."/$filename";
138 sub lock_file {
139 my ($path) = @_;
141 $path .= '.lock';
143 use Errno qw(EEXIST);
144 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
145 use IO::Handle;
146 my $handle = new IO::Handle;
148 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
149 my $cnt = 0;
150 while (not sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
151 ($! == EEXIST) or die "$path open failed: $!";
152 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
153 sleep(1);
156 # XXX: filedb-specific
157 chmod 0664, $path or die "$path g+w failed: $!";
159 $handle;
162 sub _is_passwd_file {
163 return defined($_[0]) && $_[0] eq jailed_file('/etc/passwd');
166 sub _run_update_pwd_db {
167 my ($path, $updatearg) = @_;
168 my @cmd = ($Girocco::Config::basedir.'/bin/update-pwd-db', "$path");
169 push(@cmd, $updatearg) if $updatearg;
170 system(@cmd) == 0 or die "update-pwd-db failed: $?";
173 sub unlock_file {
174 my ($path, $noreplace, $updatearg) = @_;
176 if (!$noreplace) {
177 _run_update_pwd_db("$path.lock", $updatearg)
178 if $Girocco::Config::update_pwd_db && _is_passwd_file($path);
179 rename "$path.lock", $path or die "$path unlock failed: $!";
180 } else {
181 unlink "$path.lock" or die "$path unlock failed: $!";
185 sub filedb_atomic_append {
186 my ($file, $line, $updatearg) = @_;
187 my $id = 65536;
189 open my $src, '<', $file or die "$file open for reading failed: $!";
190 my $dst = lock_file($file);
192 while (<$src>) {
193 my $aid = (split /:/)[2];
194 $id = $aid + 1 if ($aid >= $id);
196 print $dst $_ or die "$file(l) write failed: $!";
199 $line =~ s/\\i/$id/g;
200 print $dst "$line\n" or die "$file(l) write failed: $!";
202 close $dst or die "$file(l) close failed: $!";
203 close $src;
205 unlock_file($file, 0, $updatearg);
207 $id;
210 sub filedb_atomic_edit {
211 my ($file, $fn, $updatearg) = @_;
213 open my $src, '<', $file or die "$file open for reading failed: $!";
214 my $dst = lock_file($file);
216 while (<$src>) {
217 print $dst $fn->($_) or die "$file(l) write failed: $!";
220 close $dst or die "$file(l) close failed: $!";
221 close $src;
223 unlock_file($file, 0, $updatearg);
226 sub filedb_atomic_grep {
227 my ($file, $fn) = @_;
228 my @results = ();
230 open my $src, '<', $file or die "$file open for reading failed: $!";
231 my $dst = lock_file($file);
233 while (<$src>) {
234 my $result = $fn->($_);
235 push(@results, $result) if $result;
238 close $dst or die "$file(l) close failed: $!";
239 close $src;
241 unlock_file($file, 1);
242 return @results;
245 sub filedb_grep {
246 my ($file, $fn) = @_;
247 my @results = ();
249 open my $src, '<', $file or die "$file open for reading failed: $!";
251 while (<$src>) {
252 my $result = $fn->($_);
253 push(@results, $result) if $result;
256 close $src;
258 return @results;
261 sub valid_email {
262 my $email = shift;
263 defined($email) or $email = '';
264 return $email =~ /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+$/;
267 sub valid_email_multi {
268 my $email_multi = shift;
269 defined($email_multi) or $email_multi = '';
270 # More relaxed, we just want to avoid too dangerous characters.
271 return $email_multi =~ /^[a-zA-Z0-9+._, @-]+$/;
274 sub valid_web_url {
275 my $url = shift;
276 defined($url) or $url = '';
277 return $url =~
278 /^https?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~:?&=;-]*)?(#[a-zA-Z0-9._-]+)?$/;
281 sub valid_repo_url {
282 my $url = shift || '';
283 # Currently neither username nor password is allowed in the URL and IPv6
284 # literal addresses are not accepted either.
285 $Girocco::Config::mirror_svn &&
286 $url =~ /^svn(\+https?)?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
287 and return 1;
288 $Girocco::Config::mirror_darcs &&
289 $url =~ /^darcs:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
290 and return 1;
291 $Girocco::Config::mirror_bzr &&
292 $url =~ /^bzr:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
293 and return 1;
294 $Girocco::Config::mirror_hg &&
295 $url =~ /^hg\+https?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
296 and return 1;
297 return $url =~ /^(https?|git):\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/;
300 sub extract_url_hostname {
301 my $url = shift || '';
302 if ($url =~ m,^bzr://,) {
303 $url =~ s,^bzr://,,;
304 return 'launchpad.net' if $url =~ /^lp:/;
306 return undef unless $url =~ m,^[A-Za-z0-9+.-]+://[^/],;
307 $url =~ s,^[A-Za-z0-9+.-]+://,,;
308 $url =~ s,^([^/]+).*$,$1,;
309 $url =~ s/:[0-9]*$//;
310 $url =~ s/^[^@]*[@]//;
311 return $url ? $url : undef;
314 # See these RFCs:
315 # RFC 1034 section 3.5
316 # RFC 1123 section 2.1
317 # RFC 1738 section 3.1
318 # RFC 3986 section 3.2.2
319 sub is_dns_hostname {
320 my $host = shift;
321 defined($host) or $host = '';
322 return 0 if $host eq '' || $host =~ /\s/;
323 # first remove a trailing '.'
324 $host =~ s/\.$//;
325 return 0 if length($host) > 255;
326 my $octet = '(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])';
327 return 0 if $host =~ /^$octet\.$octet\.$octet\.$octet$/o;
328 my @labels = split(/[.]/, $host, -1);
329 return 0 unless @labels && @labels >= $Girocco::Config::min_dns_labels;
330 # now check each label
331 foreach my $label (@labels) {
332 return 0 unless length($label) > 0 && length($label) <= 63;
333 return 0 unless $label =~ /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
335 return 1;
338 sub is_our_hostname {
339 my $test = shift || '';
340 $test =~ s/\.$//;
341 my %names = ();
342 my @urls = (
343 $Girocco::Config::gitweburl,
344 $Girocco::Config::gitwebfiles,
345 $Girocco::Config::webadmurl,
346 $Girocco::Config::bundlesurl,
347 $Girocco::Config::htmlurl,
348 $Girocco::Config::httppullurl,
349 $Girocco::Config::httpbundleurl,
350 $Girocco::Config::httpspushurl,
351 $Girocco::Config::gitpullurl,
352 $Girocco::Config::pushurl
354 foreach my $url (@urls) {
355 if ($url) {
356 my $host = extract_url_hostname($url);
357 if (defined($host)) {
358 $host =~ s/\.$//;
359 $names{lc($host)} = 1;
363 return $names{lc($test)} ? 1 : 0;
366 my %_badtags;
367 BEGIN {
368 %_badtags = (
369 about=>1, after=>1, all=>1, also=>1, an=>1, and=>1, another=>1, any=>1,
370 are=>1, as=>1, at=>1, be=>1, because=>1, been=>1, before=>1, being=>1,
371 between=>1, both=>1, but=>1, by=>1, came=>1, can=>1, come=>1, could=>1,
372 did=>1, do=>1, each=>1, for=>1, from=>1, get=>1, got=>1, had=>1, has=>1,
373 have=>1, he=>1, her=>1, here=>1, him=>1, himself=>1, his=>1, how=>1,
374 if=>1, in=>1, into=>1, is=>1, it=>1, like=>1, make=>1, many=>1, me=>1,
375 might=>1, more=>1, most=>1, much=>1, must=>1, my=>1, never=>1, now=>1,
376 of=>1, on=>1, only=>1, or=>1, other=>1, our=>1, out=>1, over=>1,
377 said=>1, same=>1, see=>1, should=>1, since=>1, some=>1, still=>1,
378 such=>1, take=>1, than=>1, that=>1, the=>1, their=>1, them=>1, then=>1,
379 there=>1, these=>1, they=>1, this=>1, those=>1, through=>1, to=>1,
380 too=>1, under=>1, up=>1, very=>1, was=>1, way=>1, we=>1, well=>1,
381 were=>1, what=>1, where=>1, which=>1, while=>1, who=>1, with=>1,
382 would=>1, you=>1, your=>1
386 # A valid tag must only have [a-zA-Z0-9:.+#_-] characters, must start with a
387 # letter, must not be a noise word and except for 'C' must be more than one
388 # character long and no more than 32 characters long.
389 sub valid_tag {
390 local $_ = $_[0] || '';
391 return 1 if $_ eq 'C'; # Currently only allowed single letter tag
392 return 0 unless /^[a-zA-Z][a-zA-Z0-9:.+#_-]+$/;
393 return 0 if $_badtags{lc($_)};
394 return length($_) <= 32 ? 1 : 0;
397 # If the passed in argument looks like a URL, return only the stuff up through
398 # the host:port part otherwise return the entire argument.
399 sub url_base {
400 my $url = shift || '';
401 # See RFC 3968
402 $url = $1.$2.$3.$4 if $url =~ m,^( [A-Za-z][A-Za-z0-9+.-]*: ) # scheme
403 ( // ) # // separator
404 ((?:[^\@]+\@)?) # optional userinfo
405 ( [^/?#]+ ) # host and port
406 (?:[/?#].*)?$,x; # path and optional query string and/or anchor
407 return $url;
410 # If the passed in argument looks like a URL, return only the stuff following
411 # the host:port part otherwise return the entire argument.
412 # If the optional second argument is true, the returned value will have '/'
413 # appended if it does not already end in '/'.
414 sub url_path {
415 my $url = shift || '';
416 my $add_slash = shift || 0;
417 # See RFC 3968
418 $url = $1 if $url =~ m,^(?: [A-Za-z][A-Za-z0-9+.-]*: ) # scheme
419 (?: // ) # // separator
420 (?: [^\@]+\@ )? # optional userinfo
421 (?: [^/?#]+ ) # host and port
422 ((?:[/?#].*)?)$,x; # path and optional query string and/or anchor
423 $url .= '/' if $add_slash && $url !~ m|/$|;
424 return $url;
427 # If both SERVER_NAME and SERVER_PORT are set pass the argument through url_path
428 # and then prefix it with the appropriate scheme (HTTPS=?on), host and port and
429 # return it. If a something that doesn't look like it could be the start of a
430 # URL path comes back from url_path or SERVER_NAME is a link-local IPv6 address
431 # then just return the argument unchanged.
432 sub url_server {
433 my $url = shift || '';
434 my $path = url_path($url);
435 return $url unless $path eq '' || $path =~ m|^[/?#]|;
436 return $url unless $ENV{'SERVER_NAME'} && $ENV{'SERVER_PORT'} &&
437 $ENV{'SERVER_PORT'} =~ /^[1-9][0-9]{0,4}$/;
438 return $url if $ENV{'SERVER_NAME'} =~ /^[[]?fe80:/i;
439 my $server = $ENV{'SERVER_NAME'};
440 # Deal with Apache bug where IPv6 literal server names do not include
441 # the required surrounding '[' and ']' characters
442 $server = '[' . $server . ']' if $server =~ /:/ && $server !~ /^[[]/;
443 my $ishttps = $ENV{'HTTPS'} && $ENV{'HTTPS'} =~ /^on$/i;
444 my $portnum = 0 + $ENV{'SERVER_PORT'};
445 my $port = '';
446 if (($ishttps && $portnum != 443) || (!$ishttps && $portnum != 80)) {
447 $port = ':' . $portnum;
449 return 'http' . ($ishttps ? 's' : '') . '://' . $server . $port . $path;
452 # Returns the number rounded to the nearest tenths. The ".d" part will be
453 # excluded if it's ".0" unless the optional second argument is true
454 sub _tenths {
455 my $v = shift;
456 my $use0 = shift;
457 $v *= 10;
458 $v += 0.5;
459 $v = int($v);
460 return '' . int($v/10) unless $v % 10 || $use0;
461 return '' . int($v/10) . '.' . ($v%10);
464 # Returns a human-readable size string (e.g. '1.5 MiB') for the value
465 # (in bytes) passed in. Returns '0' for undefined or 0 or not all digits.
466 # Otherwise returns '1 KiB' for < 1024, or else a number rounded to the
467 # nearest tenths of a KiB, MiB or GiB.
468 sub human_size {
469 my $v = shift || 0;
470 return "0" unless $v && $v =~ /^\d+$/;
471 return "1 KiB" unless $v > 1024;
472 $v /= 1024;
473 return _tenths($v) . " KiB" if $v < 1024;
474 $v /= 1024;
475 return _tenths($v) . " MiB" if $v < 1024;
476 $v /= 1024;
477 return _tenths($v) . " GiB";
480 sub _escapeHTML {
481 my $str = shift;
482 $str =~ s/\&/\&amp;/gs;
483 $str =~ s/\</\&lt;/gs;
484 $str =~ s/\>/\&gt;/gs;
485 $str =~ s/\"/\&quot;/gs; #"
486 return $str;
489 # create relative time string from passed in age in seconds
490 sub _rel_age {
491 my $age = shift;
492 my $age_str;
494 if ($age > 60*60*24*365*2) {
495 $age_str = (int $age/60/60/24/365);
496 $age_str .= " years ago";
497 } elsif ($age > 60*60*24*(365/12)*2) {
498 $age_str = int $age/60/60/24/(365/12);
499 $age_str .= " months ago";
500 } elsif ($age > 60*60*24*7*2) {
501 $age_str = int $age/60/60/24/7;
502 $age_str .= " weeks ago";
503 } elsif ($age > 60*60*24*2) {
504 $age_str = int $age/60/60/24;
505 $age_str .= " days ago";
506 } elsif ($age > 60*60*2) {
507 $age_str = int $age/60/60;
508 $age_str .= " hours ago";
509 } elsif ($age > 60*2) {
510 $age_str = int $age/60;
511 $age_str .= " mins ago";
512 } elsif ($age > 2) {
513 $age_str = int $age;
514 $age_str .= " secs ago";
515 } elsif ($age >= 0) {
516 $age_str = "right now";
517 } else {
518 $age_str = "future time";
520 return $age_str;
523 # create relative time string from passed in idle in seconds
524 sub _rel_idle {
525 my $idle_str = _rel_age(shift);
526 $idle_str =~ s/ ago//;
527 $idle_str = "not at all" if $idle_str eq "right now";
528 return $idle_str;
531 sub _strftime {
532 use POSIX qw(strftime);
533 my ($fmt, $secs, $zonesecs) = @_;
534 my ($S,$M,$H,$d,$m,$y) = gmtime($secs + $zonesecs);
535 $zonesecs = int($zonesecs / 60);
536 $fmt =~ s/%z/\$z/g;
537 my $ans = strftime($fmt, $S, $M, $H, $d, $m, $y, -1, -1, -1);
538 my $z;
539 if ($zonesecs < 0) {
540 $z = "-";
541 $zonesecs = -$zonesecs;
542 } else {
543 $z = "+";
545 $z .= sprintf("%02d%02d", int($zonesecs/60), $zonesecs % 60);
546 $ans =~ s/\$z/$z/g;
547 return $ans;
550 # Take a list of project names and produce a nicely formated table that
551 # includes owner links and descriptions. If the list is empty returns ''.
552 # The first argument may be a hash ref that contains options. The following
553 # options are available:
554 # target -- sets the target value of the owner link
555 # emptyok -- if true returns an empty table rather than ''
556 # sizecol -- if true include a human-readable size column
557 # typecol -- if true include type column with hover info
558 # changed -- if true include a changed and idle column
559 sub projects_html_list {
560 my $options = {};
561 if (defined($_[0]) && ref($_[0]) eq 'HASH') {
562 $options = shift;
564 return '' unless @_ || (defined($options->{emptyok}) && $options->{emptyok});
565 require Girocco::Project;
566 my $count = 0;
567 my $target = '';
568 $target = " target=\""._escapeHTML($options->{target})."\""
569 if defined($options->{target});
570 my $withsize = defined($options->{sizecol}) && $options->{sizecol};
571 my $withtype = defined($options->{typecol}) && $options->{typecol};
572 my $withchanged = defined($options->{changed}) && $options->{changed};
573 my $sizehead = '';
574 $sizehead = substr(<<EOT, 0, -1) if $withsize;
575 <th class="sizecol"><span class="hover">Size<span><span class="head">Size</span
576 />Fork size excludes objects borrowed from the parent.</span></span></th
579 my $typehead = '';
580 $typehead = '<th>Type</th>' if $withtype;
581 my $chghead = '';
582 $chghead = substr(<<EOT, 0, -1) if $withchanged;
583 <th><span class="hover">Changed<span><span class="head">Changed</span
584 />The last time a ref change was received by this site.</span></span></th
585 ><th><span class="hover">Idle<span><span class="head">Idle</span
586 />The most recent committer time in <i>refs/heads</i>.</span></span></th
589 my $html = <<EOT;
590 <table class='projectlist'><tr><th>Project</th>$sizehead$typehead$chghead<th class="desc">Description</th></tr>
592 my $trclass = ' class="odd"';
593 foreach (sort({lc($a) cmp lc($b)} @_)) {
594 if (Girocco::Project::does_exist($_, 1)) {
595 my $proj = Girocco::Project->load($_);
596 my $projname = $proj->{name}.".git";
597 my $projdesc = $proj->{desc}||'';
598 utf8::decode($projdesc) if utf8::valid($projdesc);
599 my $sizecol = '';
600 if ($withsize) {
601 my $psize = $proj->{reposizek};
602 $psize = undef unless defined($psize) && $psize =~ /^\d+$/;
603 $psize = 0 if !defined($psize) && $proj->is_empty;
604 if (!defined($psize)) {
605 $psize = 'unknown';
606 } elsif (!$psize) {
607 $psize = 'empty';
608 } else {
609 $psize = human_size($psize * 1024);
610 $psize =~ s/ /\&#160;/g;
612 $sizecol = '<td class="sizecol">'.$psize.'</td>';
614 my $typecol = '';
615 if ($withtype) {
616 if ($proj->{mirror}) {
617 $typecol = substr(<<EOT, 0, -1);
618 <td class="type"><span class="hover">mirror<span class="nowrap">@{[_escapeHTML($proj->{url})]}</span></span></td>
620 } else {
621 my $users = @{$proj->{users}};
622 $users .= ' user';
623 $users .= 's' unless @{$proj->{users}} == 1;
624 my $userlist = join(', ', sort({lc($a) cmp lc($b)} @{$proj->{users}}));
625 my $spncls = length($userlist) > 25 ? '' : ' class="nowrap"';
626 $typecol = $userlist ? substr(<<EOT, 0, -1) : substr(<<EOT, 0, -1);
627 <td class="type"><span class="hover">$users<span$spncls>$userlist</span></span></td>
629 <td class="type">$users</td>
633 my $changecol = '';
634 if ($withchanged) {
635 my $rel = '';
636 my $changetime = $proj->{lastchange};
637 if ($changetime) {
638 $rel = "<span class=\"hover\">" .
639 _rel_age(time - parse_rfc2822_date($changetime)) .
640 "<span class=\"nowrap\">$changetime</span></span>";
641 } else {
642 $rel = "no commits";
644 $changecol = substr(<<EOT, 0, -1);
645 <td class="change">$rel</td>
647 my $idletime = $proj->{lastactivity};
648 my ($idlesecs, $tz);
649 $idlesecs = parse_any_date($idletime, \$tz) if $idletime;
650 if ($idlesecs) {
651 my $idle2822 = _strftime("%a, %d %b %Y %T %z", $idlesecs, $tz);
652 $rel = "<span class=\"hover\">" .
653 _rel_idle(time - $idlesecs) .
654 "<span class=\"nowrap\">$idle2822</span></span>";
655 } else {
656 $rel = "no commits";
658 $changecol .= substr(<<EOT, 0, -1);
659 <td class="idle">$rel</td>
662 $html .= <<EOT;
663 <tr$trclass><td><a href="@{[url_path($Girocco::Config::gitweburl)]}/$projname"$target
664 >@{[_escapeHTML($projname)]}</td>$sizecol$typecol$changecol<td>@{[_escapeHTML($projdesc)]}</td></tr>
666 $trclass = $trclass ? '' : ' class="odd"';
667 ++$count;
670 $html .= <<EOT;
671 </table>
673 return ($count || (defined($options->{emptyok}) && $options->{emptyok})) ? $html : '';
676 my %_month_names;
677 BEGIN {
678 %_month_names = (
679 jan => 0, feb => 1, mar => 2, apr => 3, may => 4, jun => 5,
680 jul => 6, aug => 7, sep => 8, oct => 9, nov => 10, dec => 11
684 # Should be in "date '+%a, %d %b %Y %T %z'" format as saved to lastgc, lastrefresh and lastchange
685 # The leading "%a, " is optional, returns undef if unrecognized date. This is also known as
686 # RFC 2822 date format and git's '%cD', '%aD' and --date=rfc2822 format.
687 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
688 sub parse_rfc2822_date {
689 my $dstr = shift || '';
690 my $tzoff = shift || '';
691 $dstr = $1 if $dstr =~/^[^\s]+,\s*(.*)$/;
692 return undef unless $dstr =~
693 /^\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s+([+-]\d{4})\s*$/;
694 my ($d,$b,$Y,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7);
695 my $m = $_month_names{lc($b)};
696 return undef unless defined($m);
697 my $seconds = timegm(0+$S, 0+$M, 0+$H, 0+$d, 0+$m, $Y-1900);
698 my $offset = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
699 $offset = -$offset if substr($z,0,1) eq '-';
700 $$tzoff = $offset if ref($tzoff) eq 'SCALAR';
701 return $seconds - $offset;
704 # Will parse any supported date format. Actually there are three formats
705 # currently supported:
706 # 1. RFC 2822 (uses parse_rfc2822_date)
707 # 2. RFC 3339 / ISO 8601 (T may be ' ' or '_', 'Z' is optional, ':' optional in TZ)
708 # 3. Same as #2 except no colons or hyphens allowed and hours MUST be 2 digits
709 # 4. unix seconds since epoch with optional +/- trailing TZ (may not have a ':')
710 # Returns undef if unsupported date.
711 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
712 sub parse_any_date {
713 my $dstr = shift || '';
714 my $tzoff = shift || '';
715 if ($dstr =~ /^\s*([-+]?\d+)(?:\s+([-+]\d{4}))?\s*$/) {
716 # Unix timestamp
717 my $ts = 0 + $1;
718 my $off = 0;
719 if ($2) {
720 my $z = $2;
721 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
722 $off = -$off if substr($z,0,1) eq '-';
724 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
725 return $ts;
727 if ($dstr =~ /^\s*(\d{4})-(\d{2})-(\d{2})[Tt _](\d{1,2}):(\d{2}):(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{1,2}:?\d{2})))?\s*$/ ||
728 $dstr =~ /^\s*(\d{4})(\d{2})(\d{2})[Tt _](\d{2})(\d{2})(\d{2})(?:[ _]?([Zz]|(?:[-+]\d{2}\d{2})))?\s*$/) {
729 my ($Y,$m,$d,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7||'');
730 my $seconds = timegm(0+$S, 0+$M, 0+$H, 0+$d, $m-1, $Y-1900);
731 defined($z) && $z ne '' or $z = 'Z';
732 $z =~ s/://;
733 substr($z,1,0) = '0' if length($z) == 4;
734 my $off = 0;
735 if (uc($z) ne 'Z') {
736 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
737 $off = -$off if substr($z,0,1) eq '-';
739 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
740 return $seconds - $off;
742 return parse_rfc2822_date($dstr, $tzoff);
745 # Input is a number such as a minute interval
746 # Return value is a random number between the input and 1.25*input
747 # This can be used to randomize the update and gc operations a bit to avoid
748 # having them all end up all clustered together
749 sub rand_adjust {
750 my $input = shift || 0;
751 return $input unless $input;
752 return $input + int(rand(0.25 * $input));
755 # Open a pipe to a new sendmail process. The '-i' option is always passed to
756 # the new process followed by any addtional arguments passed in. Note that
757 # the sendmail process is only expected to understand the '-i', '-t' and '-f'
758 # options. Using any other options via this function is not guaranteed to work.
759 # A list of recipients may follow the options. Combining a list of recipients
760 # with the '-t' option is not recommended.
761 sub sendmail_pipe {
762 return undef unless @_;
763 die "\$Girocco::Config::sendmail_bin is unset or not executable!\n"
764 unless $Girocco::Config::sendmail_bin && -x $Girocco::Config::sendmail_bin;
765 my $result = open(my $pipe, '|-', $Girocco::Config::sendmail_bin, '-i', @_);
766 return $result ? $pipe : undef;
769 # Open a pipe that works similarly to a mailer such as /usr/bin/mail in that
770 # if the first argument is '-s', a subject line will be automatically added
771 # (using the second argument as the subject). Any remaining arguments are
772 # expected to be recipient addresses that will be added to an explicit To:
773 # line as well as passed on to sendmail_pipe. In addition an
774 # "Auto-Submitted: auto-generated" header is always added as well as a suitable
775 # "From:" header.
776 sub mailer_pipe {
777 my $subject = undef;
778 if (@_ >= 2 && $_[0] eq '-s') {
779 shift;
780 $subject = shift;
782 my $tolist = join(", ", @_);
783 unshift(@_, '-f', $Girocco::Config::sender) if $Girocco::Config::sender;
784 my $pipe = sendmail_pipe(@_);
785 if ($pipe) {
786 print $pipe "From: \"$Girocco::Config::name\" ",
787 "($Girocco::Config::title) ",
788 "<$Girocco::Config::admin>\n";
789 print $pipe "To: $tolist\n";
790 print $pipe "Subject: $subject\n" if defined($subject);
791 print $pipe "MIME-Version: 1.0\n";
792 print $pipe "Content-Type: text/plain; charset=utf-8\n";
793 print $pipe "Content-Transfer-Encoding: 8bit\n";
794 print $pipe "Auto-Submitted: auto-generated\n";
795 print $pipe "\n";
797 return $pipe;
800 sub _goodval {
801 my $val = shift;
802 return undef unless defined($val);
803 $val =~ s/[\r\n]+$//s;
804 return undef unless $val =~ /^\d+$/;
805 $val = 0 + $val;
806 return undef unless $val >= 1;
807 return $val;
810 # Returns the number of "online" cpus or undef if undetermined
811 sub online_cpus {
812 my @confcpus = $^O eq "linux" ?
813 qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN) :
814 qw(NPROCESSORS_ONLN _NPROCESSORS_ONLN) ;
815 my $cpus = _goodval(get_cmd('getconf', $confcpus[0]));
816 return $cpus if $cpus;
817 $cpus = _goodval(get_cmd('getconf', $confcpus[1]));
818 return $cpus if $cpus;
819 if ($^O ne "linux") {
820 my @sysctls = qw(hw.ncpu);
821 unshift(@sysctls, qw(hw.availcpu)) if $^O eq "darwin";
822 foreach my $mib (@sysctls) {
823 $cpus = _goodval(get_cmd('sysctl', '-n', $mib));
824 return $cpus if $cpus;
827 return undef;
830 # Returns the system page size in bytes or undef if undetermined
831 # This should never fail on a POSIX system
832 sub sys_pagesize {
833 use POSIX ":unistd_h";
834 my $pagesize = sysconf(_SC_PAGESIZE);
835 return undef unless defined($pagesize) && $pagesize =~ /^\d+$/;
836 $pagesize = 0 + $pagesize;
837 return undef unless $pagesize >= 256;
838 return $pagesize;
841 # Returns the amount of available physical memory in bytes
842 # This may differ from the actual amount of physical memory installed
843 # Returns undef if this cannot be determined
844 sub sys_memsize {
845 my $pagesize = sys_pagesize;
846 if ($pagesize && $^O eq "linux") {
847 my $pages = _goodval(get_cmd('getconf', '_PHYS_PAGES'));
848 return $pagesize * $pages if $pages;
850 if ($^O ne "linux") {
851 my @sysctls = qw(hw.physmem64);
852 unshift(@sysctls, qw(hw.memsize)) if $^O eq "darwin";
853 foreach my $mib (@sysctls) {
854 my $memsize = _goodval(get_cmd('sysctl', '-n', $mib));
855 return $memsize if $memsize;
857 my $memsize32 = _goodval(get_cmd('sysctl', '-n', 'hw.physmem'));
858 return $memsize32 if $memsize32 && $memsize32 <= 2147483647;
859 if ($pagesize) {
860 my $pages = _goodval(get_cmd('sysctl', '-n', 'hw.availpages'));
861 return $pagesize * $pages if $pages;
863 return 2147483647 + 1 if $memsize32;
865 return undef;
868 sub _max_conf_window_bytes {
869 return undef unless defined($Girocco::Config::max_gc_window_memory_size);
870 return undef unless
871 $Girocco::Config::max_gc_window_memory_size =~ /^(\d+)([kKmMgG]?)$/;
872 my ($val, $suffix) = (0+$1, lc($2));
873 $val *= 1024 if $suffix eq 'k';
874 $val *= 1024 * 1024 if $suffix eq 'm';
875 $val *= 1024 * 1024 * 1024 if $suffix eq 'g';
876 return $val;
879 # Return the value to pass to --window-memory= for git repack
880 # If the system memory or number of CPUs cannot be determined, returns "1g"
881 # Otherwise returns half the available memory divided by the number of CPUs
882 # but never more than 1 gigabyte or max_gc_window_memory_size.
883 sub calc_windowmemory {
884 my $cpus = online_cpus;
885 my $memsize = sys_memsize;
886 my $max = 1024 * 1024 * 1024;
887 if ($cpus && $memsize) {
888 $max = int($memsize / 2 / $cpus);
889 $max = 1024 * 1024 * 1024 if $max >= 1024 * 1024 * 1024;
891 my $maxconf = _max_conf_window_bytes;
892 $max = $maxconf if defined($maxconf) && $maxconf && $max > $maxconf;
893 return $max if $max % 1024;
894 $max /= 1024;
895 return "${max}k" if $max % 1024;
896 $max /= 1024;
897 return "${max}m" if $max % 1024;
898 $max /= 1024;
899 return "${max}g";
902 # $1 => thing to test
903 # $2 => optional directory, if given and -e "$2/$1$3", then return false
904 # $3 => optional, defaults to ''
905 sub has_reserved_suffix {
906 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
907 my ($name, $dir, $ext) = @_;
908 $ext = '' unless defined $ext;
909 return 0 unless defined $name && $name =~ /\.([^.]+)$/;
910 return 0 unless exists $Girocco::Config::reserved_suffixes{lc($1)};
911 return 0 if defined $dir && -e "$dir/$name$ext";
912 return 1;