aboutsummaryrefslogtreecommitdiff
path: root/whoseip/whoseip.pl
blob: d64280e39351b361b6e9d33daec6a906834d7051 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
#! /usr/bin/perl
# Copyright (C) 2014 Sergey Poznyakoff <gray@gnu.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use Getopt::Long qw(:config gnu_getopt no_ignore_case);
use IO::Socket;
use Pod::Usage;
use Pod::Man;
use Socket qw(:DEFAULT :crlf inet_ntoa);
use Net::CIDR;
use Whoseip::DB qw(:all);

use constant EX_OK           => 0;
use constant EX_USAGE        => 64;    # command line usage error
use constant EX_DATAERR      => 65;    # data format error
use constant EX_NOINPUT      => 66;    # cannot open input file
use constant EX_SOFTWARE     => 70;    # internal software error (not used yet)
use constant EX_OSFILE       => 72;    # critical OS file missing
use constant EX_CANTCREAT    => 73;    # can't create (user) output file

my $progname;      # This script name;
($progname = $0) =~ s/.*\///;

my $progdescr = "Identifies IP addresses";
my $debug;
my @ipv4list;

my $ipv4rx = '\d{1,3}((\.\d{1,3}){3})';
my $delim = $LF;   # Output delimiter

my $dbf;
my $dbfile;

my %fmtab = (unix => '${status} $?{diag}{${diag}}{${country} ${cidr} ${range} ${count}}
',
             cgi => 'Content-Type: text/xml

<?xml version="1.0" encoding="US-ASCII"?>
<whoseip xmlns:whoseip="http://man.gnu.org.ua/8/whoseip">
  <whoseip:status>${status}</whoseip:status>
  $?{diag}{<whoseip:diag>${diag}</whoseip:diag>}{<whoseip:country>${country}</whoseip:country>
  <whoseip:cidr>${cidr}</whoseip:cidr>
  <whoseip:range>${range}</whoseip:range>
  <whoseip:count>${count}</whoseip:count>}
  $?{term}{<whoseip:term>${term}</whoseip:term>}
</whoseip>
'
);

sub error {
    my $msg = shift;
    local %_ = @_;
    print STDERR "$progname: " if defined($progname);
    print STDERR "$_{prefix}: " if defined($_{prefix});
    print STDERR "$msg\n"
}

sub debug {
    my $l = shift;
    error(join(' ',@_), prefix => 'DEBUG') if $debug >= $l;
}

sub abend {
    my $code = shift;
    print STDERR "$progname: " if defined($progname);
    print STDERR "@_\n";
    exit $code;
}

sub read_config_file($) {
    my $config_file = shift;
    print STDERR "reading $config_file\n" if ($debug);
    open(my $fd, "<", $config_file) or die("cannot open $config_file: $!");
    while (<$fd>) {
        chomp;

        s/\s+$//;

	if (/\\$/) {
	    chop;
	    $_ .= <$fd>;
	    redo;
	}

        s/^\s+//;
        s/\s+=\s+/=/;
        s/#.*//;
        next if ($_ eq "");
        unshift(@ARGV, "--$_");
    }
    close $fd;
}

sub read_ipv4list {
    my $file = shift;
    open(my $fd, "<", $file)
	or abend(EX_NOINPUT, "can't open $file for reading: $!");
    my $line = 0;
    @ipv4list = ();
    while (<$fd>) {
	++$line;
	chomp;
	s/#.*//;
	s/^\s+//;
	s/\s+$//;
	next if ($_ eq "");

	unless (/^([\d\.]+)\/(\d+)\s+([\w\.]+)$/) {
	    error("$file:$line: malformed line");
	    next;
	}
	my $srv = $3;
	next if $srv eq 'UNKNOWN';
	my $msk = $2;
	my $ip = str2ipv4($1);
	$srv = "whois.$srv.net" unless ($srv =~ /\./);

	push @ipv4list, [ $ip,
			  (0xffffffff^(0xffffffff>>$msk)),
			  $srv ];
    }

    close $fd;
}

sub str2ipv4 {
    my $ipstr = shift;
    my @ip = split(/\./, $ipstr);
    return ($ip[0] << 24) + ($ip[1] << 16) + ($ip[2] << 8) + $ip[3];
}

