00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028 #include <QFile>
00029 #include <QDir>
00030 #include <QTextStream>
00031 #include <util/string.h>
00032 #include <util/file.h>
00033 #include <vidalia.h>
00034
00035 #include "geoipcache.h"
00036
00037
00038
00039 #define CACHE_FILENAME (Vidalia::dataDirectory() + "/geoip-cache")
00040
00041
00042
00043 GeoIpCache::GeoIpCache()
00044 {
00045 loadFromDisk();
00046 }
00047
00048
00049 QString
00050 GeoIpCache::cacheFilename()
00051 {
00052 return CACHE_FILENAME;
00053 }
00054
00055
00056 bool
00057 GeoIpCache::saveToDisk(QString *errmsg)
00058 {
00059
00060 if (!create_path(Vidalia::dataDirectory())) {
00061 return false;
00062 }
00063
00064
00065 QFile tmpCacheFile(CACHE_FILENAME + ".tmp");
00066 if (!tmpCacheFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
00067 return err(errmsg, tmpCacheFile.errorString());
00068 }
00069
00070
00071 QTextStream cache(&tmpCacheFile);
00072 foreach (GeoIpCacheItem cacheItem, _cache.values()) {
00073
00074 if (!cacheItem.isExpired()) {
00075 cache << cacheItem.toString() << endl;
00076 }
00077 }
00078
00079 QFile cacheFile(CACHE_FILENAME);
00080
00081 if (cacheFile.exists()) {
00082
00083 if (!cacheFile.remove()) {
00084 return err(errmsg, cacheFile.errorString());
00085 }
00086 }
00087
00088 if (tmpCacheFile.rename(cacheFile.fileName())) {
00089 return err(errmsg, tmpCacheFile.errorString());
00090 }
00091 return true;
00092 }
00093
00094
00095
00096 bool
00097 GeoIpCache::loadFromDisk(QString *errmsg)
00098 {
00099 QFile cacheFile(CACHE_FILENAME);
00100
00101 if (cacheFile.exists()) {
00102
00103 if (!cacheFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
00104 return err(errmsg, cacheFile.errorString());
00105 }
00106
00107
00108 QTextStream cache(&cacheFile);
00109 QString line = cache.readLine();
00110 while (!line.isNull()) {
00111
00112 GeoIpCacheItem item = GeoIpCacheItem::fromString(line);
00113 if (!item.isEmpty() && !item.isExpired()) {
00114
00115 _cache.insert(item.ip().toIPv4Address(), item);
00116 }
00117 line = cache.readLine();
00118 }
00119 }
00120 return true;
00121 }
00122
00123
00124
00125 void
00126 GeoIpCache::cache(GeoIp geoip)
00127 {
00128
00129 _cache.insert(geoip.ip().toIPv4Address(),
00130 GeoIpCacheItem(geoip,QDateTime::currentDateTime()));
00131 }
00132
00133
00134 GeoIp
00135 GeoIpCache::geoip(QHostAddress ip)
00136 {
00137 if (this->contains(ip)) {
00138 return _cache.value(ip.toIPv4Address()).geoip();
00139 }
00140 return GeoIp();
00141 }
00142
00143
00144
00145 bool
00146 GeoIpCache::contains(QHostAddress ip)
00147 {
00148 quint32 ipv4 = ip.toIPv4Address();
00149 if (_cache.contains(ipv4)) {
00150 GeoIpCacheItem cacheItem = _cache.value(ipv4);
00151 return !cacheItem.isExpired();
00152 }
00153 return false;
00154 }
00155