gc.sh: include phase timestamps with show_progress=1
[girocco/readme.git] / Girocco / Util.pm
blobe712783436ce595578e4155317665ff6bab64dc4
1 package Girocco::Util;
3 use 5.008;
4 use strict;
5 use warnings;
7 use Girocco::Config;
8 use Time::Local;
9 use Encode;
11 BEGIN {
12 use base qw(Exporter);
13 our @EXPORT = qw(get_git scrypt jailed_file sendmail_pipe mailer_pipe
14 lock_file unlock_file valid_tag rand_adjust
15 filedb_atomic_append filedb_atomic_edit filedb_grep
16 filedb_atomic_grep valid_email valid_email_multi
17 valid_repo_url valid_web_url url_base url_path url_server
18 projects_html_list parse_rfc2822_date parse_any_date
19 extract_url_hostname is_dns_hostname is_our_hostname
20 get_cmd online_cpus sys_pagesize sys_memsize
21 calc_windowmemory to_utf8 capture_command human_size
22 calc_bigfilethreshold has_reserved_suffix
23 noFatalsToBrowser calc_redeltathreshold
24 clean_email_multi read_HEAD_symref read_config_file
25 read_config_file_hash is_git_dir git_bool);
28 my $encoder;
29 BEGIN {
30 $encoder = Encode::find_encoding('Windows-1252') ||
31 Encode::find_encoding('ISO-8859-1') or
32 die "failed to load ISO-8859-1 encoder\n";
35 sub to_utf8($;$) {
36 my ($str, $encode) = @_;
37 return undef unless defined $str;
38 my $ans;
39 if (Encode::is_utf8($str) || utf8::decode($str)) {
40 $ans = $str;
41 } else {
42 $ans = $encoder->decode($str, Encode::FB_DEFAULT);
44 utf8::encode($ans) if $encode;
45 return $ans;
48 BEGIN {require "Girocco/extra/capture_command.pl"}
50 # Return the entire output sent to stdout from running a command
51 # Any output the command sends to stderr is discarded
52 # Returns undef if there was an error running the command (see $!)
53 sub get_cmd {
54 my ($status, $result) = capture_command(1, undef, @_);
55 return defined($status) && $status == 0 ? $result : undef;
58 # Same as get_cmd except configured git binary is automatically provided
59 # as the first argument to get_cmd
60 sub get_git {
61 return get_cmd($Girocco::Config::git_bin, @_);
64 sub scrypt {
65 my ($pwd) = @_;
66 crypt($pwd||'', join ('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]));
69 sub jailed_file {
70 my ($filename) = @_;
71 $filename =~ s,^/,,;
72 $Girocco::Config::chroot."/$filename";
75 sub lock_file {
76 my ($path) = @_;
78 $path .= '.lock';
80 use Errno qw(EEXIST);
81 use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
82 use IO::Handle;
83 my $handle = new IO::Handle;
85 unless (sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
86 my $cnt = 0;
87 while (not sysopen($handle, $path, O_WRONLY|O_CREAT|O_EXCL)) {
88 ($! == EEXIST) or die "$path open failed: $!";
89 ($cnt++ < 16) or die "$path open failed: cannot open lockfile";
90 sleep(1);
93 # XXX: filedb-specific
94 chmod 0664, $path or die "$path g+w failed: $!";
96 $handle;
99 sub _is_passwd_file {
100 return defined($_[0]) && $_[0] eq jailed_file('/etc/passwd');
103 sub _run_update_pwd_db {
104 my ($path, $updatearg) = @_;
105 my @cmd = ($Girocco::Config::basedir.'/bin/update-pwd-db', "$path");
106 push(@cmd, $updatearg) if $updatearg;
107 system(@cmd) == 0 or die "update-pwd-db failed: $?";
110 sub unlock_file {
111 my ($path, $noreplace, $updatearg) = @_;
113 if (!$noreplace) {
114 _run_update_pwd_db("$path.lock", $updatearg)
115 if $Girocco::Config::update_pwd_db && _is_passwd_file($path);
116 rename "$path.lock", $path or die "$path unlock failed: $!";
117 } else {
118 unlink "$path.lock" or die "$path unlock failed: $!";
122 sub filedb_atomic_append {
123 my ($file, $line, $updatearg) = @_;
124 my $id = 65536;
126 open my $src, '<', $file or die "$file open for reading failed: $!";
127 my $dst = lock_file($file);
129 while (<$src>) {
130 my $aid = (split /:/)[2];
131 $id = $aid + 1 if ($aid >= $id);
133 print $dst $_ or die "$file(l) write failed: $!";
136 $line =~ s/\\i/$id/g;
137 print $dst "$line\n" or die "$file(l) write failed: $!";
139 close $dst or die "$file(l) close failed: $!";
140 close $src;
142 unlock_file($file, 0, $updatearg);
144 $id;
147 sub filedb_atomic_edit {
148 my ($file, $fn, $updatearg) = @_;
150 open my $src, '<', $file or die "$file open for reading failed: $!";
151 my $dst = lock_file($file);
153 while (<$src>) {
154 print $dst $fn->($_) or die "$file(l) write failed: $!";
157 close $dst or die "$file(l) close failed: $!";
158 close $src;
160 unlock_file($file, 0, $updatearg);
163 sub filedb_atomic_grep {
164 my ($file, $fn) = @_;
165 my @results = ();
167 open my $src, '<', $file or die "$file open for reading failed: $!";
168 my $dst = lock_file($file);
170 while (<$src>) {
171 my $result = $fn->($_);
172 push(@results, $result) if $result;
175 close $dst or die "$file(l) close failed: $!";
176 close $src;
178 unlock_file($file, 1);
179 return @results;
182 sub filedb_grep {
183 my ($file, $fn) = @_;
184 my @results = ();
186 open my $src, '<', $file or die "$file open for reading failed: $!";
188 while (<$src>) {
189 my $result = $fn->($_);
190 push(@results, $result) if $result;
193 close $src;
195 return @results;
198 sub valid_email {
199 my $email = shift;
200 defined($email) or $email = '';
201 return $email =~ /^[a-zA-Z0-9+._-]+@[a-zA-Z0-9.-]+$/;
204 sub clean_email_multi {
205 my $input = shift;
206 defined($input) or $input = '';
207 $input =~ s/^\s+//; $input =~ s/\s+$//;
208 my %seen = ();
209 my @newlist = ();
210 foreach (split(/\s*,\s*/, $input)) {
211 next if $_ eq "";
212 $seen{lc($_)} = 1, push(@newlist, $_) unless $seen{lc($_)};
214 return join(",", @newlist);
217 sub valid_email_multi {
218 # each email address must be a valid_email but we silently
219 # ignore extra spaces at the beginning/end and around any comma(s)
220 foreach (split(/,/, clean_email_multi(shift))) {
221 return 0 unless valid_email($_);
223 return 1;
226 sub valid_web_url {
227 my $url = shift;
228 defined($url) or $url = '';
229 return $url =~
230 /^https?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~:?&=;-]*)?(#[a-zA-Z0-9._-]+)?$/;
233 sub valid_repo_url {
234 my $url = shift || '';
235 # Currently neither username nor password is allowed in the URL and IPv6
236 # literal addresses are not accepted either.
237 $Girocco::Config::mirror_svn &&
238 $url =~ /^svn(\+https?)?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
239 and return 1;
240 $Girocco::Config::mirror_darcs &&
241 $url =~ /^darcs:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
242 and return 1;
243 $Girocco::Config::mirror_bzr &&
244 $url =~ /^bzr:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
245 and return 1;
246 $Girocco::Config::mirror_hg &&
247 $url =~ /^hg\+https?:\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/os
248 and return 1;
249 return $url =~ /^(https?|git):\/\/[a-zA-Z0-9.:-]+(\/[_\%a-zA-Z0-9.\/~-]*)?$/;
252 sub extract_url_hostname {
253 my $url = shift || '';
254 if ($url =~ m,^bzr://,) {
255 $url =~ s,^bzr://,,;
256 return 'launchpad.net' if $url =~ /^lp:/;
258 return undef unless $url =~ m,^[A-Za-z0-9+.-]+://[^/],;
259 $url =~ s,^[A-Za-z0-9+.-]+://,,;
260 $url =~ s,^([^/]+).*$,$1,;
261 $url =~ s/:[0-9]*$//;
262 $url =~ s/^[^\@]*[\@]//;
263 return $url ? $url : undef;
266 # See these RFCs:
267 # RFC 1034 section 3.5
268 # RFC 1123 section 2.1
269 # RFC 1738 section 3.1
270 # RFC 2606 sections 2 & 3
271 # RFC 3986 section 3.2.2
272 sub is_dns_hostname {
273 my $host = shift;
274 defined($host) or $host = '';
275 return 0 if $host eq '' || $host =~ /\s/;
276 # first remove a trailing '.'
277 $host =~ s/\.$//;
278 return 0 if length($host) > 255;
279 my $octet = '(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])';
280 return 0 if $host =~ /^$octet\.$octet\.$octet\.$octet$/o;
281 my @labels = split(/[.]/, $host, -1);
282 return 0 unless @labels && @labels >= $Girocco::Config::min_dns_labels;
283 # now check each label
284 foreach my $label (@labels) {
285 return 0 unless length($label) > 0 && length($label) <= 63;
286 return 0 unless $label =~ /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
288 # disallow RFC 2606 names provided at least two labels are present
289 if (@labels >= 2) {
290 my $tld = lc($labels[-1]);
291 return 0 if
292 $tld eq 'test' ||
293 $tld eq 'example' ||
294 $tld eq 'invalid' ||
295 $tld eq 'localhost';
296 my $sld = lc($labels[-2]);
297 return 0 if $sld eq 'example' &&
298 ($tld eq 'com' || $tld eq 'net' || $tld eq 'org');
300 return 1;
303 sub is_our_hostname {
304 my $test = shift || '';
305 $test =~ s/\.$//;
306 my %names = ();
307 my @urls = (
308 $Girocco::Config::gitweburl,
309 $Girocco::Config::gitwebfiles,
310 $Girocco::Config::webadmurl,
311 $Girocco::Config::bundlesurl,
312 $Girocco::Config::htmlurl,
313 $Girocco::Config::httppullurl,
314 $Girocco::Config::httpbundleurl,
315 $Girocco::Config::httpspushurl,
316 $Girocco::Config::gitpullurl,
317 $Girocco::Config::pushurl
319 foreach my $url (@urls) {
320 if ($url) {
321 my $host = extract_url_hostname($url);
322 if (defined($host)) {
323 $host =~ s/\.$//;
324 $names{lc($host)} = 1;
328 return $names{lc($test)} ? 1 : 0;
331 my (%_oktags, %_badtags, %_canontags, $_canontagscreated, @_whitetags);
332 BEGIN {
333 # These are always okay (a "whitelist") even if they would
334 # otherwise not be allowed
335 @_whitetags = (qw(
336 .net 2d 3d 6502 68000 68008 68010 68020 68030 68040 68060
337 8086 80286 80386 80486 80586 c cc make www x
339 map({$_oktags{lc($_)}=1} @_whitetags, @Girocco::Config::allowed_tags);
340 # entries MUST be all lowercase to be effective
341 %_badtags = (
342 # These are "nonsense" or pointless tags
343 about=>1, after=>1, all=>1, also=>1, an=>1, and=>1, another=>1, any=>1,
344 are=>1, as=>1, at=>1, be=>1, because=>1, been=>1, before=>1, being=>1,
345 between=>1, both=>1, but=>1, by=>1, came=>1, can=>1, come=>1, could=>1,
346 did=>1, do=>1, each=>1, for=>1, from=>1, get=>1, got=>1, had=>1, has=>1,
347 have=>1, he=>1, her=>1, here=>1, him=>1, himself=>1, his=>1, how=>1,
348 if=>1, in=>1, into=>1, is=>1, it=>1, like=>1, make=>1, many=>1, me=>1,
349 might=>1, more=>1, most=>1, much=>1, must=>1, my=>1, never=>1, now=>1,
350 of=>1, oh=>1, on=>1, only=>1, or=>1, other=>1, our=>1, out=>1, over=>1,
351 said=>1, same=>1, see=>1, should=>1, since=>1, some=>1, still=>1,
352 such=>1, take=>1, than=>1, that=>1, the=>1, their=>1, them=>1, then=>1,
353 there=>1, these=>1, they=>1, this=>1, those=>1, through=>1, to=>1,
354 too=>1, under=>1, up=>1, very=>1, was=>1, way=>1, we=>1, well=>1,
355 were=>1, what=>1, where=>1, which=>1, while=>1, who=>1, with=>1,
356 would=>1, yea=>1, yeah=>1, you=>1, your=>1, yup=>1
358 # These are "offensive" tags with at least one letter escaped to
359 # avoid having this file trigger various safe-scan robots
360 $_badtags{"a\x73\x73"} = 1;
361 $_badtags{"a\x73\x73hole"} = 1;
362 $_badtags{"b\x30\x30b"} = 1;
363 $_badtags{"b\x30\x30bs"} = 1;
364 $_badtags{"b\x6f\x6fb"} = 1;
365 $_badtags{"b\x6f\x6fbs"} = 1;
366 $_badtags{"b\x75tt"} = 1;
367 $_badtags{"b\x75ttd\x69\x63k"} = 1;
368 $_badtags{"c\x6f\x63k"} = 1;
369 $_badtags{"c\x75\x6e\x74"} = 1;
370 $_badtags{"d\x69\x63k"} = 1;
371 $_badtags{"d\x69\x63kb\x75tt"} = 1;
372 $_badtags{"f\x75\x63k"} = 1;
373 $_badtags{"in\x63\x65st"} = 1;
374 $_badtags{"ph\x75\x63k"} = 1;
375 $_badtags{"p\x6f\x72n"} = 1;
376 $_badtags{"p\x6f\x72no"} = 1;
377 $_badtags{"p\x6f\x72nographic"} = 1;
378 $_badtags{"p\x72\x30n"} = 1;
379 $_badtags{"p\x72\x6fn"} = 1;
380 $_badtags{"r\x61\x70e"} = 1;
381 $_badtags{"s\x65\x78"} = 1;
382 map({$_badtags{lc($_)}=1} @Girocco::Config::blocked_tags);
385 # A valid tag must only have [a-zA-Z0-9:.+#_-] characters, must start with a
386 # letter, must not be a noise word, must be more than one character long,
387 # must not be a repeated letter and must be no more than 32 characters long.
388 # However, anything in %_oktags is explicitly allowed even if it otherwise
389 # would violate the rules (except that none of [,\s\\\/] are allowed in tags).
390 # Returns the canonical name for the tag if the tag is valid otherwise undef.
391 sub valid_tag {
392 local $_ = $_[0];
393 return undef unless defined($_) && $_ ne "" && !/[,\s\/\\]/;
394 my $fold = $Girocco::Config::foldtags;
395 if ($fold && !$_canontagscreated) {
396 local $_;
397 %_canontags = ();
398 $_canontags{lc($_)} = $_ foreach sort({$b cmp $a} @_whitetags, @Girocco::Config::allowed_tags);
399 $_canontagscreated = 1;
401 return $_canontags{lc($_)} if $fold && exists($_canontags{lc($_)});
402 return ($fold ? lc($_) : $_) if $_oktags{lc($_)};
403 return undef unless /^[a-zA-Z][a-zA-Z0-9:.+#_-]+$/;
404 return undef if $_badtags{lc($_)};
405 return undef if /^(.)\1+$/;
406 return length($_) <= 32 ? ($fold ? lc($_) : $_) : undef;
409 # If the passed in argument looks like a URL, return only the stuff up through
410 # the host:port part otherwise return the entire argument.
411 sub url_base {
412 my $url = shift || '';
413 # See RFC 3968
414 $url = $1.$2.$3.$4 if $url =~ m,^( [A-Za-z][A-Za-z0-9+.-]*: ) # scheme
415 ( // ) # // separator
416 ((?:[^\@]+\@)?) # optional userinfo
417 ( [^/?#]+ ) # host and port
418 (?:[/?#].*)?$,x; # path and optional query string and/or anchor
419 return $url;
422 # If the passed in argument looks like a URL, return only the stuff following
423 # the host:port part otherwise return the entire argument.
424 # If the optional second argument is true, the returned value will have '/'
425 # appended if it does not already end in '/'.
426 sub url_path {
427 my $url = shift || '';
428 my $add_slash = shift || 0;
429 # See RFC 3968
430 $url = $1 if $url =~ m,^(?: [A-Za-z][A-Za-z0-9+.-]*: ) # scheme
431 (?: // ) # // separator
432 (?: [^\@]+\@ )? # optional userinfo
433 (?: [^/?#]+ ) # host and port
434 ((?:[/?#].*)?)$,x; # path and optional query string and/or anchor
435 $url .= '/' if $add_slash && $url !~ m|/$|;
436 return $url;
439 # If both SERVER_NAME and SERVER_PORT are set pass the argument through url_path
440 # and then prefix it with the appropriate scheme (HTTPS=?on), host and port and
441 # return it. If a something that doesn't look like it could be the start of a
442 # URL path comes back from url_path or SERVER_NAME is a link-local IPv6 address
443 # then just return the argument unchanged.
444 sub url_server {
445 my $url = shift || '';
446 my $path = url_path($url);
447 return $url unless $path eq '' || $path =~ m|^[/?#]|;
448 return $url unless $ENV{'SERVER_NAME'} && $ENV{'SERVER_PORT'} &&
449 $ENV{'SERVER_PORT'} =~ /^[1-9][0-9]{0,4}$/;
450 return $url if $ENV{'SERVER_NAME'} =~ /^[[]?fe80:/i;
451 my $server = $ENV{'SERVER_NAME'};
452 # Deal with Apache bug where IPv6 literal server names do not include
453 # the required surrounding '[' and ']' characters
454 $server = '[' . $server . ']' if $server =~ /:/ && $server !~ /^[[]/;
455 my $ishttps = $ENV{'HTTPS'} && $ENV{'HTTPS'} =~ /^on$/i;
456 my $portnum = 0 + $ENV{'SERVER_PORT'};
457 my $port = '';
458 if (($ishttps && $portnum != 443) || (!$ishttps && $portnum != 80)) {
459 $port = ':' . $portnum;
461 return 'http' . ($ishttps ? 's' : '') . '://' . $server . $port . $path;
464 # Returns the number rounded to the nearest tenths. The ".d" part will be
465 # excluded if it's ".0" unless the optional second argument is true
466 sub _tenths {
467 my $v = shift;
468 my $use0 = shift;
469 $v *= 10;
470 $v += 0.5;
471 $v = int($v);
472 return '' . int($v/10) unless $v % 10 || $use0;
473 return '' . int($v/10) . '.' . ($v%10);
476 # Returns a human-readable size string (e.g. '1.5 MiB') for the value
477 # (in bytes) passed in. Returns '0' for undefined or 0 or not all digits.
478 # Otherwise returns '1 KiB' for < 1024, or else a number rounded to the
479 # nearest tenths of a KiB, MiB or GiB.
480 sub human_size {
481 my $v = shift || 0;
482 return "0" unless $v && $v =~ /^\d+$/;
483 return "1 KiB" unless $v > 1024;
484 $v /= 1024;
485 return _tenths($v) . " KiB" if $v < 1024;
486 $v /= 1024;
487 return _tenths($v) . " MiB" if $v < 1024;
488 $v /= 1024;
489 return _tenths($v) . " GiB";
492 sub _escapeHTML {
493 my $str = shift;
494 $str =~ s/\&/\&amp;/gs;
495 $str =~ s/\</\&lt;/gs;
496 $str =~ s/\>/\&gt;/gs;
497 $str =~ s/\"/\&quot;/gs; #"
498 return $str;
501 # create relative time string from passed in age in seconds
502 sub _rel_age {
503 my $age = shift;
504 my $age_str;
506 if ($age > 60*60*24*365*2) {
507 $age_str = (int $age/60/60/24/365);
508 $age_str .= " years ago";
509 } elsif ($age > 60*60*24*(365/12)*2) {
510 $age_str = int $age/60/60/24/(365/12);
511 $age_str .= " months ago";
512 } elsif ($age > 60*60*24*7*2) {
513 $age_str = int $age/60/60/24/7;
514 $age_str .= " weeks ago";
515 } elsif ($age > 60*60*24*2) {
516 $age_str = int $age/60/60/24;
517 $age_str .= " days ago";
518 } elsif ($age > 60*60*2) {
519 $age_str = int $age/60/60;
520 $age_str .= " hours ago";
521 } elsif ($age > 60*2) {
522 $age_str = int $age/60;
523 $age_str .= " mins ago";
524 } elsif ($age > 2) {
525 $age_str = int $age;
526 $age_str .= " secs ago";
527 } elsif ($age >= 0) {
528 $age_str = "right now";
529 } else {
530 $age_str = "future time";
532 return $age_str;
535 # create relative time string from passed in idle in seconds
536 sub _rel_idle {
537 my $idle_str = _rel_age(shift);
538 $idle_str =~ s/ ago//;
539 $idle_str = "not at all" if $idle_str eq "right now";
540 return $idle_str;
543 sub _strftime {
544 use POSIX qw(strftime);
545 my ($fmt, $secs, $zonesecs) = @_;
546 my ($S,$M,$H,$d,$m,$y) = gmtime($secs + $zonesecs);
547 $zonesecs = int($zonesecs / 60);
548 $fmt =~ s/%z/\$z/g;
549 my $ans = strftime($fmt, $S, $M, $H, $d, $m, $y, -1, -1, -1);
550 my $z;
551 if ($zonesecs < 0) {
552 $z = "-";
553 $zonesecs = -$zonesecs;
554 } else {
555 $z = "+";
557 $z .= sprintf("%02d%02d", int($zonesecs/60), $zonesecs % 60);
558 $ans =~ s/\$z/$z/g;
559 return $ans;
562 # Take a list of project names and produce a nicely formated table that
563 # includes owner links and descriptions. If the list is empty returns ''.
564 # The first argument may be a hash ref that contains options. The following
565 # options are available:
566 # target -- sets the target value of the owner link
567 # emptyok -- if true returns an empty table rather than ''
568 # sizecol -- if true include a human-readable size column
569 # typecol -- if true include type column with hover info
570 # changed -- if true include a changed and idle column
571 sub projects_html_list {
572 my $options = {};
573 if (defined($_[0]) && ref($_[0]) eq 'HASH') {
574 $options = shift;
576 return '' unless @_ || (defined($options->{emptyok}) && $options->{emptyok});
577 require Girocco::Project;
578 my $count = 0;
579 my $target = '';
580 $target = " target=\""._escapeHTML($options->{target})."\""
581 if defined($options->{target});
582 my $withsize = defined($options->{sizecol}) && $options->{sizecol};
583 my $withtype = defined($options->{typecol}) && $options->{typecol};
584 my $withchanged = defined($options->{changed}) && $options->{changed};
585 my $sizehead = '';
586 $sizehead = substr(<<EOT, 0, -1) if $withsize;
587 <th class="sizecol"><span class="hover">Size<span><span class="head" _data="Size"></span
588 /><span class="none" /><br />(</span>Fork size excludes objects borrowed from the parent.<span class="none">)</span></span></span></th
591 my $typehead = '';
592 $typehead = '<th>Type</th>' if $withtype;
593 my $chghead = '';
594 $chghead = substr(<<EOT, 0, -1) if $withchanged;
595 <th><span class="hover">Changed<span><span class="head" _data="Changed"></span
596 /><span class="none" /><br />(</span>The last time a ref change was received by this site.<span class="none">)</span></span></span></th
597 ><th><span class="hover">Idle<span><span class="head" _data="Idle"></span
598 /><span class="none" /><br />(</span>The most recent committer time in <i>refs/heads</i>.<span class="none">)</span></span></span></th
601 my $html = <<EOT;
602 <table class='projectlist'><tr valign="top" align="left"><th>Project</th>$sizehead$typehead$chghead<th class="desc">Description</th></tr>
604 my $trclass = ' class="odd"';
605 foreach (sort({lc($a) cmp lc($b)} @_)) {
606 if (Girocco::Project::does_exist($_, 1)) {
607 my $proj = Girocco::Project->load($_);
608 my $projname = $proj->{name}.".git";
609 my $projdesc = $proj->{desc}||'';
610 utf8::decode($projdesc) if utf8::valid($projdesc);
611 my $sizecol = '';
612 if ($withsize) {
613 my $psize = $proj->{reposizek};
614 $psize = undef unless defined($psize) && $psize =~ /^\d+$/;
615 $psize = 0 if !defined($psize) && $proj->is_empty;
616 if (!defined($psize)) {
617 $psize = 'unknown';
618 } elsif (!$psize) {
619 $psize = 'empty';
620 } else {
621 $psize = human_size($psize * 1024);
622 $psize =~ s/ /\&#160;/g;
624 $sizecol = '<td class="sizecol">'.$psize.'</td>';
626 my $typecol = '';
627 if ($withtype) {
628 if ($proj->{mirror}) {
629 my $url = _escapeHTML($proj->{url});
630 $typecol = substr(<<EOT, 0, -1);
631 <td class="type"><span class="hover">mirror<span class="nowrap"><span class="before" _data="$url"><span class="none"> <a href="$url" rel="nofollow">(URL)</a></span></span></span></span></td>
633 } else {
634 my $users = @{$proj->{users}};
635 $users .= ' user';
636 $users .= 's' unless @{$proj->{users}} == 1;
637 my $userlist = join(', ', sort({lc($a) cmp lc($b)} @{$proj->{users}}));
638 my $spncls = length($userlist) > 25 ? '' : ' class="nowrap"';
639 $typecol = $userlist ? substr(<<EOT, 0, -1) : substr(<<EOT, 0, -1);
640 <td class="type"><span class="hover">$users<span$spncls><br class="none" />$userlist</span></span></td>
642 <td class="type">$users</td>
646 my $changecol = '';
647 if ($withchanged) {
648 my $rel = '';
649 my $changetime = $proj->{lastchange};
650 if ($changetime) {
651 my ($ts, $tz);
652 $ts = parse_rfc2822_date($changetime, \$tz);
653 my $ct = _strftime("%Y-%m-%d %T %z", $ts, $tz);
654 $rel = "<span class=\"hover\">" .
655 _rel_age(time - $ts) .
656 "<span class=\"nowrap\"><span class=\"before\" _data=\"$changetime\"></span><span class=\"none\"><br />$ct</span></span></span>";
657 } else {
658 $rel = "no commits";
660 $changecol = substr(<<EOT, 0, -1);
661 <td class="change">$rel</td>
663 my $idletime = $proj->{lastactivity};
664 my ($idlesecs, $tz);
665 $idlesecs = parse_any_date($idletime, \$tz) if $idletime;
666 if ($idlesecs) {
667 my $idle2822 = _strftime("%a, %d %b %Y %T %z", $idlesecs, $tz);
668 my $ct = _strftime("%Y-%m-%d %T %z", $idlesecs, $tz);
669 $rel = "<span class=\"hover\">" .
670 _rel_idle(time - $idlesecs) .
671 "<span class=\"nowrap\"><span class=\"before\" _data=\"$idle2822\"></span><span class=\"none\"><br />$ct</span></span></span>";
672 } else {
673 $rel = "no commits";
675 $changecol .= substr(<<EOT, 0, -1);
676 <td class="idle">$rel</td>
679 $html .= <<EOT;
680 <tr valign="top"$trclass><td><a href="@{[url_path($Girocco::Config::gitweburl)]}/$projname"$target
681 >@{[_escapeHTML($projname)]}</td>$sizecol$typecol$changecol<td>@{[_escapeHTML($projdesc)]}</td></tr>
683 $trclass = $trclass ? '' : ' class="odd"';
684 ++$count;
687 $html .= <<EOT;
688 </table>
690 return ($count || (defined($options->{emptyok}) && $options->{emptyok})) ? $html : '';
693 my %_month_names;
694 BEGIN {
695 %_month_names = (
696 jan => 0, feb => 1, mar => 2, apr => 3, may => 4, jun => 5,
697 jul => 6, aug => 7, sep => 8, oct => 9, nov => 10, dec => 11
701 # Should be in "date '+%a, %d %b %Y %T %z'" format as saved to lastgc, lastrefresh and lastchange
702 # The leading "%a, " is optional, returns undef if unrecognized date. This is also known as
703 # RFC 2822 date format and git's '%cD', '%aD' and --date=rfc2822 format.
704 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
705 sub parse_rfc2822_date {
706 my $dstr = shift || '';
707 my $tzoff = shift || '';
708 $dstr = $1 if $dstr =~/^[^\s]+,\s*(.*)$/;
709 return undef unless $dstr =~
710 /^\s*(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})\s+([+-]\d{4})\s*$/;
711 my ($d,$b,$Y,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7);
712 my $m = $_month_names{lc($b)};
713 return undef unless defined($m);
714 my $seconds = timegm(0+$S, 0+$M, 0+$H, 0+$d, 0+$m, $Y-1900);
715 my $offset = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
716 $offset = -$offset if substr($z,0,1) eq '-';
717 $$tzoff = $offset if ref($tzoff) eq 'SCALAR';
718 return $seconds - $offset;
721 # Will parse any supported date format. Actually there are three formats
722 # currently supported:
723 # 1. RFC 2822 (uses parse_rfc2822_date)
724 # 2. RFC 3339 / ISO 8601 (T may be ' ' or '_', 'Z' is optional or may be 'UTC', ':' optional in TZ)
725 # 3. Same as #2 except no colons or hyphens allowed and hours MUST be 2 digits
726 # 4. unix seconds since epoch with optional +/- trailing TZ (may not have a ':')
727 # Returns undef if unsupported date.
728 # If the second argument is a SCALAR ref, its value will be set to the TZ offset in seconds
729 sub parse_any_date {
730 my $dstr = shift || '';
731 my $tzoff = shift || '';
732 if ($dstr =~ /^\s*([-+]?\d+)(?:\s+([-+]\d{4}))?\s*$/) {
733 # Unix timestamp
734 my $ts = 0 + $1;
735 my $off = 0;
736 if ($2) {
737 my $z = $2;
738 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
739 $off = -$off if substr($z,0,1) eq '-';
741 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
742 return $ts;
744 if ($dstr =~ /^\s*(\d{4})-(\d{2})-(\d{2})[Tt _](\d{1,2}):(\d{2}):(\d{2})(?:[ _]?([Zz]|[Uu][Tt][Cc]|(?:[-+]\d{1,2}:?\d{2})))?\s*$/ ||
745 $dstr =~ /^\s*(\d{4})(\d{2})(\d{2})[Tt _](\d{2})(\d{2})(\d{2})(?:[ _]?([Zz]|[Uu][Tt][Cc]|(?:[-+]\d{2}\d{2})))?\s*$/) {
746 my ($Y,$m,$d,$H,$M,$S,$z) = ($1,$2,$3,$4,$5,$6,$7||'');
747 my $seconds = timegm(0+$S, 0+$M, 0+$H, 0+$d, $m-1, $Y-1900);
748 defined($z) && $z ne '' or $z = 'Z';
749 $z = uc($z);
750 $z =~ s/://;
751 substr($z,1,0) = '0' if length($z) == 4;
752 my $off = 0;
753 if ($z ne 'Z' && $z ne 'UTC') {
754 $off = 60 * (60 * (0+substr($z,1,2)) + (0+substr($z,3,2)));
755 $off = -$off if substr($z,0,1) eq '-';
757 $$tzoff = $off if ref($tzoff) eq 'SCALAR';
758 return $seconds - $off;
760 return parse_rfc2822_date($dstr, $tzoff);
763 # Input is a number such as a minute interval
764 # Return value is a random number between the input and 1.25*input
765 # This can be used to randomize the update and gc operations a bit to avoid
766 # having them all end up all clustered together
767 sub rand_adjust {
768 my $input = shift || 0;
769 return $input unless $input;
770 return $input + int(rand(0.25 * $input));
773 # Open a pipe to a new sendmail process. The '-i' option is always passed to
774 # the new process followed by any addtional arguments passed in. Note that
775 # the sendmail process is only expected to understand the '-i', '-t' and '-f'
776 # options. Using any other options via this function is not guaranteed to work.
777 # A list of recipients may follow the options. Combining a list of recipients
778 # with the '-t' option is not recommended.
779 sub sendmail_pipe {
780 return undef unless @_;
781 die "\$Girocco::Config::sendmail_bin is unset or not executable!\n"
782 unless $Girocco::Config::sendmail_bin && -x $Girocco::Config::sendmail_bin;
783 my $result = open(my $pipe, '|-', $Girocco::Config::sendmail_bin, '-i', @_);
784 return $result ? $pipe : undef;
787 # Open a pipe that works similarly to a mailer such as /usr/bin/mail in that
788 # if the first argument is '-s', a subject line will be automatically added
789 # (using the second argument as the subject). Any remaining arguments are
790 # expected to be recipient addresses that will be added to an explicit To:
791 # line as well as passed on to sendmail_pipe. In addition an
792 # "Auto-Submitted: auto-generated" header is always added as well as a suitable
793 # "From:" header.
794 sub mailer_pipe {
795 my $subject = undef;
796 if (@_ >= 2 && $_[0] eq '-s') {
797 shift;
798 $subject = shift;
800 my $tolist = join(", ", @_);
801 unshift(@_, '-f', $Girocco::Config::sender) if $Girocco::Config::sender;
802 my $pipe = sendmail_pipe(@_);
803 if ($pipe) {
804 print $pipe "From: \"$Girocco::Config::name\" ",
805 "($Girocco::Config::title) ",
806 "<$Girocco::Config::admin>\n";
807 print $pipe "To: $tolist\n";
808 print $pipe "Subject: $subject\n" if defined($subject);
809 print $pipe "MIME-Version: 1.0\n";
810 print $pipe "Content-Type: text/plain; charset=utf-8\n";
811 print $pipe "Content-Transfer-Encoding: 8bit\n";
812 print $pipe "X-Girocco: $Girocco::Config::gitweburl\n"
813 unless $Girocco::Config::suppress_x_girocco;
814 print $pipe "Auto-Submitted: auto-generated\n";
815 print $pipe "\n";
817 return $pipe;
820 sub _goodval {
821 my $val = shift;
822 return undef unless defined($val);
823 $val =~ s/[\r\n]+$//s;
824 return undef unless $val =~ /^\d+$/;
825 $val = 0 + $val;
826 return undef unless $val >= 1;
827 return $val;
830 # Returns the number of "online" cpus or undef if undetermined
831 sub online_cpus {
832 my @confcpus = $^O eq "linux" ?
833 qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN) :
834 qw(NPROCESSORS_ONLN _NPROCESSORS_ONLN) ;
835 my $cpus = _goodval(get_cmd('getconf', $confcpus[0]));
836 return $cpus if $cpus;
837 $cpus = _goodval(get_cmd('getconf', $confcpus[1]));
838 return $cpus if $cpus;
839 if ($^O ne "linux") {
840 my @sysctls = qw(hw.ncpu);
841 unshift(@sysctls, qw(hw.availcpu)) if $^O eq "darwin";
842 foreach my $mib (@sysctls) {
843 $cpus = _goodval(get_cmd('sysctl', '-n', $mib));
844 return $cpus if $cpus;
847 return undef;
850 # Returns the system page size in bytes or undef if undetermined
851 # This should never fail on a POSIX system
852 sub sys_pagesize {
853 use POSIX ":unistd_h";
854 my $pagesize = sysconf(_SC_PAGESIZE);
855 return undef unless defined($pagesize) && $pagesize =~ /^\d+$/;
856 $pagesize = 0 + $pagesize;
857 return undef unless $pagesize >= 256;
858 return $pagesize;
861 # Returns the amount of available physical memory in bytes
862 # This may differ from the actual amount of physical memory installed
863 # Returns undef if this cannot be determined
864 sub sys_memsize {
865 my $pagesize = sys_pagesize;
866 if ($pagesize && $^O eq "linux") {
867 my $pages = _goodval(get_cmd('getconf', '_PHYS_PAGES'));
868 return $pagesize * $pages if $pages;
870 if ($^O ne "linux") {
871 my @sysctls = qw(hw.physmem64);
872 unshift(@sysctls, qw(hw.memsize)) if $^O eq "darwin";
873 foreach my $mib (@sysctls) {
874 my $memsize = _goodval(get_cmd('sysctl', '-n', $mib));
875 return $memsize if $memsize;
877 my $memsize32 = _goodval(get_cmd('sysctl', '-n', 'hw.physmem'));
878 return $memsize32 if $memsize32 && $memsize32 <= 2147483647;
879 if ($pagesize) {
880 my $pages = _goodval(get_cmd('sysctl', '-n', 'hw.availpages'));
881 return $pagesize * $pages if $pages;
883 return 2147483647 + 1 if $memsize32;
885 return undef;
888 sub _get_max_conf_suffixed_size {
889 my $conf = shift;
890 return undef unless defined $conf && $conf =~ /^(\d+)([kKmMgG]?)$/;
891 my ($val, $suffix) = (0+$1, lc($2));
892 $val *= 1024 if $suffix eq 'k';
893 $val *= 1024 * 1024 if $suffix eq 'm';
894 $val *= 1024 * 1024 * 1024 if $suffix eq 'g';
895 return $val;
898 sub _make_suffixed_size {
899 my $size = shift;
900 return $size if $size % 1024;
901 $size /= 1024;
902 return "${size}k" if $size % 1024;
903 $size /= 1024;
904 return "${size}m" if $size % 1024;
905 $size /= 1024;
906 return "${size}g";
909 # Return the value to pass to --window-memory= for git repack
910 # If the system memory or number of CPUs cannot be determined, returns "1g"
911 # Otherwise returns one third the available memory divided by the number of CPUs
912 # but never more than 1 gigabyte or max_gc_window_memory_size.
913 sub calc_windowmemory {
914 my $cpus = online_cpus;
915 my $memsize = sys_memsize;
916 my $max = 1024 * 1024 * 1024;
917 if ($cpus && $memsize) {
918 $max = int($memsize / 3 / $cpus);
919 $max = 1024 * 1024 * 1024 if $max >= 1024 * 1024 * 1024;
921 my $maxconf = _get_max_conf_suffixed_size($Girocco::Config::max_gc_window_memory_size);
922 $max = $maxconf if defined($maxconf) && $maxconf && $max > $maxconf;
923 return _make_suffixed_size($max);
926 # Return the value to set as core.bigFileThreshold for git repack
927 # If the system memory cannot be determined, returns "256m"
928 # Otherwise returns the available memory divided by 16
929 # but never more than 512 megabytes or max_gc_big_file_threshold_size.
930 sub calc_bigfilethreshold {
931 my $memsize = sys_memsize;
932 my $max = 256 * 1024 * 1024;
933 if ($memsize) {
934 $max = int($memsize / 16);
935 $max = 512 * 1024 * 1024 if $max >= 512 * 1024 * 1024;
937 my $maxconf = _get_max_conf_suffixed_size($Girocco::Config::max_gc_big_file_threshold_size);
938 $max = $maxconf if defined($maxconf) && $maxconf && $max > $maxconf;
939 return _make_suffixed_size($max);
942 # Return the value to use when deciding whether or not to re-calculate object deltas
943 # If there are no more than this many objects then deltas will be recomputed in
944 # order to create more efficient pack files. The new_delta_threshold value
945 # is constrained to be at least 1000 * cpu cores and no more than 100000.
946 # The default is sys_memsize rounded up to the nearest multiple of 256 MB and
947 # then 5000 per 256 MB or 50000 if we cannot determine memory size but never
948 # more than 100000 or less than 1000 * cpu cores.
949 sub calc_redeltathreshold {
950 my $cpus = online_cpus || 1;
951 if (defined($Girocco::Config::new_delta_threshold) &&
952 $Girocco::Config::new_delta_threshold =~ /^\d+/) {
953 my $ndt = 0 + $Girocco::Config::new_delta_threshold;
954 if ($ndt >= $cpus * 1000) {
955 return $ndt <= 100000 ? $ndt : 100000;
958 my $calcval = 50000;
959 my $memsize = sys_memsize;
960 if ($memsize) {
961 my $quantum = 256 * 1024 * 1024;
962 $calcval = 5000 * int(($memsize + ($quantum - 1)) / $quantum);
963 $calcval = 1000 * $cpus if $calcval < 1000 * $cpus;
964 $calcval = 100000 if $calcval > 100000;
966 return $calcval;
969 # $1 => thing to test
970 # $2 => optional directory, if given and -e "$2/$1$3", then return false
971 # $3 => optional, defaults to ''
972 sub has_reserved_suffix {
973 no warnings; # avoid silly 'unsuccessful stat on filename with \n' warning
974 my ($name, $dir, $ext) = @_;
975 $ext = '' unless defined $ext;
976 return 0 unless defined $name && $name =~ /\.([^.]+)$/;
977 return 0 unless exists $Girocco::Config::reserved_suffixes{lc($1)};
978 return 0 if defined $dir && -e "$dir/$name$ext";
979 return 1;
982 # mostly undoes effect of `use CGI::Carp qw(fatalsToBrowser);`
983 # mostly undoes effect of `use CGI::Carp qw(warningsToBrowser);`
984 sub noFatalsToBrowser {
985 delete $SIG{__DIE__};
986 delete $SIG{__WARN__};
987 undef *CORE::GLOBAL::die;
988 *CORE::GLOBAL::die = sub {
989 no warnings;
990 my $ec = $! || ($? >> 8) || 255;
991 my (undef, $fn, $li) = caller(0);
992 my $loc = " at " . $fn . " line " . $li . ".\n";
993 my $msg = "";
994 $msg = join("", @_) if @_;
995 $msg = "Died" if $msg eq "";
996 $msg .= $loc unless $msg =~ /\n$/;
997 die $msg if $^S;
998 printf STDERR "%s", $msg;
999 exit($ec);
1001 undef *CORE::GLOBAL::warn;
1002 *CORE::GLOBAL::warn = sub {
1003 no warnings;
1004 my (undef, $fn, $li) = caller(0);
1005 my $loc = " at " . $fn . " line " . $li . ".\n";
1006 my $msg = "";
1007 $msg = join("", @_) if @_;
1008 $msg = "Warning: something's wrong" if $msg eq "";
1009 $msg .= $loc unless $msg =~ /\n$/;
1010 printf STDERR "%s", $msg;
1014 # mimics Git's symref reading but only for HEAD
1015 # returns undef on failure or if HEAD is not a symbolic ref
1016 sub read_HEAD_symref {
1017 my $headpath = $_[0] . "/HEAD";
1018 if (-l $headpath) {
1019 my $rl = readlink($headpath);
1020 return defined($rl) && $rl =~ m,^refs/., ? $rl : undef;
1022 open my $fd, '<', $headpath or return undef;
1023 my $hv;
1025 local $/ = undef;
1026 $hv = <$fd>;
1028 close $fd;
1029 defined($hv) or return undef;
1030 chomp $hv;
1031 return $hv =~ m,^ref:\s*(refs/.+)$, ? $1 : undef;
1034 my $cf_unesc;
1035 BEGIN {
1036 my %escvals = (
1037 b => "\b",
1038 t => "\t",
1039 n => "\n",
1040 '"' => '"',
1041 '\\' => '\\'
1043 $cf_unesc = sub {
1044 $_[0] =~ s/\\([btn\042\\])/$escvals{$1}/g;
1045 $_[0];
1049 # mimics Git's config.c git_parse_source function behavior
1050 # returns array of arrayref of key and value
1051 # except that valueless booleans have a value of undef
1052 sub read_config_file {
1053 local $_;
1054 my ($fn, $warn) = @_;
1055 my $li = 0;
1056 my $section = "";
1057 my @vals = ();
1058 open my $fh, '<', $fn or
1059 $warn && warn("could not open \"$fn\": $!\n"), return(undef);
1060 binmode($fh);
1061 my $bad = sub {
1062 close $fh;
1063 warn "bad config line $li in file $fn\n" if $warn;
1064 return undef;
1066 while (<$fh>) {
1067 ++$li;
1068 s/(?:\r\n|\n)$//;
1069 $_ = to_utf8($_);
1070 s/^\x{feff}// if $li == 1;
1071 utf8::encode($_);
1072 if (/^\s*\[/gc) {
1073 if (/\G([.a-zA-Z0-9-]+)\]/gc) {
1074 $section = lc($1) . ".";
1075 } elsif (/\G([.a-zA-Z0-9-]*)\s+"((?:[^\042\\\n]|\\.)*)"\]/gc) {
1076 $section = lc($1) . "." .
1077 &{sub{my $x=shift; $x =~ s/\\(.)/$1/g; $x}}($2) . ".";
1078 } else {
1079 return &$bad;
1082 /\G\s+/gc;
1083 next if /\G(?:[;#]|$)/;
1084 if (/\G([a-zA-Z][a-zA-Z0-9-]*)[ \t]*/gc) {
1085 my $k = $section . lc($1);
1086 my $v;
1087 if (/\G$/) {
1088 $v = undef;
1089 } elsif (/\G=\s*/gc) {
1090 $v = "";
1091 my $qt = 0;
1093 if (/\G$/) {
1094 last if !$qt;
1095 return &$bad;
1097 if (!$qt && /\G((?:[^"\\\n;#]|\\[btn"\\])+)/gc) {
1098 my $a = $1;
1099 if (/\G[;#]/) {
1100 $_ = "";
1101 $a =~ s/\s+$//;
1103 $a =~ s/\s/ /g;
1104 $v .= &$cf_unesc($a);
1105 } elsif ($qt && /\G((?:[^"\\\n]|\\[btn"\\])+)/gc) {
1106 my $a = $1;
1107 $v .= &$cf_unesc($a);
1108 } elsif (/\G\042/gc) {
1109 $qt = !$qt;
1110 } elsif (!$qt && /\G[;#]/gc) {
1111 $_ = "";
1112 } elsif (/\G\\$/) {
1113 $_ = <$fh>;
1114 if (defined($_)) {
1115 ++$li;
1116 s/(?:\r\n|\n)$//;
1117 $_ = to_utf8($_, 1);
1118 /^\s+/gc unless $v ne "" || $qt;
1119 } else {
1120 $_ = "";
1122 } else {
1123 return &$bad;
1125 redo;
1127 } else {
1128 return &$bad;
1130 push(@vals, [$k, $v]);
1131 } else {
1132 return &$bad;
1135 close $fh;
1136 return \@vals;
1139 # Same as read_config_file except that a hashref is returned and
1140 # subsequent same-key-name values replace earlier ones.
1141 # Also valueless booleans are given the value 1
1142 sub read_config_file_hash {
1143 my $result = read_config_file(@_);
1144 return undef unless defined($result);
1145 my %config = map {($$_[0], defined($$_[1])?$$_[1]:1)} @$result;
1146 return \%config;
1149 # similar to Git's test except that GIT_OBJECT_DIRECTORY is ignored
1150 sub is_git_dir {
1151 my $gd = shift;
1152 defined($gd) && $gd ne "" && -d $gd or return undef;
1153 -d "$gd/objects" && -x "$gd/objects" or return 0;
1154 -d "$gd/refs" && -x "$gd/refs" or return 0;
1155 if (-l "$gd/HEAD") {
1156 my $rl = readlink("$gd/HEAD");
1157 defined($rl) && $rl =~ m,^refs/., or return 0;
1158 -e "$gd/HEAD" or return 1;
1160 open my $fd, '<', "$gd/HEAD" or return 0;
1161 my $hv;
1163 local $/;
1164 $hv = <$fd>;
1166 close $fd;
1167 defined $hv or return 0;
1168 chomp $hv;
1169 $hv =~ m,^ref:\s*refs/., and return 1;
1170 return $hv =~ /^[0-9a-f]{40}/;
1173 # Returns 0 for false, 1 for true, undef for unrecognized or undef
1174 # Unless the optional second argument is true in which case undef returns 1
1175 sub git_bool {
1176 defined($_[0]) or return $_[1] ? 1 : undef;
1177 my $v = lc($_[0]);
1178 return 0 if $v eq 'false' || $v eq 'off' || $v eq 'no' || $v eq '' || $v =~ /^[-+]?0+$/;
1179 return 1 if $v eq 'true' || $v eq 'on' || $v eq 'yes' || $v =~ /^[-+]?0*[1-9][0-9]*$/;
1180 return undef;