sub range2count {
    my $count = 0;
    foreach my $arg (@_) {
	my @a = split /-/, shift;
	next unless $#a == 1;
	$count += str2ipv4($a[1]) - str2ipv4($a[0]) + 1;
    }
    return $count;
}

sub cidr_to_range {
    my @a;

    @a = sort { $a->[0] <=> $b->[0] }
         map {
	     map { [ map { str2ipv4($_) } split(/-/, $_, 2) ] }
	         Net::CIDR::cidr2range($_) 
	 } split /,/, shift;
    
    for (my $i = 1; $i <= $#a; $i++) {
	if ($a[$i]->[0] == $a[$i-1]->[1] + 1) {
	    $a[$i-1]->[1] = $a[$i]->[1];
	    splice @a, $i, 1;
	}
    }
    
    return join ',', map { inet_ntoa(pack('N', $_->[0])) . '-' .
			       inet_ntoa(pack('N', $_->[1])) } @a;
}

# ############
# ARIN
# ############
sub arin_fmt {
    my $q = shift;
    return "n + $q";
}

sub arin_decode {
    my ($input, $ref) = @_;

    return if ($input =~ /^#/ or $input eq '');

    if ($input =~ /^NetRange:\s+(.+)/) {
	my $r = $1;
	$r =~ s/\s+//g;
	my $n = range2count($r);
	if (!defined($ref->{count}) or $ref->{count} > $n) {
	    $ref->{range} = $r;
	    $ref->{cidr} = join ',', Net::CIDR::range2cidr($r);
	    $ref->{count} = $n;
	    delete $ref->{country}
	}
    } elsif ($input =~ /^Country:\s+(.+)/ and !defined($ref->{country})) {
	$ref->{country} = $1;
    }
}

# ############
# RIPE
# ############
use constant RIPE_INIT => 0;
use constant RIPE_TEXT => 1;
use constant RIPE_IGNR => 2;

sub ripe_decode {
    my ($input, $ref) = @_;

    return if ($input =~ /^%/);

    if ($ref->{state} == RIPE_INIT) {
	if ($input eq '') {
	    return;
	} else {
	    $ref->{state} = RIPE_TEXT;
	}
    }

    if ($ref->{state} == RIPE_TEXT) {
	if ($input =~ /^inetnum:\s+(.+)/) {
	    my $r = $1;
	    $r =~ s/\s+//g;
	    $ref->{range} = $r;
	    $ref->{count} = range2count($r);
	    $ref->{cidr} = join ',', Net::CIDR::range2cidr($r);
	} elsif ($input =~ /^country:\s+(.+)/) {
	    $ref->{country} = $1;
	} elsif ($input eq '') {
	    $ref->{state} = RIPE_IGNR;
	}
    }
}

# ############
# LACNIC
# ############
sub lacnic_decode {
    my ($input, $ref) = @_;

    return if ($input =~ /^%/);

    if ($ref->{state} == RIPE_INIT) {
	if ($input eq '') {
	    return;
	} else {
	    $ref->{state} = RIPE_TEXT;
	}
    }

    if ($ref->{state} == RIPE_TEXT) {
	if ($input =~ /^inetnum:\s+(.+)/) {
	    my $cidr = $1;
	    if ($cidr =~ m#^(\d{1,3})/(\d+)#) {
		$cidr = "$1.0.0.0/$2";
	    } elsif ($cidr =~ m#^(\d{1,3}\.\d{1,3})/(\d+)#) {
		$cidr = "$1.0.0/$2";
	    } elsif ($cidr =~ m#^(\d{1,3}\.\d{1,3}\.\d{1,3})/(\d+)#) {
		$cidr = "$1.0/$2";
	    }
	    $ref->{cidr} = $cidr;
	    $ref->{range} = cidr_to_range($cidr);
	    $ref->{count} = range2count($ref->{range});
	} elsif ($input =~ /^country:\s+(.+)/) {
	    $ref->{country} = $1;
	} elsif ($input eq '') {
	    $ref->{state} = RIPE_IGNR;
	}
    }
}

# ###################
# rwhois.gin.ntt.net
# ###################
sub ntt_decode {
    my ($input, $ref) = @_;
    if ($input =~ /^\s+(${ipv4rx}\s*-\s*${ipv4rx})/) {
	my $r = $1;
	$r =~ s/\s+//g;
	my $c = range2count($r);
	if (!defined($ref->{count}) or $ref->{count} > $c) {
	    $ref->{count} = $c;
	    $ref->{range} = $r;
	    $ref->{cidr} = join ',', Net::CIDR::range2cidr($r);
	    $ref->{country} = 'US';
	}
    }
}

# ############
# TWNIC
# ############
sub twnic_decode {
    my ($input, $ref) = @_;
    if ($input =~ /^\s+Netblock:\s+(.+)/) {
	my $r = $1;
	$r =~ s/\s+//g;
	$ref->{range} = $r;
	$ref->{count} = range2count($r);
	$ref->{cidr} = join ',', Net::CIDR::range2cidr($r);
	$ref->{country} = 'TW';
    }
}

###################
# whois.nic.ad.jp
###################
sub nic_ad_jp_fmt {
    my $q = shift;
    return "NET $q/e";
}

sub nic_ad_jp_decode {
    my ($input, $ref) = @_;
    if ($input =~ /^a\.\s+\[Network Number\]\s+(.+)/) {
	$ref->{cidr} = $1;
	$ref->{range} = cidr_to_range($ref->{cidr});
	$ref->{count} = range2count($ref->{range});
	$ref->{country} = 'JP';
    }
}

###################
# whois.nic.or.kr
###################
sub nic_or_kr_decode {
    my ($input, $ref) = @_;
    if ($input =~ /^IPv4 Address\s*:\s+(${ipv4rx}\s*-\s*${ipv4rx})/) {
	my $r = $1;
	$r =~ s/\s+//g;
	my $c = range2count($r);
	if (!defined($ref->{count}) or $ref->{count} > $c) {
	    $ref->{count} = $c;
	    $ref->{range} = $r;
	    $ref->{cidr} = join ',', Net::CIDR::range2cidr($r);
	    $ref->{country} = 'KR';
	}
    }
}

sub nobistech_decode {
    my ($input, $ref) = @_;

    if ($input =~ /network:IP-Network:(.+)/) {
	$ref->{cidr} = $1;
	$ref->{range} = cidr_to_range($1);
	$ref->{count} = range2count($ref->{range});
    } elsif ($input =~ /network:Country-Code:(.+)/) {
	$ref->{country} = $1;
    }
}

	
# #######################################################################
# Server table
# #######################################################################

my %srvtab = (
    'whois.arin.net' => { q => \&arin_fmt,  d => \&arin_decode },
    'whois.lacnic.net' => { d => \&lacnic_decode },
    'whois.ripe.net' => { d => \&ripe_decode },
    'rwhois.gin.ntt.net' => { d => \&ntt_decode },
    'whois.twnic.net' => { d => \&twnic_decode },
    'whois.nic.ad.jp' => { q => \&nic_ad_jp_fmt, d => \&nic_ad_jp_decode },
    'whois.nic.br' => { d => \&lacnic_decode },
    'whois.nic.or.kr' => { d => \&nic_or_kr_decode },
    'rwhois.nobistech.net' => { d => \&nobistech_decode }
);

sub format_query {
    my ($srv, $term) = @_;
    if (defined($srvtab{$srv}{q})) {
	return &{$srvtab{$srv}{q}}($term);
    } else {
	return $term;
    }
}

sub findsrv {
    my $ip = str2ipv4(shift);

    foreach my $r (@ipv4list) {
	debug(3, "findsrv: $ip $r->[0]/$r->[1]");
	return $r->[2] if ($ip & $r->[1]) == $r->[0];
    }
    return undef;
}

sub whois($$) {
    my $ip = shift;
    my $server = shift;
    my $port = 43;

    if ($server =~ /(.+):(.+)/) {
	$server = $1;
	$port = $2;
    }

    debug(1,"querying $ip from $server:$port");

    my $sock = new IO::Socket::INET (PeerAddr => $server,
				     PeerPort => $port,
				     Proto => 'tcp');
    my $expiration = undef;
    my @collect;

    unless ($sock) {
	error("could not connect to $server:$port: $!");
	return undef;
    }

    print $sock format_query($server, $ip)."\n";
    my $decode;
    if (defined($srvtab{$server}{d})) {
	$decode = $srvtab{$server}{d};
    } else {
	$decode = \&ripe_decode;
    }

    local $/ = LF;
    my %res;
    while (<$sock>) {
	chomp;
	debug(4, "RECV: $_");
	if (/%% referto: whois -h (\S+) -p (\S+)/) {
	    $res{referto} = "$1:$2";
	    debug(1, "found reference to $res{referto}"); 
	} elsif (m#ReferralServer: r?whois://(.+)#) {
	    $res{referto} = $1;
	    $res{referto} =~ s#/$##;
	    debug(1, "found reference to $res{referto}"); 
	} else {
	    &{$decode}($_, \%res);
	}
    }
    close $sock;
#    while (my ($k,$v) = each %res) {
#	print "$k $v\n";
#    }
    return %res;
}

sub serve {
    my $term = shift;
    my %res;

    if ($term =~ /^${ipv4rx}$/) {
	if (defined($dbf)) {
	    %res = ipdb_lookup($dbf, $term);
	    if (defined($res{country})) {
		$res{status} = 'OK';
		unless (defined($res{cidr})) {
		    $res{cidr} = Net::CIDR::addrandmask2cidr($res{network},
							     $res{netmask});
		}
		$res{range} = cidr_to_range($res{cidr});
		$res{count} = range2count($res{range});
                $res{term} = $term;
                $res{source} = 'CACHE';
		return %res;
	    }
	}

	my $srv = findsrv($term);
	if (defined($srv) and $srv ne 'UNKNOWN') {
	    my %prev;
	    while (%res = whois($term, $srv),
		   and defined($res{referto})) {
		%prev = %res if $res{status} = 'OK';
		$srv = $res{referto};
	    }
	    %res = %prev
		if (!defined($res{country}) and defined($prev{country}));
	    if (!defined($res{country})) {
		$res{status} = 'NO';
		$res{diag} = 'IP unknown';
	    } else {
		$res{status} = 'OK';
		if (defined($dbf)) {
		    foreach my $cidr (split /,/, $res{cidr}) {
			ipdb_insert($dbf, $cidr, $res{country}, cidr=>$res{cidr});
		    }
		}
	    }
	} else {
	    $res{status} = 'NO';
	    $res{diag} = 'whois server unknown';
	}
    } else {
	$res{status} = 'BAD';
	$res{diag} = 'invalid input';
    }
    $res{source} = 'QUERY';
    $res{term} = $term;
    return %res;
}

# #######################################################################
# Create a copy of this program with ipv4list embedded
# #######################################################################
sub whoseip_dump {
    my ($opt,$file) = @_;

    open(my $ifd, "<", $0)
	or abend(EX_NOINPUT, "can't open $0 for reading");
    open(my $ofd, ">", $file)
	or abend(EX_CANTCREAT, "can't open $file for writing");
    my $zapto;
    my $line = 0;
    while (<$ifd>) {
	++$line;
	if (defined($zapto)) {
	    $zapto = undef if /$zapto/;
	    next;
	}
	if (/^my \@ipv4list\s*(.*)/) {
	    my $tail = $1;
	    if ($tail =~ /^=\s*\(/) {
		$zapto = '^\);$';
	    } elsif ($tail !~ /^;/) {
		error("$file:$line: unrecognized @ipv4list initializer");
		print $ofd $_;
		next;
	    }
	    print $ofd "my \@ipv4list = (\n";
	    foreach my $x (@ipv4list) {
		print $ofd "[ $x->[0], $x->[1], '$x->[2]' ],\n";
	    }
	    print $ofd ");\n";
	} else {
	    print $ofd $_;
	}
    }
    close $ifd;
    close $ofd;
    exit 0;
}

# #######################################################################
# Output functions
# #######################################################################

sub read_format {
    my $file = shift;
    open(my $fd, "<", $file)
	or die "can't open $file for reading";
    my $res;
    while (<$fd>) {
	chomp;
	if (/\\$/) {
	    chop;
	    $_ .= <$fd>;
	    redo;
	}
	next if /^#/;
	$res .= "$_\n";
    }
    close $fd;
    return $res;
}

sub getsegm {
    my $sref = shift;
    my $s = ${$sref};
    my $level = 0;
    my $res;
    while ($s =~ /(.*?[{}])(.*)/s) {
	$res .= $1;
	$s = $2;
	if ($res =~ /[\$\?l]\{$/s) {
	    if ($s =~ /(\w+\})(.*)/s) {
		$res .= $1;
		$s = $2;
	    }
	} elsif ($res =~ /{$/) {
	    ++$level;
	} elsif ($res =~ /}$/) {
	    last if (--$level == 0);
	}
    }
    ${$sref} = $s;
    $res =~ s/^\{//s;
    $res =~ s/\}$//s;
    return $res;
}

sub output {
    my $s = shift;
    my %esctab = (a => "\a",
		  b => "\b",
		  e => "\e",
		  f => "\f",
		  n => "\n",
		  r => "\r",
		  t => "\t",
		  v => "\v");
    $s =~ s/\$l{(\w+)\}/length($_{$1})/sgex;
    $s =~ s/\$\{(\w+)\}/$_{$1}/sgex;
    $s =~ s/\\([\\abefnrtv])/$esctab{$1}/sgex;
    print $s;
}

sub format_out {
    my $fmt = shift;
    local %_ = @_;

    while ($fmt =~ /(.*?)\$\?\{(\w+)\}(.*)/s) {
	output($1);
	my $v = $2;
	$fmt = $3;
	my $t = getsegm(\$fmt);
	my $f;
	$f = getsegm(\$fmt) if ($fmt =~ /^\{/);
	if (defined($_{$v})) {
	    format_out($t, @_);
	} elsif (defined($f)) {
	    format_out($f, @_);
	}
    }
    output($fmt);
}

sub docgi {
    my ($fmt, $env) = @_;
    my $term;
    my %res;
    
    if ($env->{QUERY_STRING} =~ /^$ipv4rx$/) {
	$term = $env->{QUERY_STRING};
    } else {
	my %q = map { /(.+?)=(.*)/ ? ($1 => $2) : ($1 => 1); } 
                    split(/\&/, $env->{QUERY_STRING});
	if (defined($q{fmt})) {
	    if (defined($fmtab{$q{fmt}})) {
		if ($fmtab{$q{fmt}} =~ /^Content-Type:/) {
		    $fmt = $fmtab{$q{fmt}};
		} else {
		    %res = (status => 'BAD', diag => 'invalid format')
		}
	    } else {
		%res = (status => 'BAD', diag => 'format undefined');
	    }
        }
	$term = $q{ip} if defined($q{ip});
    }
    unless (defined($res{status})) {
	if (defined($term)) {
	    %res = serve($term);
	} else {
	    %res = (status => 'BAD', diag => 'search term invalid or missing');
	}
    }
    format_out($fmt, %res);
}

# #######################################################################
# Main
# #######################################################################

my $output_format;
my $fastcgi;
my $single_query;

if (defined($ENV{WHOSEIP_CONF})) {
    read_config_file($ENV{WHOSEIP_CONF});
} elsif (-r "/etc/whoseip.conf") {
    read_config_file("/etc/whoseip.conf");
}

GetOptions("h" => sub {
		    pod2usage(-message => "$progname: $progdescr",
			      -exitstatus => 0);
	   },
	   "help" => sub {
		    pod2usage(-exitstatus => EX_OK, -verbose => 2);
	   },
	   "usage" => sub {
		    pod2usage(-exitstatus => EX_OK, -verbose => 0);
	   },
	   "debug|d+" => \$debug,
	   "ip-list|i=s" => sub { read_ipv4list($_[1]); },
	   "dump|D=s" => \&whoseip_dump,
           "define-format=s" => sub {
		my @a = split /\s*=\s*/, $_[1], 2;
		$fmtab{$a[0]} = $a[1];
	    },
           "format|f=s" => \$output_format,
           "format-file|formfile|F=s" => sub {
		if ($_[1] =~ /=/) {
		    my @a = split /\s*=\s*/, $_[1], 2;
		    $fmtab{$a[0]} = read_format($a[1]);
		} else {
		    $output_format = read_format($_[1]); 
	        }
	   },
           "fastcgi:s" => \$fastcgi,
           "cache-file|c:s" => \$dbfile,
           "no-cache|N" => sub { $dbfile = undef; },
           "single-query" => \$single_query
) or exit(EX_USAGE);

if (defined($dbfile)) {
    $dbfile .= "whoseip.db" if (-d $dbfile);
    $dbf = ipdb_open($dbfile, debug => $debug);
}

if (defined($fastcgi)) {
    if ($fastcgi eq '') {
        $fastcgi = 1;
    } else {
        my @suf = split /\s+/, $fastcgi;
        $fastcgi = undef;
        foreach my $s (@suf) {
            if ($0 =~ /$s$/) {
                $fastcgi = 1;
                last;
            }
        }
    }
} else {
    $fastcgi = $0 =~ /\.fcgi$/;
}

if (defined($output_format) and $output_format =~ /@(.+)/) {
    abend(EX_USAGE, "format $1 not defined") unless defined $fmtab{$1};
    $output_format = $fmtab{$1};
}

if ($fastcgi) {
    eval {
        require FCGI;
        1;
    } or do {
        my $msg = $@;
        if ($debug) {
            abend(EX_OSFILE, "can't load CGI::Fast: $@");
        } else {
            abend(EX_OSFILE, "can't load CGI::Fast");
        }
    };

    $output_format = $fmtab{cgi} unless defined($output_format);
    my $req = FCGI::Request();
    while ($req->Accept() >= 0) {
	docgi($output_format, $req->GetEnvironment());
    }
} elsif ($ENV{GATEWAY_INTERFACE} =~ m#CGI/\d+\.\d+#) {
    $output_format = $fmtab{cgi} unless defined($output_format);
    docgi($output_format, \%ENV);
} else {
    my $term;
    my %res;

    ipdb_locker($dbf, lock => 'shared') if (defined($dbf));
    $output_format = $fmtab{unix} unless defined($output_format);
    if ($#ARGV == -1) {
	unless (-t *STDIN) {
	    local $/ = CRLF;
	    $delim = "$CR$LF";
	}
        my $n = 1;
        while (<>) {
            chomp;
	    format_out($output_format, serve($_), item => $n++);
            last if $single_query;
        }
    } else {
        my $n = 1;
	foreach my $term (@ARGV) {
	    format_out($output_format, serve($term), item => $n++);
	}
    }
}

ipdb_close($dbf) if defined($dbf);

__END__
=head1 NAME

whoseip - return information about IP address

=head1 SYNOPSIS

B<whoiseip>
[B<-dhN>]
[B<-F> I<FILE>]    
[B<-D> I<FILE>]
[B<-i> I<FILE>]
[B<--cache-file=>I<FILE>]
[B<--debug>]
[B<--define-format=>I<NAME>B<=>I<TEXT>]
[B<--dump=>I<FILE>]
[B<--fastcgi=>[I<SUFFIX...>]]
[B<--format=>I<TEXT>]
[B<--format-file=>[I<NAME>B<=>]I<FILE>]
[B<--formfile=>I<FILE>]
[B<--help>]
[B<--ip-list=>I<FILE>]
[B<--no-cache>]
[B<--single-query>]    
[B<--usage>] 
[I<IPADDR>...]    

=head1 DESCRIPTION

For each IP address, B<whoseip> returns the country it is located in
(a ISO 3166-1 code), the network it belongs to and the number of addresses
in the network.

The program can operate in several modes.

If the program name ends in B<.fcgi> the B<Fast CGI> mode is enabled.
This mode is also enabled if the command line option B<--fastcgi> is
given without arguments, or if the program name ends in one of the
suffixes supplied in the argument to this option (a whitespace-separated
list).  In this mode, the the IP address to look for is taken from the
parameter B<ip>.  Additional parameter B<fmt> can be used to supply the
name of the desired output format.  The format must be either one of
the built-in formats, or must be defined using the B<--define-format>
option (see below).  As a shortcut, the invocation command line containing
an IP alone is also recognized.    
    
Otherwise, when one or more IP addresses are given in the command line,
B<whoseip> prints the data for each of them on the standard output.
This is B<command line> mode.

If called without arguments, the program checks if the environment variable
B<GATEWAY_INTERFACE> is defined and contains B<CGI/I<V>> (where I<V> is the
version number).  If so, it assumes B<CGI> mode.  In this mode the command
line is parsed the same way as in B<Fast CGI> mode.

If B<GATEWAY_INTERFACE> is not set, the program reads IP addresses from
input (one per line) and prints replies for each of them.  This is B<inetd
mode>.

To summarize:

=over 4

=item 1.

Start it from the command line with one or more IPs given as arguments, if
you wish to get info about these IPs.

=item 2.

Add it to B</etc/inetd.conf> if you want to query it remotely as a service,
e.g.:

    whois stream tcp nowait nobody /usr/bin/whoseip

=item 3.

Copy it to your B<cgi-bin> directory to use it with a B<http> server as a
B<CGI>.

=item 4.

Link it to B<whoseip.fcgi> to use it as a B<FastCGI> application (or use
the B<--fastcgi> option).

=back    

Output formats are configurable and depend on the mode B<whoseip> runs
in.  In command line and inetd modes, the default output format is:

=over 4
    
B<OK> I<COUNTRY> I<CIDR> I<RANGE> I<COUNT>

=back

where I<COUNTRY> is country code, I<CIDR> is network block in CIDR notation,
I<RANGE> is network block as a range of IP addresses, and I<COUNT> is
number of IP address in the network block.

If the specified IP address is not found, the reply is

=over 4

B<NO> I<TEXT>

=back

where I<TEXT> is a human-readable explanatory message.

If the input is invalid, the reply is:    

=over 4

B<BAD> I<TEXT>

=back

In B<CGI> and B<FastCGI> modes, the output is represented as XML, as
shown in the example below:    

    <?xml version="1.0" encoding="US-ASCII"?>
    <whoseip xmlns:whoseip="http://man.gnu.org.ua/8/whoseip">
      <whoseip:status>OK</whoseip:status>
      <whoseip:country>US</whoseip:country>
      <whoseip:cidr>192.0.2.0/24</whoseip:cidr>
      <whoseip:range>192.0.2.0-192.0.2.255</whoseip:range>
      <whoseip:count>255</whoseip:count>
      <whoseip:term>192.0.2.10</whoseip:term>
    </whoseip>

The following example illustrates the reply if the IP is not found:

    <?xml version="1.0" encoding="US-ASCII"?>
    <whoseip xmlns:whoseip="http://man.gnu.org.ua/8/whoseip">
      <whoseip:status>NO</whoseip:status>
      <whoseip:diag>IP unknown</whoseip:diag>
      <whoseip:term>43.0.0.1</whoseip:term>
   </whoseip>
    
See the section B<FORMAT> below for a discussion on how to customize
output formats.
    
=head1 OPTIONS

=over 4

=item B<--cache-file=>I<FILE>

Cache retrieved data in file I<FILE>.    

=item B<-D>, B<--dump=>I<FILE>

Dump the program to I<FILE>.  This is normally done to update the
built-in server list, e.g.:

     whoseip --ip-list=ip_del_list --dump=whoseip.new

Note, that B<--dump> must be last option in the command line.
    
=item B<-d>, B<--debug>

Increase debugging verbosity.

=item B<--define-format=>I<NAME>B<=>I<TEXT>

Define a named format I<NAME> to be I<TEXT>.  Two names are predefined:
format B<cgi> is used to respond to B<CGI> or B<FastCGI> requests, and
format B<unix> is used when serving requests coming from command line or
in inetd mode.  See the section B<FORMAT>, for a detailed discussion.
    
=item B<--fastcgi=>[I<SUFFIX...>]

When used without argument, forces FastCGI mode.  If an argument is given,
it is treated as a whitespace-separated list of suffixes.  In this case,
FastCGI mode is enabled if the program name ends in one of these suffixes.

If this option is not give, FastCGI is enabled if the program name ends
in B<.fcgi>.

=item B<-f>, B<--format=>I<STRING>

Sets output format string.  If I<STRING> begins with a B<@>, it is
a reference to a named format string (either built-in one or a one
created using the B<--define-format> option), and is replaced with
the value of the format referred to.  For example, B<--format=@cgi>
instructs the program to use B<cgi> format.
    
=item B<-F>, B<--formfile>, B<--format-file=>[I<NAME>B<=>]I<FILE>

Read output format string from I<FILE>.  If I<NAME> is supplied, assign the
format string to the named format.  See the section B<FORMAT>, for a
detailed discussion.
    
=item B<-i>, B<--ip-list=>I<FILE>

Read the table of B<whois> servers from I<FILE>.  Each line in I<FILE>
must have the following format:

I<CIDR> I<SERVER>    

Comments are introduced with a B<#> sign.  Empty lines are ignored.

Without this option, B<whoseip> uses the built-in list of servers.

=item B<-N>, B<--no-cache>

Disable caching (this is the default).

=item B<--single-query>

This option is valid only in B<inetd mode>.  It instructs B<whoseip> to
terminate after replying to the first query.

=back

The following options cause the program to display informative text and
exit:

=over 4

=item B<-h>

Show a short usage summary.

=item B<--help>

Show man page.

=item B<--usage>

Show a concise command line syntax reminder.

=back    

=head1 CONFIGURATION FILE

If the file B</etc/whoseip.conf> exists, it is read before processing
command line options.  If the environment variable B<WHOSEIP_CONF> is
set, its value is used as the file name, instead of B</etc/whoseip.conf>.

The file is read line by line.  Long lines can be split over several
physical lines by inserting a backslash followed by a newline.  Empty
lines are ignored.  Comments are introduced with the B<#> character.
Anything following it up to the logical line is ignored.

Each non-empty line must contain a single long command line option,
without the leading B<-->.  Arguments must be separated from options
with an equals sign, optionally surrounded with whitespace.

For example:

    # Assume FastCGI if the program name ends in one of these
    # suffixes
    fastcgi = .fcgi .pl
    # Define output format for CGI and FastCGI modes
    define-format  =  cgi=Content-Type: application/json\n\
    \n\
    { "status": "${status}", \
    $?{diag}{"diag": "${diag}"}{\
     "country": "${country}",\
     "cidr": "${cidr}",\
     "range": "${range}",\
     "count": "${count}"}\
    $?{term}{, "term": "${term}" } }\n

=head1 FORMAT

Output formats can be redefined using B<--define-format>, B<--format>,
and B<--format-file> command line options, or corresponding configuration
file keywords.

The format string supplied with this options (or in the input file, in
case of the B<--format-file> option) can contain the following macro
references, which are replaced with the corresponding piece of information
on output:

=over 4

=item B<${status}>

The reply status: B<OK>, if the information has been retrieved,
B<NO>, if it was not, and B<BAD>, if the input was invalid.

=item B<${diag}>

Contains explanatory text if B<${status}> is B<NO> or B<BAD>.  If
it is B<OK>, this macro is not defined.

=item B<${item}>

Ordinal number of the request being served.  Not defined in B<CGI> and
B<FastCGI> modes.

=item B<${term}>

The input IP address.

=item B<${cidr}>

The network IP belongs to, as a B<CIDR>.

=item B<${range}>

The network, as a range of IP addresses.

=item B<${count}>

Number of IP addresses in the network.

=item B<${country}>

ISO 3166-1 code of the country where IP address is located.

=item B<${source}>

Where the information was obtained from.  B<QUERY>, if it was retrieved
from a remote B<whois> server and B<CACHE>, if it was read from the
cache database.

=back

If a macro is not defined, the corresponding reference expands to 
empty string.

Conditional expressions evaluate depending on whether a macro is defined.
The syntax of a conditional expression is:

=over 4

B<$?{I<NAME>}>B<{>I<TEXT-IF-TRUE>B<}>B<{>I<TEXT-IF-FALSE>B<}>

=back

Its effect is as follows: if the macro I<NAME> is defined, the
I<TEXT-IF-TRUE> is substituted, otherwise the I<TEXT-IF-FALSE>
is substituted.  Conditional expressions can be nested.

The escape sequences B<\a>, B<\b>, B<\e>, B<\f>, B<\n>, B<\r>,
B<\t>, and B<\v> are replaced according to their traditional
meaning.

=head1 BUGS

Only IPv4 is supported.    

=head1 AUTHOR

Sergey Poznyakoff <gray@gnu.org>

=cut
    

Return to:

Send suggestions and report system problems to the System administrator.