Vidalia 0.2.12

GeoIpResolver.cpp

Go to the documentation of this file.
00001 /*
00002 **  This file is part of Vidalia, and is subject to the license terms in the
00003 **  LICENSE file, found in the top level directory of this distribution. If you
00004 **  did not receive the LICENSE file with this file, you may obtain it from the
00005 **  Vidalia source package distributed by the Vidalia Project at
00006 **  http://www.vidalia-project.net/. No part of Vidalia, including this file,
00007 **  may be copied, modified, propagated, or distributed except according to the
00008 **  terms described in the LICENSE file.
00009 */
00010 
00011 /*
00012 ** \file GeoIpResolver.cpp
00013 ** \brief Retrieves GeoIP information either from Tor or from a local
00014 ** database and returns the result.
00015 */
00016 
00017 #include "GeoIpResolver.h"
00018 #include "GeoIpRecord.h"
00019 #include "Vidalia.h"
00020 
00021 
00022 /** Default constructor. */
00023 GeoIpResolver::GeoIpResolver(QObject *parent)
00024   : QObject(parent), _useLocalDatabase(false)
00025 {
00026 }
00027 
00028 bool
00029 GeoIpResolver::setLocalDatabase(const QString &databaseFile)
00030 {
00031 #if defined(USE_GEOIP)
00032   return _database.open(databaseFile);
00033 #else
00034   return false;
00035 #endif
00036 }
00037 
00038 void
00039 GeoIpResolver::setUseLocalDatabase(bool useLocalDatabase)
00040 {
00041   _useLocalDatabase = useLocalDatabase;
00042 }
00043 
00044 GeoIpRecord
00045 GeoIpResolver::resolveUsingTor(const QHostAddress &ip)
00046 {
00047   QString countryCode = Vidalia::torControl()->ipToCountry(ip);
00048   if (! countryCode.isEmpty()) {
00049     QPair<float,float> coords = CountryInfo::countryLocation(countryCode);
00050     return GeoIpRecord(ip, coords.first, coords.second,
00051                        CountryInfo::countryName(countryCode),
00052                        countryCode);
00053   }
00054   return GeoIpRecord();
00055 }
00056 
00057 GeoIpRecord
00058 GeoIpResolver::resolveUsingLocalDatabase(const QHostAddress &ip)
00059 {
00060 #if defined(USE_GEOIP)
00061   if (_database.type() == GeoIpDatabase::CityDatabase) {
00062     return _database.recordByAddr(ip);
00063   } else {
00064     QString countryCode = _database.countryCodeByAddr(ip);
00065     if (! countryCode.isEmpty()) {
00066       QPair<float,float> coords = CountryInfo::countryLocation(countryCode);
00067       return GeoIpRecord(ip, coords.first, coords.second, 
00068                          CountryInfo::countryName(countryCode),
00069                          countryCode);
00070     }
00071   }
00072 #endif
00073   return GeoIpRecord();
00074 }
00075 
00076 /** Resolves a single IP to a geographic location. */
00077 GeoIpRecord
00078 GeoIpResolver::resolve(const QHostAddress &ip)
00079 {
00080 #if defined(USE_GEOIP)
00081   if (_useLocalDatabase)
00082     return resolveUsingLocalDatabase(ip);
00083 #endif
00084   return resolveUsingTor(ip); 
00085 }
00086