#
#    W_util.pm:            common utility routines
#
package W_util;

require Exporter;
@ISA = qw (Exporter);
@EXPORT = qw ( _et z2h check_priv );

use strict 'vars';

sub z2h {
    my $str = shift;

    use Jcode;
    $str =~ s/〖/-/g;
    $str =~ s/≥/-/g;
    my $j = Jcode->new($str);
    $str = $j->tr('０-９Ａ-Ｚａ-ｚ', '0-9A-Za-z');
    $str = $j->tr('△ˉ·〔', '@.,_');
    return $str;
}


sub _et {
    return unless defined wantarray;
    my @data = @_;
    foreach(@data) {
        chomp;
	s/&/&amp;/g;
	s/</&lt;/g;
	s/>/&gt;/g;
	s/"/&quot;/g; #"
	s/'//g; #'
        s/\s+/ /g;
    }
    return wantarray ? @data : $data[0];
}

sub check_priv {
    my ($host) = @_;

    use Socket;
    my %pprefix = ("192.168.0.0" => 16,
                   "172.16.0.0" => 12,
                   "10.0.0.0" => 8,
                   "169.254.0.0" => 16,
                   "127.0.0.0" => 8,
                   );

    my $addr = inet_aton($host);
    return undef unless($addr);
    my $u32 = unpack "N", $addr;

    foreach my $k (keys %pprefix) {
        my $bits = "1" x $pprefix{$k} . "0" x (32 - $pprefix{$k});
        my $mask = unpack "N", pack "B*", $bits;
        my $anet = join ".", unpack "CCCC", pack "N", $u32 & $mask;
        if ($anet eq $k) {
            return 1;
        }
    }
    return undef;
}

1;

__END__

=head1 NAME

W_util - utility rutines.

=head1 SYNOPSIS

    use W_util;

=head1 DESCRIPTION

some utilities.

=head1 METHODS

=over 4

=item _et ( [item] )

for CGI sanitizing.

=item check_priv ( IP )

check if IP is in private address range.

=back

=head1 SEE ALSO


=head1 AUTHOR

Tomo.M <tomoyuki at pobox.com>

=head1 COPYRIGHT

Copyright (c) 2006 Tomo.M. All rights reserved.

=cut

