3 from ctypes
import c_char_p
5 from django
.core
.validators
import ipv4_re
6 from django
.contrib
.gis
.geoip
.libgeoip
import GEOIP_SETTINGS
7 from django
.contrib
.gis
.geoip
.prototypes
import (
8 GeoIPRecord
, GeoIPTag
, GeoIP_open
, GeoIP_delete
, GeoIP_database_info
,
9 GeoIP_lib_version
, GeoIP_record_by_addr
, GeoIP_record_by_name
,
10 GeoIP_country_code_by_addr
, GeoIP_country_code_by_name
,
11 GeoIP_country_name_by_addr
, GeoIP_country_name_by_name
)
13 # Regular expressions for recognizing the GeoIP free database editions.
14 free_regex
= re
.compile(r
'^GEO-\d{3}FREE')
15 lite_regex
= re
.compile(r
'^GEO-\d{3}LITE')
17 #### GeoIP classes ####
18 class GeoIPException(Exception): pass
21 # The flags for GeoIP memory caching.
22 # GEOIP_STANDARD - read database from filesystem, uses least memory.
24 # GEOIP_MEMORY_CACHE - load database into memory, faster performance
25 # but uses more memory
27 # GEOIP_CHECK_CACHE - check for updated database. If database has been
28 # updated, reload filehandle and/or memory cache. This option
31 # GEOIP_INDEX_CACHE - just cache the most frequently accessed index
32 # portion of the database, resulting in faster lookups than
33 # GEOIP_STANDARD, but less memory usage than GEOIP_MEMORY_CACHE -
34 # useful for larger databases such as GeoIP Organization and
35 # GeoIP City. Note, for GeoIP Country, Region and Netspeed
36 # databases, GEOIP_INDEX_CACHE is equivalent to GEOIP_MEMORY_CACHE
38 # GEOIP_MMAP_CACHE - load database into mmap shared memory ( not available
41 GEOIP_MEMORY_CACHE
= 1
45 cache_options
= dict((opt
, None) for opt
in (0, 1, 2, 4, 8))
47 # Paths to the city & country binary databases.
51 # Initially, pointers to GeoIP file references are NULL.
55 def __init__(self
, path
=None, cache
=0, country
=None, city
=None):
57 Initializes the GeoIP object, no parameters are required to use default
58 settings. Keyword arguments may be passed in to customize the locations
59 of the GeoIP data sets.
61 * path: Base directory to where GeoIP data is located or the full path
62 to where the city or country data files (*.dat) are located.
63 Assumes that both the city and country data sets are located in
64 this directory; overrides the GEOIP_PATH settings attribute.
66 * cache: The cache settings when opening up the GeoIP datasets,
67 and may be an integer in (0, 1, 2, 4, 8) corresponding to
68 the GEOIP_STANDARD, GEOIP_MEMORY_CACHE, GEOIP_CHECK_CACHE,
69 GEOIP_INDEX_CACHE, and GEOIP_MMAP_CACHE, `GeoIPOptions` C API
70 settings, respectively. Defaults to 0, meaning that the data is read
73 * country: The name of the GeoIP country data file. Defaults to
74 'GeoIP.dat'; overrides the GEOIP_COUNTRY settings attribute.
76 * city: The name of the GeoIP city data file. Defaults to
77 'GeoLiteCity.dat'; overrides the GEOIP_CITY settings attribute.
79 # Checking the given cache option.
80 if cache
in self
.cache_options
:
83 raise GeoIPException('Invalid GeoIP caching option: %s' % cache
)
85 # Getting the GeoIP data path.
87 path
= GEOIP_SETTINGS
.get('GEOIP_PATH', None)
88 if not path
: raise GeoIPException('GeoIP path must be provided via parameter or the GEOIP_PATH setting.')
89 if not isinstance(path
, basestring
):
90 raise TypeError('Invalid path type: %s' % type(path
).__name
__)
92 if os
.path
.isdir(path
):
93 # Constructing the GeoIP database filenames using the settings
94 # dictionary. If the database files for the GeoLite country
95 # and/or city datasets exist, then try and open them.
96 country_db
= os
.path
.join(path
, country
or GEOIP_SETTINGS
.get('GEOIP_COUNTRY', 'GeoIP.dat'))
97 if os
.path
.isfile(country_db
):
98 self
._country
= GeoIP_open(country_db
, cache
)
99 self
._country
_file
= country_db
101 city_db
= os
.path
.join(path
, city
or GEOIP_SETTINGS
.get('GEOIP_CITY', 'GeoLiteCity.dat'))
102 if os
.path
.isfile(city_db
):
103 self
._city
= GeoIP_open(city_db
, cache
)
104 self
._city
_file
= city_db
105 elif os
.path
.isfile(path
):
106 # Otherwise, some detective work will be needed to figure
107 # out whether the given database path is for the GeoIP country
109 ptr
= GeoIP_open(path
, cache
)
110 info
= GeoIP_database_info(ptr
)
111 if lite_regex
.match(info
):
112 # GeoLite City database detected.
114 self
._city
_file
= path
115 elif free_regex
.match(info
):
116 # GeoIP Country database detected.
118 self
._country
_file
= path
120 raise GeoIPException('Unable to recognize database edition: %s' % info
)
122 raise GeoIPException('GeoIP path must be a valid file or directory.')
125 # Cleaning any GeoIP file handles lying around.
126 if self
._country
: GeoIP_delete(self
._country
)
127 if self
._city
: GeoIP_delete(self
._city
)
129 def _check_query(self
, query
, country
=False, city
=False, city_or_country
=False):
130 "Helper routine for checking the query and database availability."
131 # Making sure a string was passed in for the query.
132 if not isinstance(query
, basestring
):
133 raise TypeError('GeoIP query must be a string, not type %s' % type(query
).__name
__)
135 # GeoIP only takes ASCII-encoded strings.
136 query
= query
.encode('ascii')
138 # Extra checks for the existence of country and city databases.
139 if city_or_country
and not (self
._country
or self
._city
):
140 raise GeoIPException('Invalid GeoIP country and city data files.')
141 elif country
and not self
._country
:
142 raise GeoIPException('Invalid GeoIP country data file: %s' % self
._country
_file
)
143 elif city
and not self
._city
:
144 raise GeoIPException('Invalid GeoIP city data file: %s' % self
._city
_file
)
146 # Return the query string back to the caller.
149 def city(self
, query
):
151 Returns a dictionary of city information for the given IP address or
152 Fully Qualified Domain Name (FQDN). Some information in the dictionary
153 may be undefined (None).
155 query
= self
._check
_query
(query
, city
=True)
156 if ipv4_re
.match(query
):
157 # If an IP address was passed in
158 return GeoIP_record_by_addr(self
._city
, c_char_p(query
))
160 # If a FQDN was passed in.
161 return GeoIP_record_by_name(self
._city
, c_char_p(query
))
163 def country_code(self
, query
):
164 "Returns the country code for the given IP Address or FQDN."
165 query
= self
._check
_query
(query
, city_or_country
=True)
167 if ipv4_re
.match(query
):
168 return GeoIP_country_code_by_addr(self
._country
, query
)
170 return GeoIP_country_code_by_name(self
._country
, query
)
172 return self
.city(query
)['country_code']
174 def country_name(self
, query
):
175 "Returns the country name for the given IP Address or FQDN."
176 query
= self
._check
_query
(query
, city_or_country
=True)
178 if ipv4_re
.match(query
):
179 return GeoIP_country_name_by_addr(self
._country
, query
)
181 return GeoIP_country_name_by_name(self
._country
, query
)
183 return self
.city(query
)['country_name']
185 def country(self
, query
):
187 Returns a dictonary with with the country code and name when given an
188 IP address or a Fully Qualified Domain Name (FQDN). For example, both
189 '24.124.1.80' and 'djangoproject.com' are valid parameters.
191 # Returning the country code and name
192 return {'country_code' : self
.country_code(query
),
193 'country_name' : self
.country_name(query
),
196 #### Coordinate retrieval routines ####
197 def coords(self
, query
, ordering
=('longitude', 'latitude')):
198 cdict
= self
.city(query
)
199 if cdict
is None: return None
200 else: return tuple(cdict
[o
] for o
in ordering
)
202 def lon_lat(self
, query
):
203 "Returns a tuple of the (longitude, latitude) for the given query."
204 return self
.coords(query
)
206 def lat_lon(self
, query
):
207 "Returns a tuple of the (latitude, longitude) for the given query."
208 return self
.coords(query
, ('latitude', 'longitude'))
210 def geos(self
, query
):
211 "Returns a GEOS Point object for the given query."
212 ll
= self
.lon_lat(query
)
214 from django
.contrib
.gis
.geos
import Point
215 return Point(ll
, srid
=4326)
219 #### GeoIP Database Information Routines ####
221 def country_info(self
):
222 "Returns information about the GeoIP country database."
223 if self
._country
is None:
224 ci
= 'No GeoIP Country data in "%s"' % self
._country
_file
226 ci
= GeoIP_database_info(self
._country
)
231 "Retuns information about the GeoIP city database."
232 if self
._city
is None:
233 ci
= 'No GeoIP City data in "%s"' % self
._city
_file
235 ci
= GeoIP_database_info(self
._city
)
240 "Returns information about the GeoIP library and databases in use."
242 if GeoIP_lib_version
:
243 info
+= 'GeoIP Library:\n\t%s\n' % GeoIP_lib_version()
244 return info
+ 'Country:\n\t%s\nCity:\n\t%s' % (self
.country_info
, self
.city_info
)
246 #### Methods for compatibility w/the GeoIP-Python API. ####
248 def open(cls
, full_path
, cache
):
249 return GeoIP(full_path
, cache
)
251 def _rec_by_arg(self
, arg
):
253 return self
.city(arg
)
255 return self
.country(arg
)
256 region_by_addr
= city
257 region_by_name
= city
258 record_by_addr
= _rec_by_arg
259 record_by_name
= _rec_by_arg
260 country_code_by_addr
= country_code
261 country_code_by_name
= country_code
262 country_name_by_addr
= country_name
263 country_name_by_name
= country_name