#!/usr/bin/perl -w
#
# Joshua D. Abraham ( jabra @ spl0it.org )
#
# Copyright (C) 2008 Joshua D. Abraham (jabra@spl0it.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 2 of the License, or
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Find the Longitude and Latitude of a BSSID 
#
use strict;
use LWP::UserAgent;
use Data::Dumper;
use XML::LibXML;
my $parser = XML::LibXML->new();
sub usage {
    print "Usage: $0 [bssid]\n";
    exit;
}
my $mac = uc($ARGV[0]) or usage();
$mac =~ s/\://g;
if  ( length($mac) != 12) {
    print "Error: wrong size MAC\n";
    exit;
}
my $url = 'https://api.skyhookwireless.com/wps2/location';
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;

sub parse_response {
    my ($response) = @_;
    my $xml = $response->content;
    $xml =~ s/\n//g;
    my $doc = $parser->parse_string($xml);
    if ( defined(@{$doc->getElementsByTagName('longitude')}[0]) and defined(@{$doc->getElementsByTagName('latitude')}[0]) ) {
        print "Longitude: \t" . @{$doc->getElementsByTagName('longitude')}[0]->textContent . "\n";
        print "Latitude: \t" . @{$doc->getElementsByTagName('latitude')}[0]->textContent . "\n";
    }
    else {
        print "Cant find location of $mac\n";
    }
}

sub request {
    my $str = "<?xml version='1.0'?>  
 <LocationRQ xmlns='http://skyhookwireless.com/wps/2005' version='2.6' street-address-lookup='full'>  
   <authentication version='2.0'>  
     <simple>  
       <username>beta</username>  
       <realm>js.loki.com</realm>  
     </simple>  
   </authentication>  
   <access-point>  
     <mac>$mac</mac>  
     <signal-strength>-50</signal-strength>  
   </access-point>  
 </LocationRQ>";
    my $response = $ua->post( $url, 'Content-Type' => 'text/xml', Content => $str );
    parse_response($response);
}
request();
